4

I just want to add List as a DataTable entire row. here is the code which I have tried.

private static DataTable _table = new DataTable();

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

// tempList = {"A1","A2","A3","A4","A5","A6"}

_table.Rows.Add(tempList);

Expected output:

      col1|col2 |col3 |col4  |col5| col6
      ----+-----+-----+------+----+--
row1   A1 |  A2 | A3  |  A4  | A5 |  A6

However this is not working for me. It will insert data collection to first column.

Actual output:

      col1      |col2 |col3 |col4  |col5| col6
      ----------+-----+-----+------+----+--
row1   A1,A2,A3.|     |     |      |    |  

Please help me to Add entire row using list. thank you

devan
  • 1,643
  • 8
  • 37
  • 62

3 Answers3

11

DataRowCollection.Add() Method expects Object[], so you should probably try:

_table.Rows.Add(tempList.ToArray());
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
6

Rows.Add() accepts parms[], you can achieve it by converting your list into an array.

_table.Rows.Add(tempList.ToArray());
Asif Mushtaq
  • 13,010
  • 3
  • 33
  • 42
2
 DataTable dt = new DataTable();
        dt.Columns.Add();
        dt.Columns.Add();
        dt.Columns.Add();
        List<string> tempList = new List<string>() { "a", "b", "c" };
        dt.Rows.Add(tempList.ToArray<string>());