Dave
Dave

Reputation: 45

Add dynamic ASP.NET user controls BASED ON ViewState - BUT before LoadViewState phase

Setup:

My page has a drop down whose values are dynamically populated. Based on which item is selected, a number of TextBoxes are dynamically created during runtime.The user then fills in information into the textboxes and clicks a submit button.

Problem:

After postback from the submit button, I need to again dynamically create the TextBoxes during Page_Init (BEFORE LoadViewState) so that after the ViewState loads, my Button_Click event can save/do whatever with the user input. PROBLEM is, I cannot recreate the textboxes based on the selection in the dropdown, because the dropdown hasn't been "selected" yet by LoadViewState.

SO, how can I read from the view state, create my textboxes, then let the viewstate populate the textboxes, and then the Button_Click will use the values??

The one thing I've attempted is to override the LoadViewState function so that I can read from the view state, create the boxes, and then load the viewstate again. This did NOT work, because the debugger never seemed to hit my overridden function.

    Protected Overrides Sub LoadViewState(ByVal savedState As Object)

        MyBase.LoadViewState(savedState)

        //'Do something like add controls
        Dim test As String = RecordList.SelectedValue
        //'Create controls using value "Test"

        MyBase.LoadViewState(savedState)

    End Sub

Any help would be appreciated. I can post more code if needed.

Thanks,

David

Upvotes: 2

Views: 1604

Answers (1)

volpav
volpav

Reputation: 5128

I'd suggest retrieving drop-down list value from the request directly using the UniqueID property:

Protected Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs)
    Dim selectedValue As String = Request.Form(RecordList.UniqueID)
    ' Recreate your dynamic controls based on the selected value
End Sub

Protected Sub Button_Click(ByVal sender As Object, ByVal e As EventArgs)
    ' Examine dynamic controls and their values (retireved from the ViewState)
End Sub

Upvotes: 1

Related Questions