Friday, October 10, 2008

Call Page Function from User Control using Delegates

This article will explain you about how to call the function which is in Page from User Control button click. This same concept can be used to get values from user control to page.


In Below example, I have created one user control which contains one textbox and button control. Whenever the user click the button, the value of the textbox should be passed in function which is available in page.


TestUserControl.ascx

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

<div>
</div>
<asp:TextBox ID ="txtVal" runat = "server" ></asp:TextBox>
<asp:Button ID = "btn" runat = "server" OnClick = "ButtonClick" Text = "PassValue" />


TestUserControl.ascx.cs

public delegate void SendMessageToPageHandler(string Msg);
public event SendMessageToPageHandler evtSendMsg;

protected void ButtonClick(object sender, EventArgs e)
{
if (evtSendMsg != null)
{
evtSendMsg(txtVal.Text);
}
}

Here I declared the delegate with one string parameter. Also I have created one event with that delegate. This event will be fired when we click the button.
Now what we need to do is,
1. Create a function with one string parameter and no return value.
2. Assign the function reference into delegate which was created in user control.

callUserControls.aspx


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

<%@ Register Src="TestUserControl.ascx" TagName="TestUserControl" 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>
<uc1:TestUserControl ID="TestUserControl1" runat="server" />
<asp:Label ID = "lbl" runat = "server"></asp:Label>
</div>
</form>
</body>
</html>


callUserControls.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
TestUserControl1.evtSendMsg += new TestUserControl.SendMessageToPageHandler(TestUserControl1_evtSendMsg);
}

void TestUserControl1_evtSendMsg(string Msg)
{
lbl.Text = "The Value is : " + Msg;
}

Or

You can also use Anonymous function like,


protected void Page_Load(object sender, EventArgs e)
{
TestUserControl1.evtSendMsg += delegate(string s) {
lbl.Text = "The Value is : " + s;};
}



No comments: