How To Convert List to DataTable in MVC C#

   
                          In MVC C# know about List<T> to Datatable. First I Write One Stored Procedure and I Include the SP in Your EDMX. Write your code within the C#.


              var ReportList = (from dat in dc.SP_Report(fromDate, frmTime, toDate, toTime)
                                      select new
                                      
                                          SNo = Sno += 1,
                                          Country = dat.CountryName,
                                          RequestNo = dat.RequestNo,
                                          RequestDate = dat.RequestDate,
                                          RequestTime = dat.RequestTime,
                                      }).ToList();



                    DataTable dt = ConvDtcls.ToDataTable(ReportList);


And I Create Datatable Function.


 public 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;
        }

Comments

Popular posts from this blog

Insecure cookie setting: missing Secure flag

Maximum Stored Procedure Function Trigger or View Nesting Level Exceeded (limit 32) in SQL Server

Display Line Chart Using Chart.js MVC C#