ObjectDataSource Exception Handling

I was using the ObjectDataSource today to display and delete data using a GridView.  When I tried to delete a record that was referenced in another table an exception was thrown due to referential integrity.

I found that in implementing the Deleted event of the ObjectDataSource, the ObjectDataSourceStatusEventArgs class had a boolean property called ExceptionHandled.  Setting this to true stops the ObjectDataSource from re-throwing the exception, allowing you to handle it yourself.  You can obtain the underlying exception using the Exception property.

protected void odsUser_Deleted(object sender, ObjectDataSourceStatusEventArgs e)
{
    if (e.Exception != null)
    {
        e.ExceptionHandled = true;
        //Perform own exception handling
        lblError.Text = e.Exception.Message;
    }
}

You could also use the same approach with the Updated event.

Posted on by Joe in ASP.NET, C#

Add a Comment