Hi @jewel,
You should convert the List<object>
to DataTable
. Then the issue will be fixed.
Here is the test code:
public DataTable Getcompanylist()
{
var compnay = _context.tbl_Compnays.ToList();
DataTable dt = ToDataTableByList(compnay);
return dt;
}
private static DataTable ToDataTableByList<T>(List<T> list)
{
List<PropertyInfo> pList = new List<PropertyInfo>();
Type type = typeof(T);
DataTable dt = new DataTable();
Array.ForEach<PropertyInfo>(type.GetProperties(), p =>
{
pList.Add(p);
dt.Columns.Add(p.Name, p.PropertyType);
});
if (list != null && list.Count > 0)
{
foreach (var item in list)
{
DataRow row = dt.NewRow();
pList.ForEach(p => row[p.Name] = p.GetValue(item, null));
dt.Rows.Add(row);
}
}
return dt;
}
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Jason