简体   繁体   中英

Cannot see rows in unbound DataGridView

I'm trying to pass an unbound DataGridView to a form, and cannot get the rows to appear, even though the Rows.Count value is correct. I feel like I'm missing something obvious.

// method code
// Create an DataGridView
DataGridView dgv = new DataGridView();
dgv.Columns.Add("Name","Name");
dgv.Columns.Add("Comments", "Comments");

// Add rows to datagridview
int n = dgv.Rows.Add();
dgv.Rows[n].Cells["Name"].Value = "a test name";
dgv.Rows[n].Cells["Comments"].Value = "some comment";

// Pass DataGridView to form
test_PassingDataGridView f = new test_PassingDataGridView();
f.DataGridTest = dgv;
f.ShowDialog();


// test_PassingDataGridView form code
DataGridView _datagridtest;
public DataGridView DataGridTest
{
    get { return _datagridtest; }
    set { _datagridtest = value; }
}

public test_PassingDataGridView()
{
    InitializeComponent();
}

private void test_PassingDataGridView_Load(object sender, EventArgs e)
{
    this.dataGridView1 = _datagridtest; // _datagridtest.Rows.Count is correct at this point
} 

Don't pass the DataGridView to the form. Put a DataGridView on the form in the designer and then pass a DataTable to the form and have the form bind the DataTable to the DataGridView .

By creating the DataGridView as you have you're missing a lot of properties that would often be set in the designer. You can make it work by setting the properties, particularly position and size, but even then it's really bad form to pass controls around like that. Pass data instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM