Pranay Rana: Exposing Custom event from custom control

Wednesday, January 18, 2012

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 id="spnRequired" runat="server"><b class="contentframework-required-asterisk">*</b></span>
    <asp:label id="lblText" runat="server" wrap="false"></asp:label>
     <asp:dropdownlist id="ddlDropDown" onselectedindexchanged="ddlDropDown_SelectedIndexChanged" runat="server" width="137px">
                    </asp:dropdownlist>
     <asp:requiredfieldvalidator controltovalidate="ddlDropDown" enableclientscript="False" errormessage="Selection Invalid!" forecolor="#FF0000" id="valList" initialvalue="0" runat="server">
 
</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" %>
    
    

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
 
    /// 
    /// Add Item to combo box
    /// 
    /// Name of the item

///  
Value of the item
public void AddItem(string pName, string pValue)
     {
         ddlDropDown.Items.Add(new ListItem(pName, pValue));
     }
         ///  


     /// Bind List to combo box , i.e data soruce for the combo box     
///
 
     /// Type of list 
     ///  
List of Items to bind///  
Name of the property display as text combo///  
Value Name of the property bind with the item
public void BindList(IList 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();
     }
 } 

No comments:

Post a Comment