0
votes

I have page ParentPage.aspx and 2 user controls say (control1.ascx and control2.ascx)

On load of page I have dynamically added one of user control depending on condition, Now this ParentPage also have on button which is outside PlaceHolder (which holds Usercontrol) and on click of say (btnNext Button I want to call respective method of UserControl.

Is it possible to call usercontrol's method on Event of Parent page,

I am trying to Do following for this problem 1. Both userControl will Implementing say IAction methos which has Action method in it. 2. Page will have Property of type IAction, whose getter will return respective UserControl, and On this IAction Property (on that UserControl I will call Action Method)

But I want to decouple this ParentPage with UserControl and for that I want to use Event but not getting how to do that,

All google links provided, shows how to call parent Page method on click of Usercontrol event but not vise versa.

1
yes it's possible I think that you should read up on how to call methods inside of a user control.. also if you are not familiar with Delegates I would quickly read up on how to use them as well as create them inside user controls.. - MethodMan
As MethodMan says you could do that, but it's a bad idea. Simplest way is to take the code out of the event handler and put it in a public method, then wire the event handler to that. Then you can call it however you want. - Tony Hopkinson
Can you show it practically , I tried with Event of Parent Page to be register in UserControl, but as I am loading control Dynamically I am not understanding how to work on it, any link or any sample code will be appreciated. - Giri.Net
If i understand you correctly are you trying to access Usercontrol method in parent Page. here is simple way: You set the ID="" attribute to usercontrol on page and you can use to reference it from within the page. Page code looks like this: <my:UserControl runat="server" ID="ucControl1" /> Then you can just get it like this in your parent button click event ucControl1.ActionMethod(); - prasy
Thanks Prasy, For your time. Actually Issues is I am loading controls dynam,ically, so on nextbutton Click I dont know which control is loaded to call its method in regualar ( its ID.Methodname() format) - Giri.Net

1 Answers

0
votes

If you are loading your Usercontrol Dynamically like below. you can declare your Usercontrol in class level and access it through out the class.

ParentPage:

public partial class ParentPage: System.Web.UI.Page
{
  private  Control ucUserControl;
  protected void Page_Load(object sender, System.EventArgs e)
  {
    ucUserControl =(Control)Page.LoadControl("control1.ascx");
    placeholder.Controls.Add(ucUserControl);

   }
   //button click event 
   protected void button_Click(object sender, EventArgs e)
   {
     ucUserControl.ActionMethod();
   }
}