Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How to invoke events across User Controls in ASP.NET

0.00/5 (No votes)
11 Sep 2006 2  
How to use self-registering objects and Context.Items to invoke events across User Controls.

The Problem

I have on several occasions experienced problems when events were raised in one User Control that must be received in another User Control in a different layer.

Handling events from controls on a page is easy, but it gets harder once we refactor common code into user controls. And the difficulties increase with each added User Control layer. One scenario is sending an event from a User Control to the page, another is sending an event from a User Control inside of a User Control to a User Control inside of a different User Control.

Just to complicate things even more, we can't assign to events in C#. So a naive solution would be to add event handlers to raise new events. To do that, we need to duplicate the event declaration plus the event handler code for every User Control the event has to pass through. That smells like The Middle Man anti-pattern.

I am not too fond of bubbled events, either. I find them too hard to discover, and too implicit. There is nothing in the code to reveal their existence or usage. I prefer a more explicit solution.

One Possible Solution

I want my code to avoid all the middle men, to be foolproof with clear and visible usage, and to be simple to use. That suggests we should declare our events the usual way, all listeners should register themselves the usual way, there should be no more than one line of code to forward the event, and the forwarding should happen once.

So we need something to expose the events and methods to invoke them:

  • Events and notification methods come in pairs.
  • Notifiers and listeners use the same object.
  • The object will keep track of the event handler delegates in Context.Items.

In the provided code, I have one User Control with two buttons to invoke events, and another User Control to receive them. I used a regular Button and an ImageButton to demonstrate event handlers with different argument types.

The sender control uses the following code to invoke the events:

private ButtonEvents events;
        
private void Page_Load (object sender, EventArgs e)
{
    events = new ButtonEvents(Context.Items);
}

private void uxButton_Click (object sender, EventArgs e)
{
    events.ClickButton(sender, e);
}

private void uxImage_Click (object sender, ImageClickEventArgs e)
{
    events.ClickImageButton(sender, e);
}

The receiver control uses this code to register to those events:

private void Page_Load (object sender, EventArgs e)
{
    ButtonEvents events = new ButtonEvents(Context.Items);
    events.ImageButtonClicked += 
             new ImageClickEventHandler(events_ImageButtonClicked);
    events.ButtonClicked += new EventHandler(events_ButtonClicked);
}

The ButtonEvents class needs a little more work than usual to implement, but not much:

internal class ButtonEvents
{
    private CachedEvent buttonEvent;
    private CachedEvent imageButtonEvent;

    public ButtonEvents (IDictionary items)
    {
        buttonEvent = new CachedEvent(items, "Button");
        imageButtonEvent = new CachedEvent(items, "ImageButton");
    }

    public event ImageClickEventHandler ImageButtonClicked
    {
        add { imageButtonEvent.Add(value);}
        remove { imageButtonEvent.Remove(value);}
    }

    public event EventHandler ButtonClicked
    {
        add { buttonEvent.Add(value);}
        remove { buttonEvent.Remove(value);}
    }

    public void ClickButton (object sender, EventArgs e)
    {
        buttonEvent.Invoke(sender, e);
    }

    public void ClickImageButton (object sender, ImageClickEventArgs e)
    {
        imageButtonEvent.Invoke(sender, e);
    }
}

The ButtonEvents class makes use of the CachedEvent helper object. This is the object which implements the real solution. The CachedEvents takes a dictionary and a key in its constructor, so it knows where to store the event handlers. The event handlers are delegates, and are stored as such:

public CachedEvent (IDictionary items, object key)
{
    this.items = items;
    this.key = key;
}

private Delegate Listeners
{
    set { items [key] = value; }
    get { return (Delegate) items [key]; }
}

There are two helper methods to register and unregister event listeners:

public void Add (MulticastDelegate newListener)
{
    Listeners = Delegate.Combine(Listeners, newListener);
}

public void Remove (MulticastDelegate formerListener)
{
    Listeners = Delegate.Remove(Listeners, formerListener);
}

And finally, the method to invoke the event:

public void Invoke (object sender, EventArgs arguments)
{
    Delegate listeners = Listeners;
    if (listeners != null)
        listeners.DynamicInvoke(new object[] {sender, arguments});
}

Points of Interest

History

  • Article submitted - Sep 12, 2006.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here