When extending a asp.net web control, at which event should additional web controls be injected?

StackOverflow https://stackoverflow.com/questions/296609

  •  08-07-2019
  •  | 
  •  

Question

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

Was it helpful?

Solution

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!

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top