Click here to Skip to main content
13,048,406 members (97,809 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


15 bookmarked
Posted 11 Jan 2010

How To: Expose Events from UserControl

, 11 Jan 2010
Rate this:
Please Sign up or sign in to vote.
Pass data from a User control easily using Custom Events. I have added one sample application with this.

In ASP.NET, web user control is used very often to implement modular coding. We replace the repeating blocks of code into a User Control which we add in our web page when required. Technically speaking, ASP.NET web user control is just a subset of a Web Form. You have designer where you can declare controls that comprise the user control, you can even manipulate the code from the code-behind class. The only thing that you need is to handle appropriate events within the User Control and add that in the aspx page.

The Problem

Generally we place all the controls that comprise the user control private, so that we disallow the pages to access the controls within the user control directly. Thus, we cannot access any events that are associated with any child control within the user control. We have to rely only on the OnLoad event of a user control which most of the time could not be used properly.
To help in such a situation, we need to create our custom events and expose them from the user control so that we can handle them easily to the page and do appropriate tasks.
In this article, I am going to discuss how to do this.

To make the example most simple, I have created a country/state selection box as a user control. The Usercontrol contains 2 DropdownList items which are placed one after another. There are a few behaviours of the dropdownlist controls. The second dropdown is actually populated from the data of the first one.


Thus when I choose Canada from the first dropdown, I can choose the other states from the second. To do this, I need to handle the SelectedIndexChanged event and populate the second dropdown. Just see the code below (I used XML data for better understanding):

protected void drpCountry_selectedIndexChanged(object sender, EventArgs e)
 string selecteditem = drpCountry.SelectedValue;

The PopulateDropStates clears all the items in the 2nd dropdown and recreates the items.

private void PopulateDropStates(string p)
      XElement container = doc.Descendants("country").FirstOrDefault(
          item => item.Attribute("code").Value.Equals(p));
      var elements = container.Descendants();
      foreach (XElement elem in elements)
          ListItem item = new ListItem(elem.Attribute("name").Value
                              , elem.Attribute("code").Value);
      if (this.drpState.Items.Count > 0)
          this.drpState.Items[0].Selected = true;  

I have made the dropdownlist private and which lets me access only the part of the control that I want to expose. Now let's say I want to do something when my 2nd dropdown is changed. Aah, I can't do that because as the control is not public, I can't handle the events. So I need to formulate a proxy event from the control and generate that event whenever the selectedindex of the second DropDownlist is changed.

Declaring an Event

Event is an object which raises itself whenever some other behavioral change of the class is made. When an event is raised, we need to pass the actual delegate that it calls. So to work with event, we need to create a delegate which will define the signature of the event handler and the event itself.

public delegate void DropDownSelectionDelegate(
                         object sender, SelectionChangedEventArgs e);
protected event DropDownSelectionDelegate _drp1selectionChanged;
public event DropDownSelectionDelegate DropDownCountrySelectionChanged
      if(this._drp1SelectionChanged == null)
      this._drp1selectionChanged += value;
      if(this._drp1SelectionChanged != null)
       this._drp1selectionChanged -= value;
public virtual void OnDropDownCountrySelectionChanged()
 SelectionChangedEventArgs evt = new SelectionChangedEventArgs(this.drpCountry);
 if (this._drp1selectionChanged != null)
   this._drp1selectionChanged(this, evt);

We have created an instance of a delegate DropDownSelectionDelegate which is the signature of the event _drp1selectionChanged. Thus if you want to handle the event, I need to declare an event handler same to the signature of the delegate.
The event accessor is the public property which exposes the event to the outside. I have added both add/remove to ensure the event can be added and removed using this and also to ensure only one instance of the event is registered. The virtual method OnDropDownCountrySelectionChanged actually raises the event. Thus whenever the event requires invocation in the class, just use this.OnDropDownCountrySelectionChanged() and the event will be raised.

In order to handle the event in the page, just register the event in the page_load like this:

this.objCountrySelect.DropDownCountrySelectionChanged += 
			new DropDownSelectionDelegate(methodname);

Or you can directly add the event to the control itself:

<uc1:CountryStateSelectBox runat="server"



Thus the event handler ctrySelectBox_DropDownCountrySelectionChanged will get raised automatically whenever the country selection is changed.

In this example, I have used a custom class SelectionChangedEventArgs which is basically used to send data.

public class SelectionChangedEventArgs : EventArgs
       private DropDownList _list;
       public SelectionChangedEventArgs(DropDownList list)
           this._list = list;
       public DropDownList DropDown
               return this._list;

Thus the class is created just to pass the list object with the event argument.
For better understanding, you can also try out the demo application.


Thus through events you can easily raise your custom events from the control and pass data. Events come very handy when you want callbacks for long running applications. You can define an event which you raise after an interval.

Thank you for reading. Add your valuable comments if you wish.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Abhishek Sur
India India
Did you like his post?

Oh, lets go a bit further to know him better.
Visit his Website : to know more about Abhishek.

Abhishek also authored a book on .NET 4.5 Features and recommends you to read it, you will learn a lot from it.

Basically he is from India, who loves to explore the .NET world. He loves to code and in his leisure you always find him talking about technical stuffs.

Presently he is working in WPF, a new foundation to UI development, but mostly he likes to work on architecture and business classes. ASP.NET is one of his strength as well.
Have any problem? Write to him in his Forum.

You can also mail him directly to

Want a Coder like him for your project?
Drop him a mail to

Visit His Blog

Dotnet Tricks and Tips

Dont forget to vote or share your comments about his Writing

You may also be interested in...

Comments and Discussions

GeneralMy vote of 5 Pin
dnyan8617-Sep-12 19:15
memberdnyan8617-Sep-12 19:15 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170713.1 | Last Updated 11 Jan 2010
Article Copyright 2010 by Abhishek Sur
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid