Dynamic usercontrol postback initialization

2019-08-30 00:48发布

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.

1条回答
2楼-- · 2019-08-30 01:35

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.

查看更多
登录 后发表回答