How to convert System.Collections.IEnumerable (Linq Query Result) to a DataTable

Here is how to convert an IEnumerable collection to a datatable to be populated to a Grid Control:

public DataTable CopyToDataTable(System.Collections.IEnumerable parIList)
{
System.Data.DataTable ret = new System.Data.DataTable();
try
{
System.Reflection.PropertyInfo[] ppi = null;
if (parIList == null)
return ret;
foreach (object itm in parIList)
{
if (ppi == null)
{
ppi = ((System.Type)itm.GetType()).GetProperties();
foreach (System.Reflection.PropertyInfo pi in ppi)
{
System.Type colType = pi.PropertyType;
if ((colType.IsGenericType) && (object.ReferenceEquals(colType.GetGenericTypeDefinition(), typeof(System.Nullable<>))))
colType = colType.GetGenericArguments()[0];
ret.Columns.Add(new System.Data.DataColumn(pi.Name, colType));
}
}
System.Data.DataRow dr = ret.NewRow();
foreach (System.Reflection.PropertyInfo pi in ppi)
{
dr[pi.Name] = pi.GetValue(itm, null) == null ? DBNull.Value : pi.GetValue(itm, null);
}
ret.Rows.Add(dr);
}
foreach (System.Data.DataColumn c in ret.Columns)
{
c.ColumnName = c.ColumnName.Replace("_", " ");
}
}
catch (Exception)
{
ret = new System.Data.DataTable();
}
return ret;
}

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *