Convert List to DataTable – (ListToDataTable function)

using System.Data;
using System.Reflection;

private static DataTable ListToDataTable<T>(List<T> list)
            DataTable dt = new DataTable();

            foreach (PropertyInfo info in typeof(T).GetProperties())
                dt.Columns.Add(new DataColumn(info.Name, info.PropertyType));
            foreach (T t in list)
                DataRow row = dt.NewRow();
                foreach (PropertyInfo info in typeof(T).GetProperties())
                    row[info.Name] = info.GetValue(t, null);
            return dt;

Example implementation:

        List<InvestorFilingData> lst = FilingsLogic.GetInvestorFiling();
        DataTable dt = ListToDataTable(lst);

Example use: When you have an object bound to a GridView and want to sort the columns.


Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s