DotNet Friends

December 3, 2008

Convert Generic List In To DataTable

Create simple asp.net application with C#. Add new class (GenericToDataTable).

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;

public class GenericToDataTable
{
/// <summary>
/// Default Constructor
/// </summary>
private GenericToDataTable()
{ }
/// <summary>
///
/// </summary>
/// <typeparam name=”T”>Custome Class </typeparam>
/// <param name=”lst”>List Of The Custome Class</param>
/// <returns> Return the class datatbl </returns>
public static DataTable ConvertTo<T>(IList<T> lst)
{
//create DataTable Structure
DataTable tbl = CreateTable<T>();
Type entType = typeof(T);

PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entType);
//get the list item and add into the list
foreach (T item in lst)
{
DataRow row = tbl.NewRow();
foreach (PropertyDescriptor prop in properties)
{
row[prop.Name] = prop.GetValue(item);
}
tbl.Rows.Add(row);
}

return tbl;
}

/// <summary>
///
/// </summary>
/// <typeparam name=”T”>Custome Class</typeparam>
/// <returns></returns>
public static DataTable CreateTable<T>()
{
//T –> ClassName
Type entType = typeof(T);
//set the datatable name as class name
DataTable tbl = new DataTable(entType.Name);
//get the property list
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entType);
foreach (PropertyDescriptor prop in properties)
{
//add property as column
tbl.Columns.Add(prop.Name, prop.PropertyType);
}
return tbl;
}
}

after add above class compile the code.

after compilation add new class into project (Class Name: clsUser).

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// Summary description for clsUser
/// </summary>
public class clsUser
{
//create property userid
private int _UserId;
public int UserID
{
get { return _UserId; }
set { _UserId = value; }
}
//create property username
private string _UserName;
public string UserName
{
get { return _UserName; }
set { _UserName = value; }
}
/// <summary>
/// Default Constructor
/// </summary>
public clsUser()
{ }

public clsUser(int userid,string username)
{
this.UserID = userid;
this.UserName = username;
}
}

After adding this class into project go to Default.aspx page in this page type below code on Page Load event.

//create generic list of class clsUser
System.Collections.Generic.List<clsUser> obj = new
System.Collections.Generic.List<clsUser>();
//add data into list
for (int i = 0; i < 10; i++)
{
obj.Add(new clsUser(i,”a”+i.ToString()));
}
//convert list to datatable
DataTable dt= GenericToDataTable.ConvertTo<clsUser>(obj);

now check the DataTable(dt).

thnx

10 Comments »

  1. hi Patriwala,

    excellent stuff…! u kept it simple…

    Thanks a million…….!!!!!!!!!!

    Comment by petter — December 11, 2008 @ 9:51 am

    • Hi petter,
      Thanks For your valuable comment.

      thnx

      Comment by patriwala — December 11, 2008 @ 9:53 am

  2. Very useful

    Comment by DotNetter — February 10, 2009 @ 9:50 pm

  3. thank you very much about your example.

    Comment by trungqt84 — April 17, 2009 @ 2:53 pm

  4. Excellent Guruuuuuuuuuuuuuuuu !!

    Comment by Irfan — April 29, 2009 @ 10:45 am

  5. Very useful article..

    Comment by Jemson Sentillas — April 29, 2009 @ 7:23 pm

  6. Excellent post.. It helpmed a lot in time… Really superb.

    I have got an error in CreateTable method. Err is “DataSet does not support System.Nullable”. Solution for this is before adding the column to the table just do a check as below.

    Type colType = prop.PropertyType;
    if ((colType.IsGeneric­Type) && (colType.GetGeneric­TypeDefinition() == typeof(Nullable))­)
    {
    colType = colType.GetGenericA­rguments()[0];
    }
    destTable.Columns.A­dd(new DataColumn(prop.Nam­e, colType));

    Correct me if am wrong. Hope this helps someone.

    Thanks.

    Comment by Sakthi — June 19, 2009 @ 8:59 am

  7. Great post. Ran into same issue as Sakthi with nullable type. Here is what worked for me:

    Type colType = prop.PropertyType;
    if ((colType.IsGenericType))
    {
    colType = colType.GetGenericArguments()[0];
    }
    tb.Columns.Add(prop.Name, colType);

    Comment by Perry — July 2, 2009 @ 3:28 pm

  8. awesome

    Comment by vijeya — July 23, 2009 @ 4:22 pm

  9. Great site…keep up the good work.

    Comment by Dryer Vent Cleaning — September 19, 2009 @ 4:37 am


RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.