Dynamic usercontrol postback initialization

青春壹個敷衍的年華 提交于 2019-12-25 03:13:40

问题


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:


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.



来源:https://stackoverflow.com/questions/1537910/dynamic-usercontrol-postback-initialization

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!