Thursday, June 2, 2011

Dynamic Create DataTable from Generic List using Reflection

I have few methods that returns different Generic Lists.But main thing here I am using Reflection to convert Generic List into Datatable.

//Due To Html tag problem I am using single quote with generic Type T otherwise you dont need to use single quote.

public static DataTable ListToDataTable(List list)
{
DataTable dt = new DataTable();

foreach (PropertyInfo info in typeof(T).GetProperties())
{
Type pt = info.PropertyType;
if (pt.IsGenericType && pt.GetGenericTypeDefinition() == typeof(Nullable))
{
pt = Nullable.GetUnderlyingType(pt);
dt.Columns.Add(info.Name, pt);
}
else
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;
}

No comments:

Post a Comment