In ASP.NET, we develop custom user control as a reusable server control independent of any containing parent aspx page. User control has its own public
properties, methods, delegates, etc. that can be used by parent aspx page. When a user control is embedded or loaded into a page, the page can access public
properties, methods, delegates, etc. that are in user control. After loading the user control, there a situation may arise like calling methods in page itself. But when a user control is developed, it has no knowledge of containing page. So it becomes a trick to call the page method.
In .NET, Delegate
class has one method DynamicInvoke. DynamicInvoke
method is used to invoke (late-bound) method referenced by delegate. We can use this method to call a method in parent page from user control. Let’s try with this example.
First, create a user control called CustomUserCtrl
. Its code will look something like this:
public partial class CustomUserCtrl : System.Web.UI.UserControl
{
private System.Delegate _delWithParam;
public Delegate PageMethodWithParamRef
{
set { _delWithParam = value; }
}
private System.Delegate _delNoParam;
public Delegate PageMethodWithNoParamRef
{
set { _delNoParam = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void BtnMethodWithParam_Click(object sender, System.EventArgs e)
{
object[] obj = new object[1];
obj[0] = "Parameter Value" as object;
_delWithParam.DynamicInvoke(obj);
}
protected void BtnMethowWithoutParam_Click(object sender, System.EventArgs e)
{
_delNoParam.DynamicInvoke();
}
}
Then add this user control into an aspx page. The code behind of this page is as:
public partial class _Default : System.Web.UI.Page
{
delegate void DelMethodWithParam(string strParam);
delegate void DelMethodWithoutParam();
protected void Page_Load(object sender, EventArgs e)
{
DelMethodWithParam delParam = new DelMethodWithParam(MethodWithParam);
this.UserCtrl.PageMethodWithParamRef = delParam;
DelMethodWithoutParam delNoParam = new DelMethodWithoutParam(MethodWithNoParam);
this.UserCtrl.PageMethodWithNoParamRef = delNoParam;
}
private void MethodWithParam(string strParam)
{
Response.Write("<br/>It has parameter: " + strParam);
}
private void MethodWithNoParam()
{
Response.Write("<br/>It has no parameter.");
}
}
BtnMethodWithParam
and BtnMethowWithoutParam
are two different buttons on the user control that are invoking the methods in the parent page. On Page_Load
of the page, we are setting the references of page class methods to delegate type properties in the user control. Click different buttons of user control, you will see MethodWithParam(string strParam)
and MethodWithNoParam()
methods called.
This is all we have to do to call page class methods from user control in ASP.NET.