How does this example retain selectedItem on postback?

R

RSH

Hi,

I am experimenting with the Viewstate and based on a few articles I have
read, I put together a test. it is a simple test where I am dynamically
creating a DropDownList that contains 25000 list items. When I don't create
the control dynamically, I get a viewstate that is roughly 1 mb in size!
However, when i use the code below the viewstate is 0 bytes even on
postback. Impressive size difference. Now where I get perplexed is even
though the viewstate is set to off in the creation of the dynamic control,
the Dropdownlist retains the correct SelectedItem, and furthermore i can
even reference the control to bring back it's Selecteditem property and it
returns correctly...but with Trace=true set on the page i can see that the
viewstate = 0 bytes on this control. My question is if indeed the viewstate
is disabled for this control (everything points to this) then how is the
Control retaining the correct SelectedItem upon Postback???

Thanks,
Ron


Protected Sub Page_Init(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Init



DropDownlist1 = New DropDownList

Databindlist(DropDownlist1)

DropDownlist1.EnableViewState = False

PlaceHolder1.EnableViewState = False

PlaceHolder1.Controls.Add(DropDownlist1)

Button1 = New Button

Button1.Text = "Postback"

Button1.EnableViewState = False

Placeholder2.Controls.Add(Button1)

Placeholder2.EnableViewState = False

End Sub

#End Region

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

Label1.Text = DropDownlist1.SelectedItem.Text <-- some how this line sets
the correct SelectedItem whether it is a postback or not

End If

End Sub



Public Sub Databindlist(ByVal ddl As DropDownList)

Dim li As ListItem

Dim i As Integer

For i = 0 To 25000

li = New ListItem

li.Text = "test " & i

li.Value = "test " & i

ddl.Items.Add(li)

Next

End Sub
 
B

bruce barker

the viewstate is used to regenerate the list on postback, not the value
(thats sent by the browser). if you turn viewstate off, then in oninit
you just need to regerate the list options. then when the load postback
data event is fired (just before the page onload event but after onint)
the option value will be found.

note: this works with static or dynamic controls. i always turn
viewstate off.


-- bruce (sqlwork.com)
 

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

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,054
Latest member
LucyCarper

Latest Threads

Top