As following this i have successfully converted List<T>
to DataTable
but there is something more. My T object
is basically a custom class having properties and also refernece to another class. Now i need to add that class's properties to the datatable also.
This is the function
public static DataTable ToDataTable<T>(this IList<T> list)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
for (int i = 0; i < properties.Count; i++)
{
PropertyDescriptor prop = properties[i];
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
}
object[] values = new object[properties.Count];
foreach (T item in list)
{
for (int i = 0; i < values.Length; i++)
values[i] = properties[i].GetValue(item) ?? DBNull.Value;
table.Rows.Add(values);
}
return table;
}
This is my effort to customize it but unable to retrieve an entire row of data for the DataTable
. As T is not having the properties of it's child. How can i add child's properties of T
or get an entire row of data.
private static DataTable AddColumnsForProperties(DataTable dt, PropertyDescriptor p, ref List<PropertyDescriptor> properties)
{
if (p.PropertyType.Namespace.ToLower().StartsWith("mynamespace"))
{
var allProperties = p.GetChildProperties();
foreach (PropertyDescriptor item in allProperties)
{
if (item.PropertyType.Namespace.ToLower().StartsWith("mynamespace"))
AddColumnsForProperties(dt, item, ref properties);
else
if (!dt.Columns.Contains(item.Name))
{
dt.Columns.Add(item.Name, Nullable.GetUnderlyingType(item.PropertyType) ?? item.PropertyType);
properties.Add(item);
}
}
}
else
if (!dt.Columns.Contains(p.Name))
{
dt.Columns.Add(p.Name, Nullable.GetUnderlyingType(p.PropertyType) ?? p.PropertyType);
properties.Add(p);
}
return dt;
}
public static DataTable ToDataTable<T>(this IList<T> list)
{
DataTable table = null;
if (list != null && list.Count > 0)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
List<PropertyDescriptor> propList = new List<PropertyDescriptor>();
table = new DataTable();
foreach (PropertyDescriptor item in properties)
{
AddColumnsForProperties(table, item, ref propList);
}
object[] values = new object[propList.Count];
foreach (T item in list)
{
for (int i = 0; i < values.Length; i++)
values[i] = propList[i].GetValue(item) ?? DBNull.Value;
table.Rows.Add(values);
}
}
return table;
}
I am working on a custom grid control that only works on DataTables so this functionality is crucial to me.As there are a lots of grids that need customization i need to have this function I cannot create every DataTable
manually.