Mega Code Archive

 
Categories / ASP.Net Tutorial / ADO Net Database
 

Handle the exception at the level of a DataBound control

The GridView, DetailsView, and FormView controls all include events that expose the  Exception and ExceptionHandled properties. <%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <script runat="server">     protected void grdProducts_RowUpdated(object sender, GridViewUpdatedEventArgs e)     {         if (e.Exception != null)         {             lblError.Text = e.Exception.Message;             e.ExceptionHandled = true;         }     } </script> <html xmlns="http://www.w3.org/1999/xhtml" > <body>     <form id="form1" runat="server">     <div>     <asp:Label         id="lblError"         EnableViewState="false"         CssClass="error"         Runat="server" />     <asp:GridView         id="grdProducts"         DataKeyNames="Id"         AutoGenerateEditButton="true"         DataSourceID="srcProducts"         OnRowUpdated="grdProducts_RowUpdated"         Runat="server" />     <asp:SqlDataSource         id="srcProducts"         SelectCommand="SELECT Id,Title FROM Products"         UpdateCommand="UPDATE DontExist SET Title=@Title WHERE Id=@ID"         ConnectionString="<%$ ConnectionStrings:Products %>"         Runat="server" />     </div>     </form> </body> </html> File: Web.config <configuration>   <connectionStrings>     <add name="Products"           connectionString="Data Source=.\SQLEXPRESS;          AttachDbFilename=|DataDirectory|MyDatabase.mdf;Integrated Security=True;User Instance=True" />   </connectionStrings> </configuration>