Thursday, August 23, 2007

Raise event from user control to main page / Event delegation from user control to aspx page in ASP.NET,C#

          "What is delegate?" we all have faced this question in one or more interview. :) and the most common answer is "Function pointer". Here I am showing a simple example of delegate. I have one user control and one aspx page. The user control contains one button. When user click on this button I will call a method on main page using delegate. Here is my user control,

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="Dalegate_WebUserControl" %>

<
asp:Button ID="btnTest" runat="server" Text="I am Inside User Control" OnClick="btnTest_Click" />

Fig - (1) WebUserControl.ascx

            On WebUserControl.ascx.cs I have written simple delegate and event handler as shown below,

public partial class Dalegate_WebUserControl : System.Web.UI.UserControl
{

    // Delegate declaration
    public delegate void OnButtonClick(string strValue);

    // Event declaration
    public event OnButtonClick btnHandler;
   
    // Page load
    protected void Page_Load(object sender, EventArgs e)
    {
       
    }

    protected void btnTest_Click(object sender, EventArgs e)
    {
           // Check if event is null
           if (btnHandler != null)
               btnHandler(string.Empty);

           // Write some text to output
           Response.Write("User Control's Button Click <BR/>");
    }
}

Fig - (2) WebUserControl.ascx.cs

          Above code first check whether btnHandler is not null and than raise the event by passing argument. You can pass any number of argument in event. You need to change public delegate void OnButtonClick(string strValue) and btnHandler(string.Empty) lines for changing number of arguments. Now take a look at aspx page,

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Dalegate_Default" %>

<%@
Register Src="WebUserControl.ascx" TagName="WebUserControl" TagPrefix="uc1" %>

<!
DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<
html xmlns="http://www.w3.org/1999/xhtml" >
<
head runat="server">
    <title>Untitled Page</title>
</
head>
<
body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="lblText" Text="I am On Main Page : "
                   runat
="server"></asp:Label>
        <asp:DropDownList ID="ddlTemp" runat="server">
            <asp:ListItem>Chirag</asp:ListItem>
            <asp:ListItem>Dipak</asp:ListItem>
            <asp:ListItem>Shailesh</asp:ListItem>
        </asp:DropDownList>
        <br />
        <br />
        <uc1:WebUserControl ID="WebUserControl1"
           runat="server" />    
    </div>
    </form>
</
body>
</
html>

Fig - (3) Default.aspx

          Default.aspx has one drop down list and a user control as shown in above code. Lets look at cs file,

public partial class Dalegate_Default : System.Web.UI.Page
{
      protected void Page_Load(object sender, EventArgs e)
      {
             // Declare and Define Event of User Control. When User
             // Clicks on button (which is inside UserControl)
             // below event is raised as I have called raised that
             // event on Button Click
             WebUserControl1.btnHandler += new 
             Dalegate_WebUserControl
.OnButtonClick
            
(WebUserControl1_btnHandler);
       
      }

      void WebUserControl1_btnHandler(string strValue)
      {
             Response.Write("Main Page Event<BR/>Selected
                  Value: "
+ ddlTemp.SelectedItem.Text + "<BR/>");
      }   
}

 Fig - (4) Default.aspx.cs

            Now when you run the application and clicks on button you can see that when user click on button the user control raise the click event and calls the WebUserControl1_btnHandler(string strValue) method on main page.

Happy Programming !!!

19 comments:

Anonymous said...

thanks mate !

Anonymous said...

thanks mate !!!

Vee said...

Very helpful.
Thanks buddies

Anonymous said...

Thanks you..its helps me..

Anonymous said...

thx !!! is great!!

Programmer said...

You da mon! Thank you!!!

Esco from Finland said...

Thanks a lot! Excellent article. Very simple. No any extra garbage. You are software wizard!

Anonymous said...

nice work! this was v.useful

mike from australia

Scott said...

How can I access the button name in btnTest_Click?

Rama Charan said...

Thanks for the Good Article!
Short & crisp!

Anonymous said...

Hi Chirag,
I must appreciate the efforts put in by you in making this article.
Nice dude.

But, I am just wondering after going through your profile , what about the OOP's rule of encapsulation that you haven't considered while explaining the method of accessing a control's event.

Anyways, nice article.

Imran said...

Hai chirag
nice solutions

Can u please suggest me how to do the upload functionality like the excel sheet data into database(sql server) directly. using win forms.
i'll be waiting for ur answer some what urgent.

Adnan said...

Excellent Post. Thats exactly what I was looking for!

Adnan

Anonymous said...

Hi Chirag,

May I know how do I subscribe for the click event when I load the user control dynamically?

Ramesh

Anonymous said...

Thanks a lot ,, it helped a lot ,,

MATTXtwo said...

Looks good..
How about web uc with mouseevent handler that raise an event to main page?
an example:
web uc with image that add attribute with onmouseenter,onmouseleave,onmousedown event to change the image

Dolly(Prachi)!!! said...

Seriously it helped me a lot to clearly understand event delegates..
good work keep it up:)

Anonymous said...

Thanks, very useful !!!!!!

CafeCat said...

That's simple! Oh, I'm so surprised! Thank you, this post helps me a lot, and I learned about "delegate". I find it very very useful!!