Search code examples
asp.netobjectdatasource

how to return error from ObjectDataSource?


I use an objectDataStore to insert the records from a form. But when inserting into the database, I might get an error. If I get an error, I want to show it in a field. But how do I return some data back into the aspx file?


Solution

  • Create a handler for the ObjectDataSource Updated event in your codebehind. One of the parameters to this handler is of type ObjectDataSourceStatusEventArgs. If an exception occurred while updating, the event args contain an Exception object. All you need to do is test that the Exception object is not null and then insert whatever code you want there.

    Here is an example of the code for a handler method:

    protected void MyObjectDataSource_Updated(object sender, ObjectDataSourceStatusEventArgs e)
    {
        if (e.Exception != null)
        {
            // populate your field here
            lblMessage.Text = e.Exception.Message
        }
    }
    

    Here is the ObjectDataSource tag:

    <asp:ObjectDataSource
        ID="MyObjectDataSource"
        runat="server"
        UpdateMethod="Update"
        OnUpdating="MyObjectDataSource_Updated"
        TypeName="Your.Custom.Object" />
    

    This link here contains an example but its for the "Deleting" and "Deleted" events. You will want to use the same code but implement for the "Updated" event.