viewstate possible bug?

P

Perecli Manole

I am trying to change a dropdown's value through code on a postback but the
framework seems to override my changes with the value posted. This only
happens when adding controls though code. Here is a code example of the
problem:

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load

Dim intValue As Integer = 1
intValue = Request.Item("list")

Dim a As New DropDownList
With a
.ID = "list"
.AutoPostBack = True
.EnableViewState = False
.Items.Add(New ListItem("One", 1))
.Items.Add(New ListItem("Two", 2))
.Items.Add(New ListItem("Three", 3))
End With

'change value which should override the posted value
a.SelectedValue = 3

CType(Me.FindControl("Form1"), Object).controls.Add(a)
End Sub


Here is a work around which prevents the framework from matching the control
on post back by changin the control's ID on every post thus preventing the
value override. It works but is ugly and wish someone can show me the
correct to achieve this:


Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load

Dim intValue As Integer = 1
If Not Viewstate("guid") Is Nothing Then
intValue = Request.Item("list" & Viewstate("guid").ToString)
End If

Dim a As New DropDownList

Dim g As Guid
g = Guid.NewGuid
Viewstate("guid") = g

With a
.ID = "list" & g.ToString
.AutoPostBack = True
.EnableViewState = False
.Items.Add(New ListItem("One", 1))
.Items.Add(New ListItem("Two", 2))
.Items.Add(New ListItem("Three", 3))
End With

'change value which overrides the posted value
a.SelectedValue = 3

CType(Me.FindControl("Form1"), Object).controls.Add(a)
End Sub



Thanks
Perry
 
P

Perecli Manole

I have read this article before and does not explain what is occuring here.

The document under the OnLoad states: At this point, server controls in the
tree are created and initialized, the state is restored, and form controls
reflect client-side data.

Well, as you can see from my example, I overwrote the OnLoad event. What do
I need to do to prevent posted values from overitting the values I set in
the OnLoad event.

Perry
 

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

Top