Reputation: 1689
I have a JSON
object which i get from an ajax post call,which i am mapping it to my list of Customclass objects like below.
[ObjectFilter(Param = "postdata", RootType = typeof(List<ExportToExcel8020>))]
public void ExportToExcel(List<ExportToExcel8020> text)
{
//List<ExportToExcel8020> rm = text.AsEnumerable().ToList();
//DataTable UserDt = rm .ToDataTable();
DataTable UserDt = text.ToDataTable();
}
This is how my list object looks,
Now I want this generic list object
to be converted into a datatable
,
i am trying to do this by using the below method. But i get an error which says
'System.Collections.Generic.List<...Domain.Common.ExportToExcel8020>' does not contain a definition for 'ToDataTable' and no extension method 'ToDataTable' accepting a first argument of type...
'System.Collections.Generic.List<...Domain.Common.ExportToExcel8020>' could not be found (are you missing a using directive or an assembly reference?)
public static DataTable ToDataTable<T>(List<T> 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;
}
The reason i need it as a datatable
is to use openxml
and export an excel
file.
Is there something wrong with my code? or is my apporach itself is wrong?
Upvotes: 1
Views: 460
Reputation: 1579
This looks like you are trying to write an extension method. the method signature needs to have this
as a keyword to the first parameter which then specifies the type you are extending (and passes in the instance of the object when the extension method is called). try
public static DataTable ToDataTable<T>(this List<T> items)
as the method signature.
Upvotes: 3