Click here to Skip to main content
14,237,088 members

WinForm DataGridView Loading from objectcollection

Rate this:
4.00 (1 vote)
Please Sign up or sign in to vote.
4.00 (1 vote)
30 Nov 2011CPOL
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);


//Set the Data Source of the Grid.
gridView.DataSource = myTable;


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


About the Author

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

Comments and Discussions

GeneralMy vote of 4 Pin
Explainy3-May-12 9:32
memberExplainy3-May-12 9:32 
QuestionAutogenerateColumnNames Pin
O. Vencovsky5-Dec-11 20:54
memberO. Vencovsky5-Dec-11 20:54 
AnswerRe: AutogenerateColumnNames Pin
mohanaitec5-Dec-11 23:34
membermohanaitec5-Dec-11 23:34 

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.

Posted 30 Nov 2011


7 bookmarked