Question

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?

Was it helpful?

Solution 3

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.

OTHER TIPS

I ran into a similar Catch 22 -- I needed to add dynamic usercontrols to my page, but they depended on a dropdownlist selection made by the user. Of course that dropdownlist's value doesn't become accessible until after viewstate is set up, but it's recommended to create the usercontrols in Page_Init if we want them to maintain their own states via viewstate, but that's before viewstate exists so I can't poll the dropdownlist from there.

Another suggestion that works for me -- get the dropdownlist's value from the Request.Form collection:

protected void Page_Init(object sender, EventArgs e)
{
     //get the user's DropDownList selection
     int visualizerMode = Int32.Parse(Request.Form[ddlVisualizerMode.UniqueID]);

     //now dynamically load a usercontrol based on that value
     LoadUserControl(visualizerMode);
}

...this works well for me. It's a throwback to working w/ HTML forms directly, which I often forget about since it's been so many years in the ASP.NET WebForms model.

As pointed at msdn http://msdn.microsoft.com/en-us/library/ms178472(VS.100).aspx ; you may use InitComplete event to get access viewstate data.But some times viewstate data gets bigger and makes performance problem overall .Alternatively you may use session object or a unvisisble controle to store your data.

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