Search code examples
c#datatable

Adding values to specific DataTable cells


Is it possible to add values to specific DataTable cells?

Suppose I have an existing DataTable and I add a new column, how would I go about adding to the new column's rows without overwriting the existing columns' rows?

As far as I'm aware, there isn't a method for adding to specific cells.

  dt.Rows.Add(a, b, c, d)

where a, b, c, and d are string values. So what if I just want to add to the d column?


Solution

  • If it were a completely new row that you wanted to only set one value, you would need to add the whole row and then set the individual value:

    DataRow dr = dt.NewRow();
    dr[3].Value = "Some Value";
    dt.Rows.Add(dr);
    

    Otherwise, you can find the existing row and set the cell value

    DataRow dr = dt.Rows[theRowNumber];
    dr[3] = "New Value";