先看前台代码:
1 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Demo23.aspx.cs" Inherits="Demo23" %>
2
3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4
5 <html xmlns="http://www.w3.org/1999/xhtml">
6 <head runat="server">
7 <title>示范如何处理 SELECT 语句执行错误</title>
8 </head>
9 <body>
10 <form id="form1" runat="server">
11 <div>
12 <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
13 <asp:GridView ID="GridView1"
14 runat="server" DataSourceID="SqlDataSource1">
15 </asp:GridView>
16 <asp:SqlDataSource ID="SqlDataSource1" runat="server"
17 ConnectionString="<%$ ConnectionStrings:ChtNorthwind %>"
18 SelectCommand="SELECT * FROM [authors222]"
19 onselected="SqlDataSource1_Selected"></asp:SqlDataSource>
20 </div>
21 </form>
22 </body>
23 </html>
24
2
3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4
5 <html xmlns="http://www.w3.org/1999/xhtml">
6 <head runat="server">
7 <title>示范如何处理 SELECT 语句执行错误</title>
8 </head>
9 <body>
10 <form id="form1" runat="server">
11 <div>
12 <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
13 <asp:GridView ID="GridView1"
14 runat="server" DataSourceID="SqlDataSource1">
15 </asp:GridView>
16 <asp:SqlDataSource ID="SqlDataSource1" runat="server"
17 ConnectionString="<%$ ConnectionStrings:ChtNorthwind %>"
18 SelectCommand="SELECT * FROM [authors222]"
19 onselected="SqlDataSource1_Selected"></asp:SqlDataSource>
20 </div>
21 </form>
22 </body>
23 </html>
24
其中,authors222是不存在的表。
再看后台代码:
1 using System;
2 using System.Collections;
3 using System.Configuration;
4 using System.Data;
5 using System.Linq;
6 using System.Web;
7 using System.Web.Security;
8 using System.Web.UI;
9 using System.Web.UI.HtmlControls;
10 using System.Web.UI.WebControls;
11 using System.Web.UI.WebControls.WebParts;
12 using System.Xml.Linq;
13
14 public partial class Demo23 : System.Web.UI.Page
15 {
16 protected void Page_Load(object sender, EventArgs e)
17 {
18
19 }
20 protected void SqlDataSource1_Selected(object sender, SqlDataSourceStatusEventArgs e)
21 {
22 if (e.Exception != null)
23 {
24 Label1.Text = e.Exception.Message;
25
26 e.ExceptionHandled = true; //这个表示异常已由开发人员自行处理
27 }
28 }
29 }
30
2 using System.Collections;
3 using System.Configuration;
4 using System.Data;
5 using System.Linq;
6 using System.Web;
7 using System.Web.Security;
8 using System.Web.UI;
9 using System.Web.UI.HtmlControls;
10 using System.Web.UI.WebControls;
11 using System.Web.UI.WebControls.WebParts;
12 using System.Xml.Linq;
13
14 public partial class Demo23 : System.Web.UI.Page
15 {
16 protected void Page_Load(object sender, EventArgs e)
17 {
18
19 }
20 protected void SqlDataSource1_Selected(object sender, SqlDataSourceStatusEventArgs e)
21 {
22 if (e.Exception != null)
23 {
24 Label1.Text = e.Exception.Message;
25
26 e.ExceptionHandled = true; //这个表示异常已由开发人员自行处理
27 }
28 }
29 }
30