how to convert list to datatable [duplicate]
Possible Duplicate:
.NET - Convert Generic Collection to DataTable
hi, i want to convert list datatype to datatype. i wrote the function
static DataTable ListToDataTable<T>(IEnumerable<T> list)
{
var dt = new DataTable();
foreach (var i开发者_运维问答nfo in typeof(T).GetProperties())
{
dt.Columns.Add(new DataColumn(info.Name, info.PropertyType));
}
foreach (var t in list)
{
var row = dt.NewRow();
foreach (var info in typeof(T).GetProperties())
{
row[info.Name] = info.GetValue(t, null);
}
dt.Rows.Add(row);
}
return dt;
}
but this is throwing exception "DataSet does not support System.Nullable<>" how can we solve this or is there any other solution
Give this a try...
// When building table
Type pt = info.PropertyType;
if(pt.IsGenericType && pt.GetGenericTypeDefinition()==typeof(Nullable<>))
pt = Nullable.GetUnderlyingType(pt);
}
dt.Columns.Add(new DataColumn(info.Name, pt));
// When loading table
row[info.Name] = info.GetValue(t, null) ?? DBNull.Value;
精彩评论