Blog Archives

Web User Control Events

Ever want to have an event for a Web User Control that the parent page can consume?  Well you can, and it is fairly simple.

I am not an expert since I just figured this out myself so here we go.

There are three basic things you need to do for each event.

  1. Create a public delegate variable in your User Control
  2. Create a public event event for the type of delegate
  3. Create a protected virtual method

So lets see some code.

//Public variables and methods
public delegate void ItemClickEvent(object sender, EventArgs e);
public event ItemClickEvent ItemClick;

//Protected Methods
protected virtual void OnItemClicked(object sender, EventArgs e)
    if (ItemClick != null)
        ItemClick(this, e);

The property in the page with this user control will be called OnItemClick.  Notice I do not have anything named OnItemClick.  The only public names are ItemClickEvent, which is a delegate and the event itself, ItemClick.  So I assume that .NET adds the On to the front of your event name.