WinForm DataGridView Loading from objectcollection





4.00/5 (1 vote)
WinForm DataGridView loading from ObjectCollection.
Th following tip/trick will help you create/load the datasource of a DataGridView
with very little effort to create Rows/Columns using Reflection. It is a reusuable piece of code across multiple Forms and/or DataGridView
controls. But think of requiring custom names for the columns before using this tip, since this creates column header(s) with just property name(s).
//Create and Add columns to the DataTable.
foreach (FieldInfo field in ((object)myObject).GetType().GetFields())
{
myTable.Columns.Add(new DataColumn(field.Name));
}
//Load DataTable
DataRow dr;
foreach (Class item in ObjectCollection)
{
//Create a new Row for each item in the collection.
dr = myTable.NewRow();
foreach (FieldInfo field in ((object)item).GetType().GetFields())
{
//Set Column value
dr[field.Name] = field.GetValue(item);
}
myTable.Rows.Add(dr);
}
//Set the Data Source of the Grid.
gridView.DataSource = myTable;