Updating Rows

There are three ways to modify the contents of a row. First, you can simply replace the values of the column with a new value:

DataRow row;

// ... code to retrieve data into the row

// access the column by its ordinal and update the value

row[0] = "New Value";

// access the column by its name and update the value

row["MyColumn"] = "New Value";

You can also buffer the updates to a row by calling the BeginEdit( ) , EndEdit( ), and CancelEdit( ) methods. The BeginEdit( ) method turns off all constraints and suspends events used to enforce validation rules. If CancelEdit( ) is called, the changes in the buffer are discarded. When EndEdit( ) is called, the data is validated against the constraints, and the appropriate events are raised. BeginEdit( ) is called implicitly when a user changes the value of a data-bound control. EndEdit( ) is called implicitly when AcceptChanges( ) is called.

DataTable dt = new DataTable();

// ... code to retrieve data into the DataTable object

DataRow row = dt.Rows[0];


foreach(DataColumn col in dt.Columns)


    // ...modify the column value


bool rowValid = true;

// ...check the values in the row to make sure that they are valid










Finally, a row can be updated by accessing the row through the ItemArray property. When this method is called, an attempt is made to locate the row matching the primary key. If the row is found, it is updated with the values in the ItemArray ...

Get ADO.NET in a Nutshell now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.