Click here to Skip to main content
15,884,629 members
Articles / Desktop Programming / Windows Forms
Tip/Trick

WinForm DataGridView Loading from objectcollection

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
30 Nov 2011CPOL 20.7K   7   3
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)


Written By
Computer Sciences Corporation
India India
Thanks,
Mohan Ayyavu,
Senior Engineer - Application Development,
Computer Sciences Corporation,
Chennai, IND.

Comments and Discussions

 
GeneralMy vote of 4 Pin
Explainy3-May-12 9:32
Explainy3-May-12 9:32 
QuestionAutogenerateColumnNames Pin
O. Vencovsky5-Dec-11 20:54
O. Vencovsky5-Dec-11 20:54 
AnswerRe: AutogenerateColumnNames Pin
mohanaitec5-Dec-11 23:34
mohanaitec5-Dec-11 23:34 
Yes.. But by default it will generate columns for all the properties. If any Array object is present in the Datasource object, then there will be a column in the grid with the value as namespace of the item in the array.

This can be filtered out using IsArray property which is exposed by FieldInfo.

Likewise, the same AutoGeneration can be much more customized.


Thanks. Smile | :)

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.