ASP.NET:Viewstate并以编程方式添加用户控件 [英] ASP.NET: Viewstate and programmatically adding user controls
问题描述
当使用LoadControl(字符串路径)以编程方式添加用户控件时,何时在用户控件的页面生命周期中使用视图状态初始化其子控件?
When programmatically adding user controls using LoadControl(string path), when, in the user control's page life cycle, does it initialize its sub-controls with its viewstate?
我问这个问题是因为我正在以编程方式加载的一个用户控件具有一个TextBox控件,该控件未通过Page_Load事件在PostBack上的viewstate初始化/加载(对于常规.aspx则不是这种情况)页,因此我感到困惑).总的来说,我需要从文本框"控件中检索值.
I'm asking this question because one of my user controls that's being programmatically loaded has a TextBox control that is not being initialized/loaded by it's viewstate on PostBack on the Page_Load event (which is not the case for a regular .aspx pages and hence my confusion). Overall, I need to retrieve values from the Textbox control.
谢谢
推荐答案
在Page_Load事件之前加载ViewState.如果希望控件与ViewState一起使用,则需要加载该控件并将其添加到该事件之前的页面上-通常在PreInit上.
ViewState is loaded before the Page_Load event. If you want your control to work with ViewState, you need to load it and add it to the page before that event — usually on PreInit.
生命周期参考在这里:
http://msdn.microsoft.com/en-us/library/ms178472.aspx?ppud=4
The life cycle reference is here:
http://msdn.microsoft.com/en-us/library/ms178472.aspx?ppud=4
阅读 Pre Load
事件的描述,该事件紧接在页面加载之前:
Read the description for the Pre Load
event, which immediately precedes Page Load:
如果需要在Load事件之前对页面或控件执行处理,请使用此事件.
Use this event if you need to perform processing on your page or control before the Load event.
在Page实例引发此事件之前,它会为其自身和所有控件加载视图状态,然后处理Request实例附带的所有回发数据.
Before the Page instance raises this event, it loads view state for itself and all controls, and then processes any postback data included with the Request instance.
因此,按预加载时间,已经为时已晚.另外,对PreInit事件的描述特别提到了它是创建或重新创建动态控件"的地方.
Thus by Pre Load time it's already too late. Also, the description for the PreInit event specifically mentions that it's the place to "create or re-create dynamic controls."
这篇关于ASP.NET:Viewstate并以编程方式添加用户控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!