Visual Basic and Visual C# Concepts
Handling Concurrency Errors

ADO.NET provides a DBConcurrencyException object to assist in resolving issues arising from concurrency violations. The DBConcurrencyException object returns the data row that caused the error. For more information, see DBConcurrencyException Members.

The following example attempts to update a data source with the contents of myDataset from within a Try...Catch block, if an error is raised an error message along with the first column of the offending data row is displayed.

Note   The code below is an illustration of one strategy in handling a database update error. The code assumes several things; an existing connection to a database, an existing dataset named
myDataset
, as well as the assumption that execution of the update command will raise a concurrency violation. For more information and a complete example, see Walkthrough: Handling a Concurrency Exception.

To resolve a concurrency violation

  1. Execute the command to update the database from within a Try...Catch block.
  2. If an exception is raised, inspect the Catch statement's Row property to determine what caused the violation.
  3. Add code to resolve the error based on your application's business rules.

    The following code uses SqlDataAdapter1 and myDataset as examples of the data adapter and dataset in your application.

    ' Visual Basic
    Try
       SqlDataAdapter1.Update(myDataset)
    Catch ex As DBConcurrencyException
       Dim customErrorMessage As String
       customErrorMessage = "Concurrency violation" & vbCrLf
       customErrorMessage += Ctype(ex.Row.Item(0), String)
       MessageBox.Show(customErrorMessage)
       ' Replace the above code with appropriate business logic
       ' to resolve the concurrency violation.
    End Try
    
    // C#
    try
    {
       SqlDataAdapter1.Update(myDataset);
    }
    catch (DBConcurrencyException ex)
    {
       string customErrorMessage;
       customErrorMessage = "Concurrency violation\n";
       customErrorMessage += ex.Row[0].ToString();
       // Replace the above code with appropriate business logic 
       // to resolve the concurrency violation.
    }

See Also

DBConcurrencyException Class| SqlDataAdapter Class | OleDbDataAdapter Class | Try...Catch...Finally Statements (Visual Basic) | DBConcurrencyException Members

Page view tracker