Click here to Skip to main content
15,885,216 members
Articles / Programming Languages / C#

How To: Expose Events from UserControl

Rate me:
Please Sign up or sign in to vote.
4.89/5 (7 votes)
11 Jan 2010CPOL4 min read 45.7K   15   1
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.

Eventdemo.JPG

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):

C#
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.

C#
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.

C#
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:

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

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

XML
<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.

C#
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.

License

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


Written By
President
India India
Did you like his post?

Oh, lets go a bit further to know him better.
Visit his Website : www.abhisheksur.com 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.
http://bit.ly/EXPERTCookBook

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.

Working as a VP product of APPSeCONNECT, an integration platform of future, he does all sort of innovation around the product.

Have any problem? Write to him in his Forum.

You can also mail him directly to abhi2434@yahoo.com

Want a Coder like him for your project?
Drop him a mail to contact@abhisheksur.com

Visit His Blog

Dotnet Tricks and Tips



Dont forget to vote or share your comments about his Writing

Comments and Discussions

 
GeneralMy vote of 5 Pin
dnyan8617-Sep-12 19:15
dnyan8617-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.