views:

278

answers:

2

I have an ajax toolkit tab container on my ASP.Net page, and I am dynamically creating the tabs in the code behind (at runtime, I have a variable number of tabs, each with the same layout but different header text and body data). Each tab contains only one control, which is a user control I built to make all the tabs look the same. In the user control is another user control I built to handle the paging of my data within the tab. That paging user control has a property that is backed its ViewState.

I bind all the data for the tabs in a single BindData function on the ASPX page. Within that function, I am always setting an ID for my dynamically created controls and adding them to their container controls before setting any other properties, wiring events, or binding data to them.

I am losing the ViewState variable's value in my paging user control in this scenario:

main ASPX page

Page_Init:

    If IsPostBack Then
        BindData     ' Recreates the control tree on postback.
        ' ViewState is loaded successfully here.
    End If

Page_Load:

    If Not IsPostBack Then
        BindData()   ' Bind the initial data.
    End If

[Some event that happens after Page_Load in response to clicking on my user control]:

    ...
    BindData()    ' Controls recreated with changed data but same IDs as in Page_Init.
    ' ViewState does not get loaded back into my control tree.

Should I not expect the ViewState to get loaded again on the second version of my control tree in the page lifecycle?

A: 

You should create the dynamic controls in pre-init phase. And recreate them even after postback. Check the details of the page lifecycle here: http://msdn.microsoft.com/en-us/library/ms178472.aspx

o.k.w
I do recreate my dynamic controls in the Init phase (I checked the article and the ViewState loading comes after Init, so it doesn't seem to matter if the dynamic controls are created in PreInit or Init), including after a postback. All of that is working fine. When I create the controls again after my control event handlers fire, I lose my ViewState.
Matt Hamsmith
+2  A: 

After much reading, it seems like any dynamic controls created after the Init phase do not load the ViewState. For my situation, in my BindData function, I grab my viewstate values to local variables, recreate the controls, and then reset the viewstate values. This seems to work.

Matt Hamsmith
Have you tried just plugging you control creation code into pre-init? JUst to see if it saves you the effort to manually reassign the values from the viewstate. Though you already made it work :)
o.k.w