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

20 responses to “Convert Generic List In To DataTable”

  1. petter Avatar
    petter

    hi Patriwala,

    excellent stuff…! u kept it simple…

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

    1. patriwala Avatar

      Hi petter,
      Thanks For your valuable comment.

      thnx

  2. DotNetter Avatar
    DotNetter

    Very useful

  3. trungqt84 Avatar

    thank you very much about your example.

  4. Irfan Avatar
    Irfan

    Excellent Guruuuuuuuuuuuuuuuu !!

  5. Jemson Sentillas Avatar
    Jemson Sentillas

    Very useful article..

  6. Sakthi Avatar
    Sakthi

    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 Avatar
    Perry

    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 Avatar
    vijeya

    awesome

  9. Dryer Vent Cleaning Avatar
    Dryer Vent Cleaning

    Great site…keep up the good work.

  10. leo Avatar
    leo

    outstanding ….

  11. V.V. Avatar
    V.V.

    not too clear. however ok

  12. custom web applications Avatar
    custom web applications

    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. Florian Avatar
    Florian

    Thank you very much!!

    Nice and clean solution.
    Very usefull!

  14. Dhara Avatar
    Dhara

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

  15. Chandra Prakash Avatar

    Thank you very much.Really nice example

  16. james Avatar
    james

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

    Thanks Techie !

  17. Mustapha Avatar
    Mustapha

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

  18. raj Avatar
    raj

    this is saved me alot.

Leave a Reply

Discover more from The Engineering Behind Enterprise AI

Subscribe now to keep reading and get access to the full archive.

Continue reading