Specializations

Wednesday, November 14, 2012

Convert List to Datatable in C#.net

 public DataTable ToDataTable(IList<YourClassName> data)
{
 PropertyDescriptorCollection props =TypeDescriptor.GetProperties(typeof(YourClassName));
 DataTable table = new DataTable();
for (int i = 0; i < props.Count; i++)
{
 PropertyDescriptor prop = props[i];
table.Columns.Add(prop.Name, prop.PropertyType);
}
object[] values = new object[props.Count];
foreach (JobIDObj item in data){
for (int i = 0; i < values.Length; i++)
{
 values[i] = props[i].GetValue(item);
} table.Rows.Add(values);
}
 return table;
}

No comments:

Post a Comment