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


Anonymous said...

My friend and I were recently talking about how technology has become so integrated in our day to day lives. Reading this post makes me think back to that discussion we had, and just how inseparable from electronics we have all become.

I don't mean this in a bad way, of course! Ethical concerns aside... I just hope that as memory gets less expensive, the possibility of downloading our memories onto a digital medium becomes a true reality. It's one of the things I really wish I could encounter in my lifetime.

(Posted on Nintendo DS running [url=]R4i SDHC[/url] DS OperaMod)

Anonymous said...

Reading these kind of posts reminds me of just how technology truly is undeniably integral to our lives in this day and age, and I can say with 99% certainty that we have passed the point of no return in our relationship with technology.

I don't mean this in a bad way, of course! Ethical concerns aside... I just hope that as memory gets cheaper, the possibility of downloading our memories onto a digital medium becomes a true reality. It's a fantasy that I daydream about all the time.

(Posted on Nintendo DS running [url=]R4i[/url] DS SKu2)

Anonymous said...

Good brief and this fill someone in on helped me alot in my college assignement. Say thank you you on your information.

Anonymous said...

[b]Queres ganar dinero desde tu casa y buscas informacion[/b]
Nosotros hemos encontrado la mejor pagina web en internet de como trabajo casa. Como nos ha sido de utilidad a nosotros, tambien les puede ser de interes para ustedes. No son unicamente formas de ganar dinero con su pagina web, hay todo tipo de formas de ganar dinero en internet...
[b][url=][img][/img][/url]Te recomendamos entrar a [url=][/url][url=][img][/img][/url][/b]

Anonymous said...

You have to express more your opinion to attract more readers, because just a video or plain text without any personal approach is not that valuable. But it is just form my point of view

Post a Comment

Please make sure that the question you ask is somehow related to the post you choose. Otherwise you post your general question in Forum section.

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 !!!