Click here to Skip to main content
15,915,328 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Hi All,

Can anyone help me how to convert list<Of T> to a DataTable in .net

Thanks in Advance
Seshu
Posted

 
Share this answer
 
Comments
RaviRanjanKr 16-Jul-11 4:26am    
Nice Link, My 5+
Here is an extension method which does just that:
public static class ExtensionMethods
    {
    /// <summary>
    /// Converts a List to a datatable
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="data"></param>
    /// <returns></returns>
    public static DataTable ToDataTable<T>(this IList<T> data)
        {
        PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
        DataTable dt = new DataTable();
        for (int i = 0; i < properties.Count; i++)
            {
            PropertyDescriptor property = properties[i];
            dt.Columns.Add(property.Name, property.PropertyType);
            }
        object[] values = new object[properties.Count];
        foreach (T item in data)
            {
            for (int i = 0; i < values.Length; i++)
                {
                values[i] = properties[i].GetValue(item);
                }
            dt.Rows.Add(values);
            }
        return dt;
        }
    }
 
Share this answer
 
Have a go through the threads going there[^] where its suggested to use BindingList<T>
BindingList<T>[^] Class Provides a generic collection that supports data binding.

or the given function also might help you to convert List<type> to datatable
public 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);
}
dt.Rows.Add(row);
}
return dt;
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900