動的に作成された子ユーザー コントロールで同様の問題が発生したと思います。LoadViewState
最初に作成したときに ViewState にアクセスできたとしても、ポストバックで呼び出されませんでした。SaveViewState
も正しく呼び出されたようです。子の ViewState は、完全に初期化される前にページ イベントで (これにより例外が発生することなく) 実際には使用できませんでした。Init
これは、コントロールが親に追加された場合にのみ発生しました。これを確認した後、子の 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; }
}