【问题标题】:Error with dynamically adding controls动态添加控件时出错
【发布时间】:2012-08-03 06:39:36
【问题描述】:

我有一个UserControl。我在CreateChildControl 方法中动态创建了一些控件(SPGridView 的列。在标记中添加了网格控件ObjectDataSourceButtonLabel)并将它们添加到Controls 集合中。其中两个控件在回发中添加得很好(ButtonLabel),但其中一个(MenuTemplate)引发了带有此类内容的异常:

"加载视图状态失败。视图状态所在的控件树 正在加载的必须与用于保存的控制树匹配 上一个请求期间的视图状态。例如,当添加 动态控制,在回发期间添加的控件必须匹配 在初始阶段添加的控件的类型和位置 请求。 "

当我将代码移动到OnInit 方法时,所有控件都已成功添加。所以,我有一个问题:有人能解释一下为什么有些控件成功添加到 Controls 集合中,而其他控件在 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 中添加的控件将没有视图状态。 Viewstate 是在此之前构建的。
  • 我认为控件将在 Page_Load 中具有视图状态。请参阅this explanation,图 4。事件和视图状态

标签: asp.net webforms viewstate dynamic-controls


【解决方案1】:

我认为,您只能在 Page_Load 或其他事件中(即在 Page_Init 之后)将项目添加到模板中,以便将其保留在回发中,而不是模板本身。模板需要在 Page_Init 之前或在 Page_Init 之前创建阶段,否则它可能无法将控件从视图状态加载到该模板中,或者可能导致错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多