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.

About SheldonS

Web developer for over 15 years mainly with Microsoft technologies from classic ASP to .NET 4. Husband, father, and aspiring amateur photographer.

Posted on November 10, 2010, in C#, User Control and tagged , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: