Click here to Skip to main content
15,901,205 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
how can i convert list of view models to data table to print it in pdf later ?

i have error in this line : values[i] = Props[i].GetValue(item, null).ToString();
cant convert it !

C#
public ActionResult detailsoperation(OperationViewModel operationvm
,
C#
CategorieViewModel categories, string idd)
         {
             List<CategorieViewModel> list = (List<CategorieViewModel>)Session["categories"];
             list.Add(categories);
             DataTable dataTable = new DataTable(typeof(CategorieViewModel).Name);

             //Get all the properties
             PropertyInfo[] Props = typeof(OperationViewModel).GetProperties(BindingFlags.Public | BindingFlags.Instance);
             foreach (PropertyInfo prop in Props)
             {
                 //Setting column names as Property names
                 dataTable.Columns.Add(prop.Name);
             }

             foreach (CategorieViewModel item in list)
             {
                 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).ToString();
                 }
                 dataTable.Rows.Add(values);
             }
Posted

Solution1 by Jörgen Andersson[^] is very good. In addition to it, i'd suggest to read this: How to: Implement CopyToDataTable<t> Where the Generic Type T Is Not a DataRow[^]
 
Share this answer
 
Allow me to plug my own[^] solution
 
Share this answer
 
Comments
Maciej Los 19-Apr-15 12:43pm    
+5!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900