1
votes

I have a UserControl. I dynamically create some controls (Columns for SPGridView. Grid control was added in markup, ObjectDataSource, Button and Label) in CreateChildControl method and add them to Controls collection. Two of these controls are added well (Button and Label) in postback, but one of them (MenuTemplate) raise the exception with such content:

"Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request. For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request. "

When I move my code to OnInit method all controls are added successfully. So, I have a question: Could someone explain me why some controls are added to Controls collection successfully and others are failed in CreateChildControls in postback? I have read about ViewState here. Probably I didn't understand some moments.

Look at me code:

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();
}
1
I hope you are aware of the page life cycle. Control added in Page_Load will not have viewstate. The Viewstate is build earlier to this. - Ankit
I think that controls will have viewstate in Page_Load. See this explanation, Figure 4. Events and View State - andDaviD

1 Answers

0
votes

I think, you can only add items into a template in Page_Load or other events(ie, after Page_Init) so that it will be retained in postback, not the template itself.. Templates are need to be created before or at Page_Init stage, otherwise it may not load the controls into that templates from viewstate or may result in error.