Winz
Winz

Reputation: 449

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?

Upvotes: 26

Views: 172551

Answers (5)

MX313
MX313

Reputation: 153

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";

Upvotes: 0

pinkfloydx33
pinkfloydx33

Reputation: 12739

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";

Upvotes: 26

Teekai
Teekai

Reputation: 141

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

Upvotes: 14

lc.
lc.

Reputation: 116458

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.

Upvotes: 0

Pedigree
Pedigree

Reputation: 2594

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

Upvotes: 1

Related Questions