Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically create DataGridview from DataTable

I have the following code:

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;

When I examine grid, the DataSource attribute indicates that the number of rows is correct. However, the grid.Rows count is zero.

In contrast, if I create a DataGridView on a winform, and then assign its DataSource to a DataTable, the DataGridView.Rows will be added automatically.

What code am I missing here, in order to have the DataGridView.Rows count correct?

like image 499
Joe Sisk Avatar asked Nov 22 '13 20:11

Joe Sisk


1 Answers

By adding this DataGridView control to the form programmatically it works :) Anybody would tell us why?

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;
like image 123
GrzegorzM Avatar answered Sep 29 '22 09:09

GrzegorzM