Dynamically added controls based on information from viewstate

R

Ross Presser

My problem is probably very similar to the frequently asked questions
about dynamically added controls, but I can't quite resolve it.
Probably I don't understand the page lifecycle well enough.

The goal is to have a custom Web Control that has a particular object
property (called PricingModel). When the property is not set, the
control has a default appearance (showing "N/A" for some fields). When
the property is set, it uses information in the control to determine
how many dropdownlist child controls to add and what their choices
are. Once that's done, the values of those dropdownlists that are
chosen by the end web user are used to compute a couple of values,
which are accessible to the parent page through another object
property (called PricingResult)

Currently I am storing the value of the PricingModel property in
ViewState immediately when it is set, and retrieving it from ViewState
whenever it is needed, even by the custom control itself. This
works.

I am creating the child controls in the PreRender event for the custom
control. (I have also tried the Init event -- doesn't work, because I
can't get the PricingModel object from Viewstate because Viewstate
hasn't been loaded yet.) This works in so as far as the child controls
get created and their values loaded. However, the values chosen by the
end user do not persist.

Here's some simplified code:

Partial Class PricingCalculator.aspx
Public Property PricingModel() As PricingModel
Get
Return ViewState(Me.ID & ".PricingModel")
End Get
Set(ByVal value As PricingModel)
ViewState(Me.ID & ".PricingModel") = value
End Set
End Property

Private Sub Page_PreRender(sender as object, e as
System.EventArgs) Handles Me.PreRender
If PricingModel Is Nothing Then
Me.lblFinalPrice.Text = "N/A"
Me.lblWeight.Text = "N/A"
Else
CreateControls()
End If
End Sub

Sub CreateControls()
for each parm as string in PricingModel.ParmNames
dim ddCtl as DropDownList
ddCtl = new DropDownList
ddCtl.ID = "dd_" & parm
for each val as string in PricingModel.GetParmOptions(parm)
ddCtl.Items.Add(val)
next
AddHandler ddCtl.SelectedIndexChanged, AddressOf
ChangeHandler
Me.Controls.Add(ddCtl) ' (actually this is more complex, I
put it into a table row)
next
End Sub

Sub ChangeHandler(sender as Object, e as EventArgs)
' recompute final price ...
End Sub
End Class


So, any suggestions?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top