ASP.NET Event delegation between user controls
Posted
by Ishan
on Stack Overflow
See other posts from Stack Overflow
or by Ishan
Published on 2010-03-31T03:16:00Z
Indexed on
2010/03/31
3:23 UTC
Read the original article
Hit count: 379
Give the following control hierarchy on a ASP.NET page:
- Page
- HeaderControl (User Control)
- TitleControl (Server Control)
- TabsControl (User Control)
- other controls
- HeaderControl (User Control)
I'm trying to raise an event (or some notification) in the TitleControl that bubbles to the Page
level. Then, I'd like to (optionally) register an event handler at the Page codebehind that will take the EventArgs
and modify the TabsControl in the example above. The important thing to note is that this design will allow me to drop these controls into any Page and make the entire system work seamlessly if the event handler is wired up. The solution should not involve a call to FindControl()
since that becomes a strong association. If no handler is defined in the containing Page, the event is still raised by TitleControl but is not handled.
My basic goal is to use event-based programming so that I can decouple the user controls from each other. The event from TitleControl is only raised in some instances, and this seemed to be (in my head) the preferred approach. However, I can't seem to find a way to cleanly achieve this.
Here are my (poor) attempts:
Using HttpContext.Current.Items
Add the EventArgs to the Items collection on TitleControl and pick it up on the TabsControl. This works but it's fundamentally hard to decipher since the connection between the two controls is not obvious.
Using Reflection
Instead of passing events, look for a function on the container Page directly within TitleControl as in:
Page.GetType().GetMethod("TabControlHandler").Invoke(Page, EventArgs);
This will work, but the method name will have to be a constant that allPage
instances will have to defined verbatim.
I'm sure that I'm over-thinking this and there must be a prettier solution using delegation, but I can't seem to think of it. Any thoughts?
© Stack Overflow or respective owner