Reputation: 10037
How do you handle the Web User Control event? I notice my custom web user control have a event call OnError but it never fire when i tweak the control to fail. The control is basically a custom gridview control. I search for web user control event handling over the net but i haven't find a article that address what i looking for. Can someone do a quick explanation or point me to the right direction?
thank
Upvotes: 2
Views: 3928
Reputation:
I had an issue with a custom control that was throwing exceptions which were not firing Error
event. Thus I could not catch exceptions from this control and display appropriate message in the ASP.NET page.
Here is what I did. I wrapped the code in the custom control in a try..catch
block and fired the Error
event myself, like this:
// 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 }
The ASP.NET page was handling the exception using the Error
event like this:
<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" />
Upvotes: 0
Reputation: 39806
You didn't mention what flavour of ASP.NET, so I'll make the assumption of VB - C# is largely the same with the exception of how the event handler is attached.
The normal pattern you would expect to see is something along these lines:
User Control "MyUserControl" CodeBehind
Public Event MyEvent(ByVal Sender As Object, ByVal e As EventArgs)
Private Sub SomeMethodThatRaisesMyEvent()
RaiseEvent MyEvent(Me, New EventArgs)
End Sub
Page Designer Code
Private WithEvents MyUserControl1 As System.Web.UI.UserControls.MyUserControl
Page or other Control that wraps MyUserControl instance CodeBehind
Private Sub MyUserControlEventHandler(ByVal Sender As Object, ByVal e As EventArgs) _
Handles MyUserControl.MyEvent
Response.Write("My event handled")
End Sub
In some instances, you see something called Event Bubbling which doesn't follow this kind of pattern exactly. But in the basic sense of handling events from a user control to a wrapper control or the page it sits in, that's how you would expect it to work.
Upvotes: 1