2

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

1
  • There is little reason to do such a thing. A List<T> is probably a bit more flexible than a DT...and you certainly do not need a DataTable you created for DB updates Commented Nov 22, 2018 at 17:11

2 Answers 2

4

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)); 
Sign up to request clarification or add additional context in comments.

Comments

0

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;

1 Comment

How will that make any difference given the error message?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.