Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / WinForms

WinForm DataGridView Loading from objectcollection

4.00/5 (1 vote)
30 Nov 2011CPOL 21K  
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).


C#
//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;

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)