Jonathan
Jonathan

Reputation: 651

Convert list of string to DataTable

I want to convert List of string to datatable so I try:

List<string> DesignNameList = new List<string>();

  public static Mymethod...{

     parameters = ToDataTable(DesignNameList);
   }


 public static DataTable ToDataTable(List<string> list)
        {

            DataTable dataTable = new DataTable();
            foreach (var row in list)
            {
                dataTable.Rows.Add(row);
            }
            return dataTable;

        }

But I get error when foreach is being executed in line dataTable.Rows.Add(row);:

'Input array is longer than the number of columns in this table.'

What I'm doing wrong? Regards

Upvotes: 2

Views: 10584

Answers (2)

Wallison Felipe
Wallison Felipe

Reputation: 9

Try to exchange the loop 'foreach' by the 'for', like this:

  DataTable dataTable = new DataTable();
  for (int i = 0; i < list.Count(); i++)
  {
      dataTable.Rows.Add(list[i]);
  }
  return dataTable;

Upvotes: 0

Carlo Bos
Carlo Bos

Reputation: 3293

You'll need to add a column to the data table first. As it is created is has no columns

DataTable datatable= new DataTable();  

DataColumn workCol = datatable.Columns.Add("column_name", typeof(String)); 

Upvotes: 4

Related Questions