You can use the BubbleEvent concept for this. BubbleEvent raises the management hierarchy until someone can handle it. GridView and Repeater controls do this with their Row / ItemCommand events.
You can implement it in WebUserControl1, turning it into a standard event for the page (for example, GridView):
Class UserControl1 ' Parent Protected Override Function OnBubbleEvent(sender as Object, e as EventArgs) as Boolean Dim c as CommandEventArgs = TryCast(e, CommandEventArgs) If c IsNot Nothing Then RaiseEvent ItemEvent(sender, c) Return True ' Cancel the bubbling, so it doesn't go up any further in the hierarchy End If Return False ' Couldn't handle, so let it bubble End Function Public Event ItemEvent as EventHandler(Of CommandEventArgs) End Class Class UserControlB ' Child Protected Sub OnClicked(e as EventArgs) ' Raise a direct event for any handlers attached directly RaiseEvent Clicked(Me, e) ' And raise a bubble event for parent control RaiseBubbleEvent(Me, New CommandEventArgs("Clicked", Nothing)) End Sub Protected Sub OnMoved(e as EventArgs) ' Raise a direct event for any handlers attached directly RaiseEvent Moved(Me, e) ' And raise a bubble event for parent control RaiseBubbleEvent(Me, New CommandEventArgs("Moved", Nothing)) End Sub End Class Class PageA Sub UserControl1_ItemEvent(sender as Object, e as CommandEventArgs) Handles UserControl1.ItemEvent Response.Write(sender.GetType().Name & " was " & e.CommandName) End Sub End Class
Or do it right on the page. UserControlB (Child) is the same as above, and UserControl1 (Parent) does not need to do anything - by default OnBubbleEvent returns False, so the event bubbles up:
Class PageA Protected Override Function OnBubbleEvent(sender as Object, e as EventArgs) as Boolean If sender Is UserControlB Then Dim c as CommandEventArgs = TryCast(e, CommandEventArgs) If c IsNot Nothing Then Response.Write(sender.GetType().Name & " was " & c.CommandName) Else Response.Write(sender.GetType().Name & " raised an event, with " & e.GetType().Name & " args) End If Return True ' Cancel the bubbling, so it doesn't go up any further in the hierarchy End If Return False ' Not handled End Function End Class
If your initial event comes from a server control (e.g. Button.Click), then it will be encoded to raise the bubble event already - so UserControlB (Child) does not need to do anything to get this parent. You just need to call RaiseBubbleEvent for any of your custom events or if you somehow transform EventArg.
source share