Dear frnds,
Please any one tell me how to convert list to datatable in asp.net.
Thanks & Regards
Niranjan Poddar
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Rasmita DashPosted Oct 24, 2014, 6:01 AM
"
public static DataTable ListToDataTable
Dhanunjay JajimogglaPosted Oct 24, 2014, 7:48 AM
Hi Niranjan Poddar,
public DataTable ToDataTable(List items)
{
DataTable dataTable = new DataTable(typeof(T).Name);
//Get all the properties
PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public |BindingFlags.Instance);
foreach (PropertyInfo prop in Props)
{
//Setting column names as Property names
dataTable.Columns.Add(prop.Name);
}
foreach (T item in items)
{
var values = new object[Props.Length];
for (int i = 0; i < Props.Length; i++)
{
//inserting property values to datatable rows
values[i] = Props[i].GetValue(item, null);
}
dataTable.Rows.Add(values);
}
//put a breakpoint here and check datatable
return dataTable;
}
Abhishek KumarPosted Oct 24, 2014, 5:52 AM
here is the code.
public static DataTable ToDataTable( List items)
{
DataTable dataTable = new DataTable(typeof(T).Name);
//Get all the properties
PropertyInfo[] Props =
typeof(T).GetProperties(BindingFlags.Public |
BindingFlags.Instance);
foreach (PropertyInfo prop in Props)
{
//Setting column names as Property names
dataTable.Columns.Add(prop.Name);
}
foreach (T item in items)
{
var values = new object[Props.Length];
for (int i = 0; i < Props.Length; i++)
{
//inserting property values to datatable rows
values[i] = Props[i].GetValue(item, null);
}
dataTable.Rows.Add(values);
}
//put a breakpoint here and check datatable
return dataTable;
}
Hope this will help.
Abhishek