Apr 25 2006

Define Custom Events in UserControls

Category: ASP.NET 1.x | ASP.NET 2.0 - GeneralBil@l @ 17:55

A very common question on the ASP.NET forums is:

How to define an event in a UserControl, and process this event in the Page holding this UserControl?

The answer is simple, follow this post, and you will be able to define your own events very easily.

We have the following UserControl file together with the Code Behind as follows:

<%@ Control Language="c#" AutoEventWireup="false" Codebehind="EventUserControl.ascx.cs" Inherits="UserControls.EventUserControl" TargetSchema="http://schemas.microsoft.com/intellisense/ie5"%>
<P>Choose a Country:&nbsp;&nbsp;
 <asp:DropDownList id="ddlCountry" runat="server">
  <asp:ListItem Value="Australia">Australia</asp:ListItem>
  <asp:ListItem Value="Canada">Canada</asp:ListItem>
  <asp:ListItem Value="Kuwait">Kuwait</asp:ListItem>
  <asp:ListItem Value="Lebanon">Lebanon</asp:ListItem>
  <asp:ListItem Value="Saudi Arabia">Saudi Arabia</asp:ListItem>
  <asp:ListItem Value="USA">USA</asp:ListItem>
 </asp:DropDownList></P>
<P>
 <asp:Button id="btnSubmit" runat="server" Text="Select"></asp:Button></P>

The code behind has been enriched with many comments to make your life easy while reading the code:

namespace UserControls
{
 #region Imports
 using System;
 using System.Data;
 using System.Drawing;
 using System.Web;
 using System.Web.UI.WebControls;
 using System.Web.UI.HtmlControls;
 #endregion

 #region Class Declaration
 public class EventUserControl : System.Web.UI.UserControl
 {
  #region Controls
  protected System.Web.UI.WebControls.DropDownList ddlCountry;
  protected System.Web.UI.WebControls.Button btnSubmit;
  #endregion
 
  #region Delegate Declaration
  // Step 2
  // Define the handler that will handle the event fired by the Button
  // It takes two arguments, the sender and a parameter of type ButtonEventArgs.
  // The ButtonEventArgs will hold the country that was selected
  // So the event handler in the ASPX page, should have the same signature
  // as that of the handler, of the event fired by the UserControl
  public delegate void ButtonClickedHandler (object Sender, ButtonEventArgs e);
  #endregion

  #region Event Definition
  // Step 3
  // Define an instance of the event handler,
  // this instance shall be filled with the event handler
  // that will be defined in the ASPX page
  public event ButtonClickedHandler ButtonClicked;
  #endregion

  #region OnEvent Event
  // Step 4
  // You always need the "On" method that will check if
  // the above event has been registered with an event handler or not
  // if it has been registered, then it will fire that event in the ASPX page
  // the page that is holding the UserControl
  public virtual void OnButtonClicked(ButtonEventArgs e)
  {
   if (ButtonClicked != null)
   {
    ButtonClicked(this,e);
   }
  }
  #endregion

  #region Control Events
  private void Page_Load(object sender, System.EventArgs e)
  {
   
  }
  private void btnSubmit_Click(object sender, System.EventArgs e)
  {
   string ddlSelectedValue = this.ddlCountry.SelectedItem.Text;

   // Step 5
   // Get a new instance of ButtonClickedArgs, fill it with the
   // Country that has been selected
   ButtonEventArgs objBCA = new ButtonEventArgs();
   objBCA.CountrySelected = ddlSelectedValue;

   // Call the method that will fire the event in ASPX page
   OnButtonClicked(objBCA);

  }
  #endregion

  #region Web Form Designer generated code
  override protected void OnInit(EventArgs e)
  {
   InitializeComponent();
   base.OnInit(e);
  }

  private void InitializeComponent()
  {
   this.btnSubmit.Click += new System.EventHandler(this.btnSubmit_Click);
   this.Load += new System.EventHandler(this.Page_Load);
  }
  #endregion
 }
 #endregion

 #region ButtonEventArgs Definition
 // Step 1
 // An object can extend the EventArgs object
 // and adds its own fields to it
 // to be able lto gather more data
 // about the event fired
 public class ButtonEventArgs : EventArgs
 {
  #region Private Fields
  private string m_CountrySelected;
  #endregion

  #region Public Properties
  public string CountrySelected
  {
   get {return this.m_CountrySelected;}
   set {this.m_CountrySelected = value;}
  }
  #endregion

  #region Constructors
  public ButtonEventArgs()
  {}

  public ButtonEventArgs(string p_CountrySelected)
  {
   this.m_CountrySelected = p_CountrySelected;
  }
  #endregion
 }
 #endregion

}

Then, the ASPX page that will hold the UserControl is defined below, through both the Code-Behind and ASPX page:

<%@ Page language="c#" Codebehind="TestEventUserControl.aspx.cs" AutoEventWireup="false" Inherits="UserControls.TestEventUserControl" %>
<%@ Register TagPrefix="uc1" TagName="EventUserControl" Src="EventUserControl.ascx" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
 <HEAD>
 </HEAD>
 <body MS_POSITIONING="GridLayout">
  <form id="Form1" method="post" runat="server">
   <uc1:EventUserControl id="EventUserControl1" runat="server"></uc1:EventUserControl>
  </form>
 </body>
</HTML>

The code behind is as follows:

#region Imports
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
#endregion

namespace UserControls
{
 public class TestEventUserControl : System.Web.UI.Page
 {
  #region Define UserControl
  // Step 1
  // Define an instance of the UserControl
  // to be able to add an event handler
  protected EventUserControl EventUserControl1;
  #endregion

  private void Page_Load(object sender, System.EventArgs e)
  {
   
  }
  
  // Step 3
  // The event handler, whose signature is the same as the ButtonClickEventHandler
  // that will be used to handle the event fired by the UserControl
  private void EventUserControl_Fired(object Sender, ButtonEventArgs e)
  {
   Response.Write("You have choosen: " + e.CountrySelected);
  }

  #region Web Form Designer generated code
  override protected void OnInit(EventArgs e)
  {
   InitializeComponent();
   base.OnInit(e);
  }
  
  private void InitializeComponent()
  {   
   this.Load += new System.EventHandler(this.Page_Load);

   // Step 2
   // Registering the ButtonClick event with the event handler on the ASPX page
   this.EventUserControl1.ButtonClicked += new UserControls.EventUserControl.ButtonClickedHandler(EventUserControl_Fired);
  }
  #endregion
 }
}

Now, you can create a new Web Application, make sure to name the Application UserControls, create a user control called EventUserControl.ascx and a page called TestEventUserControl.aspx. Those names are just named so that you can run the above code without any changes, however, feel free to change them to whatever names you want.

Hope I was able to make it easy on you, on how to define events inside UserControl and handle them in the ASPX page that is holding the UserControl.

HTH,

Regards

 

Tags: ,

Comments are closed