动态用户控件初始化回传 [英] Dynamic usercontrol postback initialization
问题描述
我有一个动态加载其它用户控件的用户控件。问题是,在回发我控制不存在。现在我的IM pression我不得不重新初始化它们之下。
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.
现在要做到这一点,因为他们是用户控件,使用用户控件的控件的ASCX文件都没有了空的构造被初始化。
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.
问:如何我在这个时候加载用户控件的ASCX文件
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);
}
在哪里ctrlCollectionType是用户控件的类型。
Where ctrlCollectionType is the Type of the userControl.
编辑:解决方案为每乔尔Coehoorn的输入
Solution as per Joel Coehoorn's input.
推荐答案
您必须做两步骤:
- 负载控制(你的
this.LoadControl()
调用做到这一点) - 添加加载的控制,以表单的
控制
集合。你没有表现出任何code,这是否。
- 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.
此外,你需要做的的前的视图状态在页面生命周期的恢复,或者你想到事情会无法正常工作。由于ViewState是Page_Load事件触发之前恢复,这意味着你需要做它Page_Init或更早版本。
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.
这篇关于动态用户控件初始化回传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!