ahmed elbarbary

ahmed elbarbary

  • NA
  • 1.6k
  • 254.7k

How to convert list to datatable using extension method

Sep 26 2018 5:07 PM

Problem

error mismatch count parameter when convert list to datatable

my list as below

my list output of itemcode as below "1830","950","902","540"

How to convert list of string to datatable

  1. static List<string> SimilarItems = new List<string>();  
  2. Similar = ConvertToString(dt.Rows[i]["ItemCode"]);  
  3.                     SimilarItems.Add(Similar);  
  4. dtcollectlistdata = Extensions.ToDataTable(SimilarItems);  
  5.   
  6. public static DataTable ToDataTable(List items)  
  7.     {  
  8.   
  9.         DataTable dataTable = new DataTable(typeof(T).Name);  
  10.   
  11.         //Get all the properties  
  12.   
  13.         PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);  
  14.          
  15.         foreach (PropertyInfo prop in Props)  
  16.         {  
  17.   
  18.             //Setting column names as Property names  
  19.   
  20.             dataTable.Columns.Add(prop.Name);  
  21.   
  22.         }  
  23.   
  24.         foreach (T item in items)  
  25.         {  
  26.   
  27.             var values = new object[Props.Length];  
  28.   
  29.             for (int i = 0; i < Props.Length; i++)  
  30.             {  
  31.   
  32.                 //inserting property values to datatable rows  
  33.   
  34.                 values[i] = Props[i].GetValue(item, null);  
  35.   
  36.             }  
  37.   
  38.             dataTable.Rows.Add(values);  
  39.   
  40.         }  
  41.         return dataTable;  
  42.     }  
 

Answers (1)