2008-12-04 103 views
2

你如何處理Web用戶控制事件?我注意到我的自定義Web用戶控件有一個事件調用OnError,但是當我調整控件失敗時它永遠不會觸發。該控件基本上是一個自定義的gridview控件。我通過網絡搜索網絡用戶控件事件處理,但是我沒有找到一篇文章解決我尋找的問題。有人可以做一個快速解釋或指向正確的方向嗎?在asp.net頁面上處理Web用戶控制錯誤

謝謝

回答

1

你沒有提到ASP.NET的味道,所以我將假設VB-C#與連接事件處理程序的例外情況大致相同。

你希望看到的正常模式是沿着這些路線的東西:

用戶控制 「的MyUserControl」 代碼隱藏

Public Event MyEvent(ByVal Sender As Object, ByVal e As EventArgs) 

Private Sub SomeMethodThatRaisesMyEvent() 
    RaiseEvent MyEvent(Me, New EventArgs) 
End Sub 

頁面設計代碼

Private WithEvents MyUserControl1 As System.Web.UI.UserControls.MyUserControl 

頁或其他控制,它包裝的MyUserControl實例代碼隱藏

Private Sub MyUserControlEventHandler(ByVal Sender As Object, ByVal e As EventArgs) _ 
    Handles MyUserControl.MyEvent 

    Response.Write("My event handled") 

End Sub 

在某些情況下,你看到的東西稱爲事件冒泡不遵循這種模式完全吻合。但是從處理用戶控件到包裝控件或其所在頁面的事件的基本意義上來說,這就是你期望它能夠工作的方式。

0

我有一個自定義控件拋出的異常沒有觸發Error事件。因此我無法從該控件捕獲異常並在ASP.NET頁面中顯示適當的消息。

這是我做的。我裹在一個try..catch塊自定義控件的代碼,並解僱了Error事件自己,像這樣:

 
// within the custom control 
try 
{ 
    // do something that raises an exception 
} 
catch (Exception ex) 
{ 
    OnError(EventArgs.Empty); // let parent ASP.NET page handle it in the 
     // Error event 
}

的ASP.NET頁面中使用Error事件這樣處理異常:

<script runat="server"> 
    void MyCustomControl_Error(object source, EventArgs e) 
    { 
     MyCustomControl c = source as MyCustomControl; 

     if (c != null) 
     { 
      // Notice that you cannot retrieve the Exception 
      // using Server.GetLastError() as it will return null 

      Server.ClearError(); 
      c.Visible = false; 

      // All I wanted to do in this case was to hide the control 
     } 
    } 
</script> 

<sd:MyCustomControl OnError="MyCustomControl_Error" runat="server" />