1
votes

I have visual web part and two usercontrols. On Page_Load() of visual web part i dynamically create userControl1:

protected void Page_Load(object sender, EventArgs e)
{
  UserControl1 userControl = Page.LoadControl(userControl1Path) as UserControl1;
  userControl.ID = "UserControl1";
  this.Controls.Clear();
  this.Controls.Add(userControl);
}

In UserControl1 i have a button, that load second user control (UserControl2) (and it works!):

protected void GoToUserControl2_Click(object sender, EventArgs e)
{
  UserContol2 userControl = Page.LoadControl(userControl2Path) as UserContol2;
  userControl.ID = "UserContol2";
  this.Controls.Clear();
  this.Controls.Add(userControl);
}

UserControl2 also have a button, but when i click on it - click event not firing. Instead of it, button click perform redirect to UserControl1. Even if button does't have any event - it redirects to UserControl1.

Help me, please!

1
Put a break point in your page load, you will notice that page_load function is executed EVERY TIME there is a post back, i suspect that your page load clears control 2 and use event of control 1Antoine Pelletier

1 Answers

1
votes

Dynamically generated Controls have to be recreated on every page load, and that includes a PostBack. Because the second User Control is only loaded on a button click, it disappears when another PostBack is performed. You will have to keep track if UserContol2 has been created and if so, reload it in the Page_Load of the parent. In this snippet I'm using a Session for keeping track of the opening of UserContol2.

Set the Session in Button Click Method

protected void GoToUserControl2_Click(object sender, EventArgs e)
{
    //rest of the code
    Session["uc2_open"] = true;
}

And check on Page_load if the Session exists and if so, create the second User Control.

protected void Page_Load(object sender, EventArgs e)
{
    UserControl1 userControl = Page.LoadControl(userControl1Path) as UserControl1;
    userControl.ID = "UserControl1";
    this.Controls.Clear();
    this.Controls.Add(userControl);

    if (Session["uc2_open"] != null)
    {
        UserContol2 userControl = Page.LoadControl(userControl2Path) as UserContol2;
        userControl.ID = "UserContol2";
        this.Controls.Clear();
        this.Controls.Add(userControl);
    }
}