How to : Expose events from UserControl

In ASP.NET, web user control is used very often to implement modular coding. We replace the repeating blocks of code into an 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 think 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 comprises 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 is associated with any child control within the user control. We have to rely only on the OnLoad event of an 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 create a country/state selection box as an 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 populated 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 to access only the part of the control that I want to expose. Now let say I want to do something when my 2nd dropdown is changed. Aah, I cant do that because as the control is not public, I cant 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 inthe page, just register the event in the page_load like this :
this.objCountrySelect.DropDownCountrySelectionChanged += new

Or you can directly add the event to 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.


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

Thanks for reading my blog.
Shout it Submit this story to DotNetKicks Bookmark and Share
Read Disclaimer Notice

Author's new book

Abhishek authored one of the best selling book of .NET. It covers ASP.NET, WPF, Windows 8, Threading, Memory Management, Internals, Visual Studio, HTML5, JQuery and many more...
Grab it now !!!