ADO.NET: Handle Errors

In addition to Try/Catch and exceptions, the new ADO.NET data architecture allows you to add error messages to each row of Data in a DataSet. SqlDataAdapters attach error messages to Rows if updates or other actions fail. Furthermore, you can filter for rows in error to present them to the user, or pass them to error handling functions.

Errors persist with the DataSet even when being transferred using XML or XML Web services. You can use the RowError property to set the Error message of a DataRow in a DataSet.


    myDataSet.Tables("Customers").Rows(0).RowError = "An error was added"
    myDataSet.Tables("Customers").Rows(1).RowError = "This is another error message"
    
VB

Now you can walk the error in a DataTable with the GetErrors() method. You can also test for errors using HasErrors.


    if myDataSet.Tables("Customers").HasErrors then
      Dim ErrDataRows as DataRow()
      ErrDataRows = myDataSet.Tables("Customers").GetErrors()
      Console.WriteLine("DataTable " + myDataSet.Tables("Customers").TableName + " has " + ErrDataRows.Length.ToString() + " Error(s)!")
    
      Dim i as integer
      for i = 0 to ErrDataRows.Length -1
        Console.WriteLine("Row Error for row " + ErrDataRows(i)("CustomerID").ToString() + " --  Error Msg="  + ErrDataRows(i).RowError)
      next
    else
      Console.WriteLine("=================")
      Console.WriteLine("DataTable " + myDataSet.Tables("Customers").TableName + " Has no errors")
    end if
    
VB

The following example loads a DataSet, sets some errors, and then shows the Errors in the Rows.

 
VB HandleErrors.aspx

[Run Sample] | [View Source]


Copyright 2001 Microsoft Corporation. All rights reserved.