Reputation: 8135
I have a stored procedure(SP) named UPDATE_INFO, in that SP, I throw some SQLExceptions
RAISERROR ('Exception Created',16,1);
I use that SP in a girdview, now what I want is that whenever an exception is thrown, I can catch it and display it sothat the users can know what is going wrong.
But I don't know how to do this, I think that the Gridview already catch all exceptions from SPs
Does anyone get a way to do this?
Code part:
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:UpdatePanel ID="UpdatePane" runat="server">
<ContentTemplate >
<asp:GridView ID="GridView" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="ProjectID"
DataSourceID="DataSource" >
<Columns>
<asp:CommandField ShowEditButton="True" CausesValidation="false" />
<asp:BoundField DataField="Name" HeaderText="Name"
SortExpression="ProjectID"/>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
<asp:SqlDataSource ID="DataSource" runat="server"
ConflictDetection="CompareAllValues"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT" SelectCommandType="StoredProcedure"
UpdateCommand="UPDATE" UpdateCommandType="StoredProcedure">
<UpdateParameters>
<asp:Parameter Name="Name" Type="String" />
<asp:Parameter Name="original_Name" Type="String" />
</UpdateParameters>
</asp:SqlDataSource>
</asp:Content>
Upvotes: 1
Views: 989
Reputation: 63970
You need to handle the OnRowUpdated event and detect if there were any errors like this:
protected void GridView_RowUpdated(object sender, GridViewUpdatedEventArgs e)
{
if (e.Exception != null)
{
//show nice error message however you want
// I imagine by firing javascript on the page
e.ExceptionHandled = true; //important not forgetting this
}
}
In your markup:
<asp:GridView ID="GridView" OnRowUpdated="GridView_RowUpdated" runat="server"
AllowPaging="True" ....
Upvotes: 4
Reputation: 44605
Man, you are doing everything in the aspx page. In general these things are done in the code behind where you can use ADO.NET with more control on what happens and you can invoke the stored procedure inside a try-catch.
Probably there is also a way to set the exception handling event to trigger from the aspx markup page you are using but I do think is better if you load the data from method in the aspx.cs
file.
this is what is usually done in real world applications.
Upvotes: 1