How To: Expose Events from UserControl






4.89/5 (7 votes)
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;
PopulateDropStates(selecteditem);
}
The PopulateDropStates
clears all the items in the 2nd dropdown and recreates the items.
private void PopulateDropStates(string p)
{
this.drpState.Items.Clear();
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);
this.drpState.Items.Add(item);
}
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
{
add
{
if(this._drp1SelectionChanged == null)
this._drp1selectionChanged += value;
}
remove
{
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"
ID="ctrySelectbox"
OnDropDownCountrySelectionChanged="ctrySelectBox_DropDownCountrySelectionChanged">
</uc1:CountryStateSelectBox>
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)
:base()
{
this._list = list;
}
public DropDownList DropDown
{
get
{
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.
Conclusion
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.