且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.NET:Viewstate并以编程方式添加用户控件

更新时间:2023-11-30 15:13:34

在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."