Wednesday, November 11, 2009

Calling Parent Method from child control using Events & Delegates.

Before starting we should very clear about event and delegate

Event: it's handler which will call the delegate and it will call the method.

Delegate: it's a function pointer, it will point to the particular function.

Let me explain about calling parent method from the child control.


Step 1: create one aspx pages and usercontrol pages.


step 2:

In the usercontrol create one button and lable. The scenoria is like this when user click on the button has to call the child method as well as the parent method.

Step 3:

Create one user control with the following code.


Childcontrol.ascx

<asp:Button ID="btnShow" runat="server" />
<asp:Label ID="lblShow" runat="server"></asp:Label>



Childcontrol.ascx.cs

public delegate void callDelegate();
public event callDelegate callEvent;

protected void Page_Load(object sender, EventArgs e)
{
btnShow.Click += delegate
{
lblShow.Text = "Hi how are u";
this.showData();
};
}
protected virtual void showData()
{
if (this.callEvent != null)
{
this.callEvent();
}
}


Step 4:


Create one aspx page with name of Parent with the following code.

parent.aspx


<%@ Register Src="~/UserControl/Childuser.ascx" TagPrefix="child" TagName="UC" %>

<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="lblParent" runat="server"></asp:Label>
<child:UC id="UC1" runat="server"></child:UC>
</div>
</form>
</body>
</html>


parent.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
UC1.callEvent += new Childuser.callDelegate(UC1_callEvent);
}

void UC1_callEvent()
{
lblParent.Text = "Hi Parent";
}