Reputation: 1
I have a child UserControl which is dynamically loaded into a parent page.
ChildControl childcontrol = this.LoadControl("") as ChildControl;
I have to call one of the methods in the parent page from this childUserControl. How do we do that?
Thanks
Upvotes: 0
Views: 2405
Reputation: 68506
You shouldn't write a control that relies on a method being on the page, so the best thing to do would be to expose and handle an event from the child control. Add the following to your child control:
public event OnSomethingHandler Something;
public delegate void OnSomethingHandler(ChildControl sender);
Then when you want to fire the page method in question, fire off the event:
public void FireParentMethod()
{
if (Something != null)
{
Something(this);
}
}
The all you need to do is handle the event on the page (in markup or in code as follows):
childUserControl.Something+=
new ChildControl.OnSomethingHandler(ChildControl_OnSomething);
And add the handler to the code behind:
protected void ChildControl_OnSomething(ChildControl sender)
{
FirePageMethod();
}
Upvotes: 3
Reputation: 29664
Cast the parent of the control as the specific type of your page and then call the method.
Upvotes: 0