我有一个UserControl. 我在方法中动态创建了一些控件(SPGridView. Grid 控件的列添加到标记中ObjectDataSource,Button和Label),CreateChildControl并将它们添加到Controls集合中。其中两个控件在回发中添加得很好 (Button和Label),但其中一个 ( MenuTemplate) 引发了带有此类内容的异常:
"加载视图状态失败。要加载视图状态的控件树必须与之前请求期间用于保存视图状态的控件树匹配。例如,动态添加控件时,回发期间添加的控件必须匹配在初始请求期间添加的控件的类型和位置。 "
当我将代码移动到OnInit方法时,所有控件都已成功添加。所以,我有一个问题:有人能解释一下为什么有些控件成功添加到 Controls 集合中而其他控件CreateChildControls在回发中失败了吗?我在这里阅读了有关 ViewState 的信息。可能有些时候我没听懂。
看我代码:
protected override void CreateChildControls()
{
 Label l = new Label();
 l.ID = "labelTest";
 l.Text = "Hello test!";
 Button b = new Button();
 b.Text = "Press test";
 b.ID = "buttonTest";
 b.Click += b_Click;
 Controls.Add(l);
 Controls.Add(b);
 ObjectDataSource gridDataSource = new ObjectDataSource();
 gridDataSource.ID = "gridDataSource";
 gridDataSource.SelectMethod = "GetDataSource";
 gridDataSource.TypeName = this.GetType().AssemblyQualifiedName;
 Controls.Add(gridDataSource);
 SPMenuField colMenu = new SPMenuField();
 colMenu.HeaderText = "Test";
 colMenu.TextFields = "Test";
 colMenu.MenuTemplateId = "ListMenu";
 // it is my SPGridView that added in markup
 customGridView.Columns.Add(colMenu);
 MenuTemplate titleListMenu = new MenuTemplate();
 titleListMenu.ID = "ListMenu";
 // The exception occurs here
 Controls.Add(titleListMenu);
 base.CreateChildControls();
}