Click here to Skip to main content
13,260,108 members (47,159 online)
Click here to Skip to main content
Add your own
alternative version

Stats

16K views
7 bookmarked
Posted 30 Nov 2011

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.

You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 4 Pin
Explainy3-May-12 10:32
memberExplainy3-May-12 10:32 
QuestionAutogenerateColumnNames Pin
O. Vencovsky5-Dec-11 21:54
memberO. Vencovsky5-Dec-11 21:54 
AnswerRe: AutogenerateColumnNames Pin
mohanaitec6-Dec-11 0:34
membermohanaitec6-Dec-11 0: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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.171114.1 | Last Updated 30 Nov 2011
Article Copyright 2011 by mohanaitec
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid