[ Team LiB ] Previous Section Next Section

9.2 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];

row.BeginEdit();
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
 
if(rowValid)
{
    row.CancelEdit();
}
else
{
    row.EndEdit();
}

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; otherwise, a new row is created. Any columns with an array element set to null are set to the default value for the column. The value for AutoIncrement columns should be set to null in the ItemArray.

// create a table with two columns
DataTable dt = new DataTable();
DataColumn colId = 
  new DataColumn("ProductId", typeof(System.Int32));
DataColumn colDesc = 
  new DataColumn("Description", typeof(System.String));
dt.Columns.AddRange(new DataColumn[] {colId, colDesc});

dt.Rows.Add(new object[] {1, "Widget"});

// get the data for the row using the ItemArray property
object[] row = dt.Rows[0].ItemArray; 

// set the ProductId to be AutoIncrement 
colId.AutoIncrement = true;
// pass null for the AutoIncrement value
dt.Rows.Add(new object[] {null, "Thing"});

// let the description be null
colDesc.AllowDBNull = true;
// add a row with a null description, and AutoIncrement Id
dt.Rows.Add(new object[] {null, null});
    [ Team LiB ] Previous Section Next Section