User Control ViewState/State Help needed
I need help making this code work better. Currently, what happens is when it reloads, I loose the third value which is a calculated value . I would like for my page to reload without loosing the values for each property and each instance of the user control on the page.
Thanks in advance
Private _Length As Double = 0.0
Public Property Length() As Double
Get
If (Me.ViewState("calcLength") IsNot Nothing) Then
Return CType(ViewState("calcLength"), Double)
End If
Return _Length
End Get
Set(ByVal value As Double)
ViewState("calcLength") = value
txtLength.Text = value.ToString()
_Length = value
End Set
End Property
Private _Width As Double = 0.0
Public Property Width() As Double
Get
If (Me.ViewState("calcwidth") IsNot Nothing) Then
Return CType(Me.ViewState("calcwidth"), Double)
End If
Return _Width
End Get
Set(ByVal value As Double)
Me.ViewState("calcwidth") = value
Me.txtwidth.Text = 开发者_如何学运维value.ToString()
_Width = value
End Set
End Property
Private _calculatedboardfeet As Double = 0.0
Public Property CalculateBoardFeet() As Double
Get
If (Me.ViewState("calculateboardfeet") IsNot Nothing) Then
_calculatedboardfeet = CType(ViewState("calculateboardfeet"), Double)
End If
Return _calculatedboardfeet
End Get
Set(ByVal value As Double)
Me.ViewState("calculateboardfeet") = value
Me.lblCalculatedValue.Text = String.Format("{0:f2}", value)
_calculatedboardfeet = value
End Set
End Property
There's this portion which I 'think' doesn't make sense, though it may not be the cause of the problem. I've yet to studied the rest of the codes in detail.
ElseIf (Me.ViewState("txtwidth") Is Nothing) Then
Return CType(Me.ViewState("txtwidth"), Double)
If the ViewState
item cannot be found (i.e. Is Nothing
), how do you return the cast-ed value? This is the same for the 3 properties.
What do you mean by the "third value which is the calculated value"? Third as in CalculateBoardFeet()?
At what stage in the page life cycle are you calling these properties?
Why are you storing the values both in ViewState and in the control's .Text property, and then again in a class variable? Too. Many. Copies.
If you programmatically set the control's .Text property, that value should be restored on postback for you, without you having to explicitly set ViewState yourself.
Turns out what I needed was to call the assignment part of my code in the pre_Render event in the Usercontrol. It comes later than the Parent Page's PageLoad() event, which is when the information needed will be available in the control's viewstate
精彩评论