GridViewUpdated事件
这个事件处理程序的第二个输入参数是一个GridViewUpdatedEventArgs类型的对象,它有三个关于处理异常的属性:
· Exception –获取更新操作过程中引发的异常;如果没有抛出异常,该属性的值为null
· ExceptionHandled –获取或设置一个值,它指示在更新操作过程中所引发的异常是否已在RowUpdated事件处理程序中得到处理;如果设为false(默认值),该异常将被重新引发,漏出到ASP.NET运行时
· KeepInEditMode – 如果设置为true,GridView当前编辑行将维持在编辑模式;如果设置为false(默认值),当前行将恢复到只读模式
那么我们的代码应该检测Exception是否为null,不是null则意味着执行此操作时引发了一个异常。如果是这样,我们则希望:
· 在ExceptionDetails控件中显示一个对用户友好的提示信息
· 指示异常已经被处理
· 让当前行保持编辑模式
下面的代码实现了上述的目的:
1
protected void GridView1_RowUpdated(object sender, GridViewUpdatedEventArgs e)
2{
3 if (e.Exception != null)
4 {
5 // Display a user-friendly message
6 ExceptionDetails.Visible = true;
7 ExceptionDetails.Text = "There was a problem updating the product. ";
8
9 if (e.Exception.InnerException != null)
10 {
11 Exception inner = e.Exception.InnerException;
12
13 if (inner is System.Data.Common.DbException)
14 ExceptionDetails.Text += "Our database is currently experiencing problems. Please try again later.";
15 else if (inner is NoNullAllowedException)
16 ExceptionDetails.Text += "There are one or more required fields that are missing.";
17 else if (inner is ArgumentException)
18 {
19 string paramName = ((ArgumentException)inner).ParamName;
20 ExceptionDetails.Text += string.Concat("The ", paramName, " value is illegal.");
21 }
22 else if (inner is ApplicationException)ExceptionDetails.Text += inner.Message;
23 }
24
25 // Indicate that the exception has been handled
26 e.ExceptionHandled = true;
27
28 // Keep the row in edit mode
29 e.KeepInEditMode = true;
30 }
31}
32
2{
3 if (e.Exception != null)
4 {
5 // Display a user-friendly message
6 ExceptionDetails.Visible = true;
7 ExceptionDetails.Text = "There was a problem updating the product. ";
8
9 if (e.Exception.InnerException != null)
10 {
11 Exception inner = e.Exception.InnerException;
12
13 if (inner is System.Data.Common.DbException)
14 ExceptionDetails.Text += "Our database is currently experiencing problems. Please try again later.";
15 else if (inner is NoNullAllowedException)
16 ExceptionDetails.Text += "There are one or more required fields that are missing.";
17 else if (inner is ArgumentException)
18 {
19 string paramName = ((ArgumentException)inner).ParamName;
20 ExceptionDetails.Text += string.Concat("The ", paramName, " value is illegal.");
21 }
22 else if (inner is ApplicationException)ExceptionDetails.Text += inner.Message;
23 }
24
25 // Indicate that the exception has been handled
26 e.ExceptionHandled = true;
27
28 // Keep the row in edit mode
29 e.KeepInEditMode = true;
30 }
31}
32
在这个事件处理程序中,首先检测e.Exception是否为null。如果不是,设置ExceptionDetails控件的Visible属性为true、设置它的Text属性为“There was a problem updating the product.”。
e.Exception对象的InnerException
当前抛出的异常详细信息则保存在e.Exception对象的InnerException属性里。检查这个内部异常,如果它是特定的类型,则把一些额外的有用的信息附加到ExceptionDetails标签的Text属性。最后,ExceptionHandled和KeepInEditMode属性都设置为true。