user9236349
user9236349

Reputation:

How to iterate through a datatable and set values?

How would I go about doing something similar to the code below? I'd like to iterate through my datatable and set / change values. In this case, setting all of the rows DateRcvd to the current date.

foreach(DataRow row in SubVwr.Tables[0].Tbl.Rows)
{
    row.Field<DateTime>("DateRcvd") = DateTime.Today;
}

Upvotes: 0

Views: 1194

Answers (2)

AlleXyS
AlleXyS

Reputation: 2598

You can iterate through each row and use an indexer property of the DataRow:

foreach(DataRow row in SubVwr.Tables[0].Tbl.Rows)
{
   row["DateRcvd"] = DateTime.Today;
}

Upvotes: 3

Blindy
Blindy

Reputation: 67380

The modern way of writing it is:

row.SetField("DateRcvd", DateTime.Today);

Since SetField is a generic method, it won't box your value type like using the default indexer will (the indexer takes an object).

Upvotes: 2

Related Questions