Click here to Skip to main content
Click here to Skip to main content

Convert .NET Class to a DataGrid

, 18 Jul 2005
Rate this:
Please Sign up or sign in to vote.
Create a DataGrid from an ArrayList which is a collection of a specific class type. Read all attributes of a class in a nested hierarchy and create datacolumns from that or just select a few attributes as datacolumns and ignore others. Have unique readable datacolumn names finally in the datatable.


Everywhere you would see the OOPS concept and emphasizing you to work the oops, but ask anyone how to create a DataGrid from an ArrayList which is a collection of same class type, you will find people saying go for DataSet or create DataTable rows from these ArrayList items. I too faced the same problem when I was asked to design a DataGrid and what I got from the C# team was just an ArrayList.

I'm damn sure, one of you who is reading this article would say that it is still possible in DataGrid and one can use the "." operator, but if I ask you how to do sorting and paging on them, and what if the item is inside the ArrayList then you might not have any answer.

I am not saying this is 100% right, but this is one of the easiest ways of converting an ArrayList (which is a collection of a specific class type) to a DataTable, where you can have sorting, paging and filtering on the DataGrid. Since whatever DataTable you form finally has valid column names.


What is with us?

ArrayList - arrEmployees 
 Item[0] - (Type EmployeeCmpnt)
 Item[1] - (Type EmployeeCmpnt)
 Item[2] - (Type EmployeeCmpnt)

EmployeeCmpnt structure

What we want?

If the first item of the ArrayList contains following
 Employeecmpnt.NameCmpnt.FirstName = "John"
 Employeecmpnt.NameCmpnt.LastName = "Abraham"
 Employeecmpnt.HomeAddress.AddressDetailsCmpnt.Address1 = 
                                      "1520 Magnolia Apts"
and the second item contains following
 Employeecmpnt.NameCmpnt.FirstName = "Peter"
 Employeecmpnt.NameCmpnt.LastName = "Paul"
 Employeecmpnt.HomeAddress.AddressDetailsCmpnt.Address1 = 
                                       "1870 Meridan Pkwy"

The expected DataGrid output is shown below

Implementing the approach

FYI The DataTable column names finally when it is implemented

You can see that every hierarchy is separated by double underscores "__". Please note that it is the exposed attribute name and not the type which is used. (I mean to say that it is the "HomeAddress" that is used and not the type "AddressCmpnt".)

Steps to convert an ArrayList to a DataGrid

In .cs

ArrayList arrEmployee = new ArrayList();
//Fill data in arrEmployee
arrEmployee.Add(new EmployeeCmpnt("Peter",
//Create instance of grid utility class 
GridViewClass gridView = new GridViewClass();
//Create specific columns (DataColumns) OR 
//create all attributes of a class 
//as column (AutoNestedColumns)
//Set all attributes as data columns //ALL OF THE ATTRIBUTES, 
                                     //MAXIMUM SIZE.
gridView.AutoNestedColumns = true;
//Create specific columns //LESS COLUMNS, LESS DATATABLE SIZE
//gridView.DataColumns  = "EmployeeCmpnt__NameCmpnt__FirstName,
//Call the CreateDataTable() method which does the conversion job.
DataTable dtEmployee = gridView.CreateDataTable(arrEmployee);
dgEmployee.DataSource = dtEmployee;

In .aspx

<asp:TemplateCOLUMN HeaderText="First Name" 
    SortExpression='EmployeeCmpnt__NameCmpnt__FirstName'  >
     <asp:Label id="Label8"  style="text-align:left" 
         Runat="server" Text='<%# DataBinder.Eval(Container, 
             "DataItem.EmployeeCmpnt__NameCmpnt__FirstName") %>' />

How it is done

It is the method CreateDataTable() which through reflection finds out the type of the class, its attributes and loops through all the nested children and creates a DataTable. Click here to see the code of GridView.cs.

Can I have paging and sorting?

Yeah sure! That's why all this trouble was taken, since the DataTable column names are valid names you can straightaway use them in the "SortExpression" of DataGrid.

protected void dgEmployee_Sort(Object sender, 
                   DataGridSortCommandEventArgs e)
  dtEmployee.DefaultView.Sort = e.SortExpression; 
  dgEmployee.DataSource = dtEmployee;

Can I use this in my custom ASP Grid control and use it the way I want

Definitely, you can add a method "CreateDataTable()" to your DataGrid custom control and can have two exposed attributes like "DataColumns" and "AutoNestedColumns" which can take further inputs. E.g.:

public class MyDataGrid : System.Web.UI.WebControls.DataGrid
  public string DataColumns
    get... set...
  public bool AutoNestedColumns
    get... set...
  public DataTable CreateDataTable(..)

By the way, you will be happy to know that I have already done this and will soon post my custom DataGrid in my next article but only if I get a good rating for my current article Smile | :) , moreover, I needed this submission to explain how a DataGrid can be created from a collection of classes.

You know the custom DataGrid control I'm talking about has features like multi column sorting, freezing headers/rows/columns etc. and that too in a very easy way.


You may use the code given here by any means and in whatever way you want, but I will truly appreciate if you keep the author's name along with the code.


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Tittle Joseph
Team Leader Royal Bank of Scotland
India India
Total 11+ years of experience in Software Development. Expertise in .net (C#,, controls making, webservice,, xml/xsl, assemblies, rational XDE etc.) also UML, Design Patterns, ASP, Javascript, VbScript, Dhtml, CSS etc.
Member of, and many other and have submitted several snippets/sample applications on the web.

Comments and Discussions

GeneralRe: select a row within the datagrid problem PinmemberTittle Joseph4-Aug-05 5:11 
GeneralRe: select a row within the datagrid problem PinmemberTittle Joseph4-Aug-05 23:48 
GeneralRe: select a row within the datagrid problem PinmemberTipi Sha5-Aug-05 12:22 
GeneralA Beginner's Question Pinmemberdocrob127-Jul-05 6:16 
I was happy to find your project, since I'm working on just such a solution. I don't have web hosting on my computer, so I tried to make a C# form to test the code. In the context of a standard Windows Form project that has a DataGrid "dataGrid1", I have the following code:
DataTable DT=new DataTable();
TestClass TC=new TestClass();
ArrayList TCAL=new ArrayList();
GridViewClass GV= new GridViewClass();
Where "TestClass" is defined as:
public class TestClass
public string LastName;
public string FirstName;
public string SSN;
It compiles and runs without errors, but the datatable is empty. When I follow your class through the debugger, it gets to the point where you have the comment "// Loop through all the properties..." and the fromObj.GetType().GetProperties() code returns nothing.
Can you tell me what I've done wrong?
Thank you for your time.
GeneralRe: A Beginner's Question PinmemberTittle Joseph27-Jul-05 19:58 
GeneralRe: A Beginner's Question Pinmemberdocrob128-Jul-05 4:31 
GeneralRe: A Beginner's Question Pinmemberdocrob128-Jul-05 4:55 
GeneralRe: A Beginner's Question PinmemberTittle Joseph28-Jul-05 23:23 
GeneralWaiting for comment !! PinsussTittle Joseph18-Jul-05 20:56 
GeneralRe: Waiting for comment !! PinsussAnonymous19-Jul-05 14:09 

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 | Terms of Use | Mobile
Web03 | 2.8.150327.1 | Last Updated 19 Jul 2005
Article Copyright 2005 by Tittle Joseph
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid