views:

223

answers:

1

I have a user control that loads other user controls dynamically. The issue is that on postback my controls don't exist. Now i'm under the impression i have to re-initialize them.

Now to do this since they're UserControls and use the ascx file none of the UserControl's controls have been initialized in the empty constructor.

Question: How do i load the UserControl's ascx file at this time?

Currently i'm trying to do it like this:

for (int i = 0; i < count; i++)
{
    Control ctrl;
    if(ctrlCollectionType.Rows[i]["Type"] is UserControl)
        ctrl = LoadControl((string)ctrlCollectionType.Rows[i]["Path"]);
    else
        this.LoadControl(ctrlCollectionType[i]["Type"], null);

    ctrl.ID = i;
    pnlContent.Controls.Add(ctrl);
}

Where ctrlCollectionType is the Type of the userControl.

Edit: Solution as per Joel Coehoorn's input.

+3  A: 

You have to do two steps:

  • Load the control (your this.LoadControl() call does this)
  • Add the loaded control to your form's Controls collection. You didn't show any code that does this.

Additionally, you need to do this before viewstate is restored in the page life cycle, or things won't work as you expect. Since viewstate is restored before the Page_Load event fires, that means you need to do it on Page_Init or earlier.

Joel Coehoorn
Ahh you would be correct, out of curiosity from a best practices standpoint what would be the best way of preserving the ID of the control?
Highstead
ClientID or just normal server-side id? If it's server ID, then just make sure you set it in the same way on the postback that you did when you created it.
Joel Coehoorn
Well the issue is that the user is able to choose the controls that are added dynamically so i can't count on creating it the same way.
Highstead
You have to remember what they chose last time.
Joel Coehoorn