以编程方式从DataTable创建DataGridview

Joe*_*isk 7 c# datagridview winforms

我有以下代码:

DataTable table = new DataTable();

//DataTable is filled with values here...

DataGridView grid = new DataGridView();

foreach (DataColumn column in table.Columns)
{
    grid.Columns.Add(column.ColumnName, column.ColumnName);
}

grid.DataSource = table;
Run Code Online (Sandbox Code Playgroud)

当我检查时grid,该DataSource属性表明行数是正确的.但是,grid.Rows计数为零.

相反,如果我DataGridView在winform上创建一个,然后将其分配DataSource给a DataTable,DataGridView.Rows则会自动添加.

我在这里错过了什么代码,以便DataGridView.Rows计算正确?

Grz*_*rzM 5

通过DataGridView以编程方式将此控件添加到表单,它可以工作:)任何人都会告诉我们为什么?

DataTable table = new DataTable();

//DataTable is filled with values here...

DataGridView grid = new DataGridView();

// assuming (this) is a reference to the current form
this.Controls.Add(grid);

grid.DataSource = table;
Run Code Online (Sandbox Code Playgroud)