Sunday, September 21, 2008

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” %>



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
”);
}
}

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″ %>





Untitled Page




runat=”server”>

Chirag
Dipak
Shailesh












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
Selected Value: “ +
ddlTemp.SelectedItem.Text + “
”);
}
}

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.

No comments: