How to convert list to datatable using extension method

  • Thread starter Thread starter engahmedbarbary
  • Start date Start date
E

engahmedbarbary

Guest
Problem

error mismatch count parameter when convert list to datatable

my list as below

static List<string> SimilarItems = new List<string>();
Similar = ConvertToString(dt.Rows["ItemCode"]);
SimilarItems.Add(Similar);
dtcollectlistdata = Extensions.ToDataTable(SimilarItems);

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 = Props.GetValue(item, null);

}

dataTable.Rows.Add(values);

}
return dataTable;
}


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

How to convert list of string to datatable

Continue reading...
 
Back
Top