Sunday 8 December 2013

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

Leave a Comment

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

0 comments:

Post a Comment

Subscribe to our newsletter to get the latest updates to your inbox.

Your email address is safe with us!




Founder of developersnote.com, love programming and help others people. Work as Software Developer. Graduated from UiTM and continue study in Software Engineering at UTMSpace. Follow him on Twitter , or Facebook or .



Powered by Blogger.