Click here to Skip to main content
15,886,578 members
Articles / Web Development / ASP.NET
Article

Exposing Custom event from custom control

Rate me:
Please Sign up or sign in to vote.
4.80/5 (4 votes)
8 Jul 2012CPOL2 min read 32.7K   12   3
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">*</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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India

Microsoft C# MVP (12-13)



Hey, I am Pranay Rana, working as a Team Leadin MNC. Web development in Asp.Net with C# and MS sql server are the experience tools that I have had for the past 5.5 years now.

For me def. of programming is : Programming is something that you do once and that get used by multiple for many years

You can visit my blog


StackOverFlow - http://stackoverflow.com/users/314488/pranay
My CV :- http://careers.stackoverflow.com/pranayamr

Awards:



Comments and Discussions

 
SuggestionChange title Pin
toddmo23-Jul-14 10:56
toddmo23-Jul-14 10:56 
QuestionMessage Closed Pin
8-Jul-12 15:04
mfdsaha8-Jul-12 15:04 
AnswerRe: welcome to: http://www.netetrader.com Pin
Member 19692679-Jul-12 11:48
Member 19692679-Jul-12 11:48 

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.