public static DataTable ToDataTable(this IEnumerable ien)
{
DataTable dt = new DataTable();
foreach (object obj in ien)
{
Type t = obj.GetType();
PropertyInfo[] pis = t.GetProperties();
if (dt.Columns.Count == 0)
{
foreach (PropertyInfo pi in pis)
{
Type propType = pi.PropertyType;
// Is it a nullable type? Get the underlying type
if (propType.IsGenericType && propType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
propType = new System.ComponentModel.NullableConverter(propType).UnderlyingType;
dt.Columns.Add(pi.Name, propType);
}
}
DataRow dr = dt.NewRow();
foreach (PropertyInfo pi in pis)
{
object value = pi.GetValue(obj, null);
dr[pi.Name] = value;
}
dt.Rows.Add(dr);
}
return dt;
}
thanks.... this helped me
ReplyDelete