0
votes

I am dynamically loading a user control on the page which works fine. However i am facing one problem:

  • I have a class level variable on the User Control code-behind and the value to the same is assigned in User Control Page Load. Now when i click the button on my aspx page which contains the user control in it and try to call the User Control function from it, i see the value of the variable which i had set in the user control-page load has been reset.

The same code works perfectly if i have the user control at design time.

Code is something like this:

Page:

    MyUserControl cntrl = Page.LoadControl("~/MyUserControl.ascx")
    btn_click(){
    {
      cntrl.TestFunction();
    }

User Control:

    class MyUserControl: UserControl
    {
       //Variable
       string org="";
       Page_Load()
       {
          org="test";
       }

       TestFunction()
       {
          //The value of org variable is empty here.
          //It should however be "test" which i have set in page_load
       }
   }
1

1 Answers

1
votes

"Code is something like this:" - when providing code (even as fragments), try to make it to comply with the language syntax - in this case C#.

In order for MyUserControl.Page_Load to fire, you have to add the user control to the control tree of the page:

MyUserControl cntrl = (MyUserControl)Page.LoadControl("~/MyUserControl.ascx");
Panel1.Controls.Add(cntrl);

The Page_Load method must have very specific signature and scope:

class MyUserControl: UserControl
{
  string org="";

  protected void Page_Load(object sender, EventArgs e)
  {
    org="test";
  }

}