views:

689

answers:

2

I'm trying to avoid a composite control or using and ASCX by extending an existing control. However, I'm having trouble with getting the controls added to the inherited control and keep their view-state/post-back integrity. Whenever I add the controls during pre-render, the controls show up, but the post-back throws a viewstate exception. I tried adding them both there and during LoadViewState (which of course was a long-shot silly). Init is not available from the control which I'm extending.

The exception is Sys.WebForms.PageRequestManagerServerErrorException: Failed to load viewsstate. 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

+2  A: 

You should add them in OnInit or in CreateChildControls. Anyway, to avoid having troubles with ViewState, read this GREAT article. Possibly, sample "4. Initializing child controls programmatically" is your case.

I read that article a year ago, lost the link, and have been looking for it again ever since. Thanks for posting it here. If I could upvote twice I would.
Joel Coehoorn
+2  A: 

Actually, microsoft says you should override the CreateChildControls method.

You can call the base class method before or after you add the controls, I'm not sure if there is a convention there.

protected override void CreateChildControls(){
  Controls.Add(someControl);
  base.CreateChildControls();
}

Hope that helps!

Zachary Yates