Saturday, August 17, 2013

Calling a method in Parent page from User Control

User Controls in ASP.net is a reusable server control independent of Containing parent aspx page. When a User control embedded into a Aspx Page or other control, parent control will have access to the public properties, methods and objects of the child user control. There might be a scenario where, we need to call one of the method from Parent page or Parent control from the Child User control.

So to call the method in the Parent page or control we can create one Event Handler to our User control and add the Event Handler definition in parent control. Now from the User control we can trigger that Event which will then execute the Event Handler definition in Parent control,  then from there we can call the respective method in Parent Control.
1.       Add an Event to your User Control.

public event EventHandler CreateClick;

2.       Trigger the event from the User Control whenever required on particular action.

CreateClick(sender, e); 

Below is the Code behind of the User Control
 
  //Event Handler Declaration
 public event EventHandler CreateClick;
 
  //Triggering the Event in User control
 public void CallParentEvent(object sender, EventArgs e)
 {
    if (CreateClick != null)
    {
        CreateClick(sender, e);
    }
 }
 
  //Calling the Event trigger after action completed in User control
 protected void btnCreateCtrl_Click(object sender, EventArgs e)
 {
    //your code here then trigger the event
    CallParentEvent(sender, e);
 }
  

3.       Now register the User Control in your Parent page or control, while registering provide the Event Handler method for our custom event.
Below is the Parent Control page. You can also behind the Event handler in Page load in code behind.
 
<SP:CreateCtrl id="createCtrl" runat="server" OnCreateClick="CreateCtrl_Click"/>
 
 

4.       Now in the Parent control code behind, call the respective method inside the above mentioned Event Handler (CreateCtrl_Click)
 
protected void CreateCtrl_Click(object sender, EventArgs e)
{
    try
    {
        //Call the respective in Parent control
    }
    catch (Exception ex)
    {
    }
}
 

 

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...