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 .

The ASPX page

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

The Code Behind

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

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;
            return table;

The Output

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

Example to disable save as certain file type in SSRS Report Viewer

Phone book application example - Java

Modal Popup Message Box ASP.NEt C# Example