我有UserControl
。我动态地创建了一些控件(SPGridView
的列,网格控件添加在标记中,ObjectDataSource
,Button
和Label
)CreateChildControl
方法并将它们添加到Controls
集合。这些控制中的两个孔加入(Button
和Label
)在回发,但是它们(MenuTemplate
)中的一个提高与这样的内容的异常:动态添加控件时出错
“未能加载视图状态的控制树成视图状态是 被加载的数据必须与前一个请求期间用于保存视图状态的控制树匹配,例如,动态添加 控件时,在回发期间添加的控件必须匹配 初始期间添加的控件的类型和位置 要求。“
当我将代码移至OnInit
方法时,所有控件都成功添加。所以,我有一个问题:有人可以解释为什么一些控件成功添加到控件集合,其他人在回发中CreateChildControls
失败?我已阅读关于ViewState here。可能我有些时候不明白。
看着我的代码:
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();
}
我希望你知道页面的生命周期。在Page_Load中添加的控件将不具有视图状态。视图状态是在此之前构建的。 – Ankit 2012-08-03 07:06:45
我认为控件将在Page_Load中拥有viewstate。请参阅[本解释](http://msdn.microsoft.com/ru-ru/library/ms972976.aspx#viewstate_topic3),图4.事件和视图状态 – andDaviD 2012-08-03 07:10:37