26

I'm wondering if it's 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 (unless I'm wrong).

  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?

Any help would be appreciated.

Raidri
  • 17,258
  • 9
  • 62
  • 65
Winz
  • 449
  • 2
  • 6
  • 18

5 Answers5

26

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";
pinkfloydx33
  • 11,863
  • 3
  • 46
  • 63
14

Try this:

dt.Rows[RowNumber]["ColumnName"] = "Your value"

For example: if you want to add value 5 (number 5) to 1st row and column name "index" you would do this

dt.Rows[0]["index"] = 5;

I believe DataTable row starts with 0

Blundering Philosopher
  • 6,245
  • 2
  • 43
  • 59
Teekai
  • 141
  • 1
  • 2
1

I think you can't do that but atleast you can update it. In order to edit an existing row in a DataTable, you need to locate the DataRow you want to edit, and then assign the updated values to the desired columns.

Example,

DataSet1.Tables(0).Rows(4).Item(0) = "Updated Company Name"
DataSet1.Tables(0).Rows(4).Item(1) = "Seattle"

SOURCE HERE

Pedigree
  • 2,384
  • 3
  • 23
  • 28
0

You mean you want to add a new row and only put data in a certain column? Try the following:

var row = dataTable.NewRow();
row[myColumn].Value = "my new value";
dataTable.Add(row);

As it is a data table, though, there will always be data of some kind in every column. It just might be DBNull.Value instead of whatever data type you imagine it would be.

lc.
  • 113,939
  • 20
  • 158
  • 187
0

If anyone is looking for an updated correct syntax for this as I was, try the following:

Example:
dg.Rows[0].Cells[6].Value = "test";
MX313
  • 129
  • 1
  • 9