我想我对一些动态创建的子用户控件有类似的问题。LoadViewState
即使我在第一次创建它们时能够访问它们的 ViewState,也不会在回发中调用它们。SaveViewState
似乎也被正确调用。Init
在完全初始化之前,子 ViewState 在页面事件中并不是真正可用的(不会导致异常) ,这仅在控件添加到父级时才会发生。在确保这一点之后,子 ViewState 在回发中正确持久化。
// Belongs to a Page. If you create the children control in the
// Load event in you can also access the page ViewState
protected void Page_Init(object sender, EventArgs e)
{
if (!IsPostBack)
{
for (int it = 0; it < 5; it++)
{
ChildControl child = LoadControl("ChildControl.ascx")
as ChildControl;
child.ParentPage = this;
TabPanel tab = tabContainer.FindControl("TabPanel" + it)
as TabPanel;
// Ensure to add the child control to its parent before
// accessing its ViewState!
tab.Controls.Add(child); // <---
string caption = "Ciao" + it;
child.Caption = caption; // Here we access the ViewState
tab.HeaderText = caption;
tab.Visible = true;
_Children.Add(child);
}
}
[...]
}
// Belongs to ChildControl
public string Caption
{
get { return ViewState["Caption"] as string; }
internal set { this.ViewState["Caption"] = value; }
}