How to convert List to DataTable - C#,ASP.NET

Short Description

This example will show how to convert List<T> where T could be any object and convert the List<T> to DataTable. The example will use two class which is System.ComponentModel; and System.Data;

Note : The Convertion class extention method must be in static because System.ComponentModel.TypeDescriptor is a static method

In this example i will use asp.net .

The ASPX page

     <h1>
        How to convert List To DataTable
    </h1>
    <asp:GridView ID="GridView1" runat="server">
    </asp:GridView>


The Code Behind

       protected void Page_Load(object sender, EventArgs e)
        {
            List<string> listOfString = new List<string>();
            for (int i = 0; i < 10; i++)
            {
                listOfString.Add(i.ToString());
            }           
            GridView1.DataSource = Convertion.ToDataTable<string>(listOfString);
            GridView1.DataBind();
        }


The Convertion Class

    public static class Convertion
    {
        public static DataTable ToDataTable<T>(this IList<T> data)
        {
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
            DataTable table = new DataTable();
            foreach (PropertyDescriptor prop in properties)
            {
                table.Columns.Add(prop.Name, (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() ==
                    typeof(Nullable)) ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType);
                foreach (T item in data)
                {
                    DataRow row = table.NewRow();
                    foreach (PropertyDescriptor _prop in properties)
                    {
                        row[_prop.Name] = item;
                        table.Rows.Add(row);
                    }
                }
            }
            return table;
        }
    }


The Output


By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)

Popular posts from this blog

How to create zip file to download in JSP- Servlet

How to create DataGrid or GridView in JSP - Servlet

Pinging in ASP.NET Example