Click here to Skip to main content
Click here to Skip to main content
Go to top

WinForm DataGridView Loading from objectcollection

, 30 Nov 2011
Rate this:
Please Sign up or sign in to 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;

License

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

Share

About the Author

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

Comments and Discussions

 
GeneralMy vote of 4 PinmemberExplainy3-May-12 9:32 
QuestionAutogenerateColumnNames PinmemberO. Vencovsky5-Dec-11 20:54 
AnswerRe: AutogenerateColumnNames Pinmembermohanaitec5-Dec-11 23:34 

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.140916.1 | Last Updated 30 Nov 2011
Article Copyright 2011 by mohanaitec
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid