Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Exposing Custom event from custom control

0.00/5 (No votes)
8 Jul 2012 1  
Exposing Custom event from custom control
In this post I m going to discuss about registering custom event in custom control. Recently In my project I have created user control it’s consist of one label control and dropdown box. This user control is common control which can be used in whole project to avoid writing repeated code for binding and also validation code for the same.

Ascx file i.e user control file
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="CommonDropDownControl.ascx.cs"
    Inherits="ValidDropDown" %>
<div>
<span  runat="server" id="spnRequired">[__strong class="contentframework-required-asterisk"__]*</span>
    <asp:label wrap="false" runat="server" id="lblText" />
     <asp:dropdownlist width="137px" runat="server" onselectedindexchanged="ddlDropDown_SelectedIndexChanged" id="ddlDropDown">
                    </asp:dropdownlist>
     <asp:requiredfieldvalidator runat="server" initialvalue="0" id="valList" forecolor="#FF0000" errormessage="Selection Invalid!" enableclientscript="False" controltovalidate="ddlDropDown">
 
</asp:requiredfieldvalidator></div>
Now as you can see in above code I have attached as requirefieldvalidator to validate the control which get fire when no value is selected by user.
But the important thing to note here is I have written SelectedChange event with the dropdown control which I want to expose, so that I can write different code on each page where it utilize. Because the problem with the usercontrol is when I attached event with the any control that is part of usercontrol event get encapsulated in the code of that usercontrol and that's why we cannot able to write different code on each page where it is utilize and require to expose.
So in following code I will show how you can expose the change event and how you can utilize it on your page when using usercontrol.

Step 1 : Register event
public event EventHandler DrpChange;
as you see in above code I have registered event of delegate type EventHandler and name of it is DrpChange. On the page I need to register DrpChange which get fire when user do change the selection in the dropdown box of the usercontrol. How I do this will so later on in this post.

Step 2 : Virtual function to handle raised event
public virtual void OnDropDownChange()
    {
        if (DrpChange != null)
        {
            this.DrpChange(this, EventArgs.Empty);
        }
    }
above code there is virtual function which handle the event raise from the page by the control. This function is responsible for calling the code written on page i.e event code written on the page.

Step 3 : Register on Change Event of dropdown in ASCX.CS file
protected void ddlDropDown_SelectedIndexChanged(object sender, EventArgs e)
    {
        this.OnDropDownChange();
    }

above code written in OnChage event of the dropdown box in ASCX.Cs file so when use made selection and raise event it call this event and than custom register event. As you can see OnDropDownChange is called from the event and in turn custom written code of the page.
In following step we are going to utilize created custom control and the custom event

Step 4 : Use User control on page and utilize expose custom event .Aspx page
<%@ Register src="Controls/CommonDropDownControl.ascx" 
   tagname="CommonDropDownControl" tagprefix="uc" %>
    <title></title>
    <form id="form1" runat="server">
<div>
<uc1:commondropdowncontrol  runat="server" labletext="Country" id="usrDrp" drpchange="usrDrp_DrpChange" autopostback="true">
    </uc1:commondropdowncontrol></div>
</form>

code register the event which is going to be fire when the selection in dropdown box of user control change.

Step 5 : write code on page for the custom event .Aspx.CS file
protected void usrDrp_DrpChange(object sender, EventArgs e)
    {
        Response.Write("event called.");
    }
so last there is code of register custom event which get executed on change of dropdwon box of user control. Note that this code is written on the page where I am utilizing the control.
For referance full code of ascx.cs file
using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
 
////////////////////////////////////////////////////////////////////////////////////
//
//    File Description  :  Common Dropdown box control
// ---------------------------------------------------------------------------------
//    Date Created            : Month DD, YYYY (Dec 01, 2011)
//    Author                      : Pranay Rana
// ---------------------------------------------------------------------------------
//    Change History
//    Date Modified           : Month DD, YYYY (e.g Jan 01, 2000)
//    Changed By        :
//    Change Description   :
//
/////////////////////////////////////////////////////////////////////////////////
public partial class ValidDropDown : System.Web.UI.UserControl
{
    #region property
    public string LableText
    {
        get
        {
            return lblText.Text;
        }
        set
        {
            lblText.Text = value;
        }
    }
   
