Search code examples
c#asp.net.netsqldatasource

How to add exception handling to SqlDataSource.UpdateCommand


We have a radgrid that is automatically updated with the SqlDataSource.UpdateCommand. So when we edit some column(s) and click on "Update" the table is updated correctly with UpdateCommand in the markup.

It looks something like this:

<telerik:RadGrid ID="RadGrid" DataSourceID="SqlDataSource1" runat="server" AllowAutomaticUpdates="true" >
<MasterTableView AutoGenerateColumns="False" DataKeyNames="City" CommandItemDisplay="Top"  AllowAutomaticUpdates="true">
        <Columns>
            <telerik:GridEditCommandColumn ButtonType="ImageButton" UniqueName="EditCommandColumn">
            </telerik:GridEditCommandColumn>
            <telerik:GridBoundColumn DataField="City" HeaderText="City" ReadOnly="True" SortExpression="City"
                UniqueName="City" >
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn DataField="Prefix" HeaderText="Prefix" UniqueName="Prefix">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn DataField="sector" HeaderText="sector" UniqueName="sector">
            </telerik:GridBoundColumn>
        </Columns>
        </MasterTableView>
</telerik:RadGrid>
<asp:SqlDataSource ID="SqlDataSource1" ConnectionString="<%$ ConnectionStrings:RF-PRConnectionString %>"
SelectCommand="SELECT STATEMENT" runat="server"
UpdateCommand= "UPDATE STATEMENT">
<UpdateParameters>
    <asp:Parameter Name="Name" Type="String" />
    <asp:Parameter Name="sector" Type="String" />
</UpdateParameters>
</asp:SqlDataSource>

But let's say that the update generates an exception in the table (ie. tried to update an Int with varchar, violates some key, etc). Is there any way I can add a Try...Catch to SqlDataSource.UpdateCommand? I wouldn't know how to since there's no code behind that does the update, everything is done through SqlDataSource.


Solution

  • Very simple solution: I need to handle the OnRowUpdated event.

    protected void GridView_RowUpdated(object sender, GridViewUpdatedEventArgs e)
    {
        if (e.Exception != null)
        {
            //show error message
            e.ExceptionHandled = true;
        }
    }