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

Advertisements

20 comments

  1. hi Patriwala,

    excellent stuff…! u kept it simple…

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

    1. Hi petter,
      Thanks For your valuable comment.

      thnx

  2. DotNetter · · Reply

    Very useful

  3. thank you very much about your example.

  4. Excellent Guruuuuuuuuuuuuuuuu !!

  5. Jemson Sentillas · · Reply

    Very useful article..

  6. Sakthi · · Reply

    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.

  7. Perry · · Reply

    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);

  8. vijeya · · Reply

    awesome

  9. Dryer Vent Cleaning · · Reply

    Great site…keep up the good work.

  10. outstanding ….

  11. not too clear. however ok

  12. custom web applications · · Reply

    Wow! very nice and neatly done.
    really useful since I use a lot of generics with my gridviews and they don’t support sorting/paging etc.
    converting them to datatables obviously sorted all those problems!
    well done and thanks!

  13. Thank you very much!!

    Nice and clean solution.
    Very usefull!

  14. Hey This is a nice example. But can you please give an example for converting DataTable into Generic List.

  15. Thank you very much.Really nice example

  16. This Really Helped Me Alot !,after so much google found this.

    Thanks Techie !

  17. Mustapha · · Reply

    It’s a very useful example. I tested it. It works successfully. Thanks!

  18. this is saved me alot.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s