How to properly handle the situation when some controls/WebUserControls should be added into a page hierarchy at runtime based on some certain conditions?
It is recommended to use the following sequence of operations when creating a control (or loading a WebUserControl) dynamically:
- Control: Create a new control instance via the control type constructor:
- WebUserControl: Load a WebUserControl (*.acsx file) by its virtual path via the LoadControl method:
2) Specify the control ID property;
3) Specify the SkinID and EnableTheming properties of the control if required.
4) Attach event handlers:
(see the ASP.NET Page Life Cycle Overview MSDN help topic to learn more about the order of events/stages)
5) Insert the control into the entire controls hierarchy;
6) Specify the control's properties;
7) Bind the control (for data-aware controls).
Note once you have modified the entire controls hierarchy (i.e., added the control into the controls collection), it is necessary to restore this control with the same settings during the Page_Init stage.
The linked E1238 - How to create controls dynamically Code Central example illustrates these solutions in action.
Show all comments