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;
}

Advertisements
This entry was posted in C# and tagged , , . Bookmark the permalink.

One Response to Dynamic Create DataTable from Generic List using Reflection

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s