Home  


Update Dataset Records in ADO.NET

First get the specific row which wants changes. Then call BeginEdit() on the DataRow to put the row into editing mode. This suspends events on the row so that you could, if you chose, edit a number of rows at once without any validation rules.It is good form to bracket changes on DataRows with calls to BeginEdit() and EndEdit().

					
protected void btnUpdate_Click (object sender, System.EventArgs e)
{
    int  index;

    // Get the selected row from the ListBox
    index = listBoxCustomers.SelectedIndex;
    if (index == (-1))
    {
        lblMessage.Text = "Please select a Customer";
        return;
    }
    else
    {
        lblMessage.Text = "";
    }
    DataRow targetRow  = _dataTable.Rows[index];

    // Inform the user
    lblMessage.Text = "Updating: " +  targetRow["CompanyName"];
    Application.DoEvents();

    // Edit the row, no validation is fired between
    // BeginEdit() and EndEdit(). The underlying Dataset
    // will no mark the Row as an UPDATE!
    targetRow.BeginEdit();
    targetRow["CompanyName"] = txtCustomerName.Text;
    targetRow.EndEdit();

    // Use the GetChanges method to create a second DataSet
    // object that is then used to update a data source.
    DataSet dataSetChanged =
        _dataSet.GetChanges(DataRowState.Modified);

    // Test to make sure all the changed rows are without errors
    bool okayFlag = true;
    if (dataSetChanged.HasErrors)
    {
        okayFlag = false;
        string msg = "Error in row with customer ID ";

        // Examine each table in the changed DataSet
        foreach (DataTable theTable in dataSetChanged.Tables)
        {
            // If any table has errors, find out which rows
            if (theTable.HasErrors)
            {
                // Get the rows with errors
                DataRow[] errorRows = theTable.GetErrors();

                // iterate through the errors and correct
                // (in our case, just identify)
                foreach (DataRow theRow in errorRows)
                {
                    msg = msg + theRow["CustomerID"];
                }
            }
        }
        lblMessage.Text = msg;
    }
    // If we have no errors
    if (okayFlag)
    {
        // Update the database on second dataset
        _dataAdapter.Update(dataSetChanged,"Customers");

        // Inform the user
        lblMessage.Text = "Updated " +  targetRow["CompanyName"];
        Application.DoEvents();

        // Accept the changes and repopulate the list box
        _dataSet.AcceptChanges();
        PopulateListBox();
    }
    else
    {   // If we had errors, reject the changes
        _dataSet.RejectChanges();
    }
}