Mega Code Archive

 
Categories / ASP.Net Tutorial / ADO Net Database
 

Handling SQL Command Execution Errors

You can handle errors thrown by the SqlDataSource control by handling any or all of  the following four events: Deleted, Inserted, Selected, Updated Each of these events is passed an EventArgs parameter that includes any exceptions raised  when the command was executed.  <%@ 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 srcProducts_Selected(object sender, SqlDataSourceStatusEventArgs 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"         DataSourceID="srcProducts"         Runat="server" />     <asp:SqlDataSource         id="srcProducts"         SelectCommand="SELECT * FROM DontExist"         ConnectionString="<%$ ConnectionStrings:Products %>"         OnSelected="srcProducts_Selected"         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>