I have a UserControl
which dynamically creates several TextBoxes. The number of TextBoxes is dependent on user selection. I chose to store the IDs of each TextBox
in the UserControl
's ViewState
object so that they can be re-created consistently across each postback.
If I re-create the dynamic controls during Page_Init
(as is recommended) then the UserControls
's ViewState
has not yet been populated.
If I re-create the dynamic controls during Page_Load
or PreLoad
then their postback values are not rehydrated until after the Page_Load
event, so I can't access their correct values until later in the page lifecycle which is causing problems.
Is there a better approach to this?
It appears that overriding CreateChildControls
is the way to go. It is not always called at the same point in the page life cycle, see http://msdn.microsoft.com/en-us/library/aa719775%28VS.71%29.aspx
The CreateChildControls method is not listed in the table because it is called whenever the ASP.NET page framework needs to create the controls tree and this method call is not limited to a specific phase in a control's lifecycle. For example, CreateChildControls can be invoked when loading a page, during data binding, or during rendering.
However, this seems to be best practice (When "must" I use asp.net CreateChildControls()?) and when combined with EnsureChildControls()
it is always called at the appropriate moment with ViewState
data available.