    public bool IsRequired
    {
        get
        {
            return spnRequired.Visible;
        }
        set
        {
             valList.Visible = value;
            spnRequired.Visible = value;
        }
    }
    public bool Enabled
    {
        get
        {
            return ddlDropDown.Enabled;
        }
        set
        {
            ddlDropDown.Enabled = value;
        }
    }
    public int Count
    {
        get
        {
            return ddlDropDown.Items.Count;
        }      
    }
    public bool Clear
    {
        set
        {
            if (value)
            {
                ddlDropDown.Items.Clear();
                ddlDropDown.Items.Add(new ListItem(UIConstants.SELECT, "0"));
            }
        }
    }
  
    public string SelectedValue
    {
        get
        {
 
            return ddlDropDown.SelectedValue;
 
        }
        set
        {
            ddlDropDown.ClearSelection();
            ListItem li = ddlDropDown.Items.FindByValue(value.ToString());
            if (li != null)
                li.Selected = true;
        }
    }
    public ListItem SelectedItem
    {
        get
        {
 
            return ddlDropDown.SelectedItem;
 
        }
        set
        {
            ddlDropDown.ClearSelection();
            ListItem li = ddlDropDown.Items.FindByText(value.ToString());
            if (li != null)
                li.Selected = true;
        }
    }
    public string SelectedText
    {
        get
        {
 
            return ddlDropDown.SelectedItem.Text;
 
        }
        set
        {
            ddlDropDown.ClearSelection();
            ListItem li = ddlDropDown.Items.FindByText(value.ToString());
            if (li != null)
                li.Selected = true;
        }
    }
    public int SelectedIndex
    {
        get
        {
 
            return ddlDropDown.SelectedIndex;
 
        }
        set
        {
            ddlDropDown.SelectedIndex = value;
        }
    }
  
    public bool AutoPostBack
    {
        get
        {
            return ddlDropDown.AutoPostBack;
        }
        set
        {
            ddlDropDown.AutoPostBack = value;
        }
    }
    #endregion property
 
    #region public methods
 
    /// <summary>
    /// Add Item to combo box
    /// </summary>
    /// <param name="pName" />Name of the item
    /// <param name="pValue" />Value of the item
    public void AddItem(string pName, string pValue)
    {
        ddlDropDown.Items.Add(new ListItem(pName, pValue));
    }
 
 
    /// <summary>
    /// Bind List to combo box , i.e data soruce for the combo box
    /// </summary>
    /// <typeparam name="T">Type of list </typeparam>
    /// <param name="pLstItemInfo" />List of Items to bind
    /// <param name="pDataText" />Name of the property display as text combo
    /// <param name="pDataValue" />Value Name of the property bind with the item
    public void BindList<t>(IList<t> pLstItemInfo, string pDataText, string pDataValue)
    {
 
        ddlDropDown.ClearSelection();
        ddlDropDown.Items.Clear();
        if (pLstItemInfo != null)
        {
            ddlDropDown.DataSource = pLstItemInfo;
            ddlDropDown.DataTextField = pDataText;
            ddlDropDown.DataValueField = pDataValue;
            ddlDropDown.DataBind();
        }
 
        ddlDropDown.Items.Insert(0, new ListItem(UIConstants.SELECT, "0"));
 
    }
 
    #endregion public methods
 
 
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (LableText == string.Empty)
                tdLabel.Visible = false;
            if(ddlDropDown.Items.Count == 0)
                ddlDropDown.Items.Add(new ListItem(UIConstants.SELECT, "0"));
        }
    }
 
 
    public event EventHandler DrpChange;
 
    public virtual void OnDropDownChange()
    {
        if (DrpChange != null)
        {
            // CustomArgs  e = new CustomArgs(this.ddlDropDown);
            this.DrpChange(this, EventArgs.Empty);
        }
    }
    protected void ddlDropDown_SelectedIndexChanged(object sender, EventArgs e)
    {
        this.OnDropDownChange();
    }
}
</t> </t> 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here