Click here to Skip to main content
15,742,477 members
Please Sign up or sign in to vote.
0.00/5 (No votes)

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

What I have tried:

static List<string> SimilarItems = new List<string>();
Similar = ConvertToString(dt.Rows[i]["ItemCode"]);
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



        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);



        return dataTable;
Updated 26-Sep-18 20:12pm

Have a look at this: Converting a List to a DataTable[^] - it's the method I use.
Share this answer
Maciej Los 27-Sep-18 2:12am    
Well, i'd strogly recommend to read this: How to: Implement CopyToDataTable<T> Where the Generic Type T Is Not a DataRow | Microsoft Docs[^]

If your list is just a List<string>, you can use: DataTable.LoadDataRow()[^] + CopyToDataTable()[^] method.

List<string> mylist = new List<string>() {"1830","950","902","540"};

DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("item", typeof(string)));
dt = mylist
	.Select(x=> dt.LoadDataRow(new object[]{x}, false))

For further details, please see: Creating a DataTable From a Query (LINQ to DataSet) | Microsoft Docs[^]

Good luck!
Share this answer

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