Calling a method of parent page from user control

In my previous post i explained about how to handle events of usercontrol in parent page in asp.net and here i am going to explain

How to call a function from a usercontrol on the Parent form.

All you need to pass a event to the parent page to call method across the page and control, you can call parent page methods in usercontrol as well as usercontrol methods in the parent page through the concept of events and delegates.

Suppose you have a usercontrol named ucprompt and want to call a method of parent page named MyParentMethod from that usercontrol what a button which is inside the usercontrol clicked

UserControl Part :
public partial class uc_prompt : System.Web.UI.UserControl
{
  protected void Page_Load(object sender, EventArgs e)
  {
  }

  public delegate bool customHandler(object sender);
  public event customHandler checkIfExist;
  protected void btnYes_Click(object sender, EventArgs e)
  {
      checkIfExist(sender);
  }
}

Parent Page Part :
public partial class getproductdetails : System.Web.UI.Page
{
 protected void Page_Load(object sender, EventArgs e)
 {
  ucPrompt.checkIfExist += new uc_prompt.customHandler(MyParentMethod);
 }

 bool MyParentMethod(object sender)
 {
   //Do Work
 }
}



Recent Article