Write an Add Row with NewRow in one line

600 Views Asked by At

I would like to add a new row in an existing table. I want to create a new row with the NewRow method and put the values on the same line.

DataTable dtTable1 = new DataTable();
dtTable1.Rows.Add(new DataColumn(NCdeTCMParametrs.NombreCol1), typeof(string));
dtTable1.Rows.Add(new DataColumn(NCdeTCMParametrs.NombreCol2()), typeof(string)); 
        
        
dtTable1.Rows.Add(dtTable1.NewRow() { new object[] { datCol1, string.Join(",", listCol2) } });

I can't find the correct syntax for it to be accepted. What is the mistake?

1

There are 1 best solutions below

3
Tim Schmelter On

You just need to use DataRowCollection.Add that takes an Object[]:

dtTable1.Rows.Add(new object[] { datCol1, string.Join(",", listCol2) });

DataTable.NewRow is used if you want to initialize each field separately, so you don't need it if you want to pass the whole array at once. You could also use NewRow and initialize all fields at once with ItemArray, but you need multiple lines:

DataRow row = dtTable1.NewRow();
row.ItemArray = new object[] { datCol1, string.Join(",", listCol2) };
dtTable1.Rows.Add(row);

A third option is to add an empty row and afterwards modify the already added row:

DataRow addedRow = dtTable1.Rows.Add();
addedRow.ItemArray = new object[] { datCol1, string.Join(",", listCol2) };