by Nicholas Head
22. February 2009 22:11
If you’ve used ASP.Net for any amount of time, you quickly realize how much it loves to dump into the viewstate. Now, I’m not claiming I’m a saint in this area, but I have been learning as I go to recognize what operations will fill the viewstate and work to prevent them.
One trick I learned recently is to re-bind your DropDownList on every postback, inside of the DropDownList’s Init event handler. You can also pull in the postback value from the Request.Form collection and set the DropDownList’s SelectedValue to what it should be. Observe the following example:
Protected Sub ddlMyDropDownList_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlMyDropDownList.Init
Dim db = New MyDataContext()
Dim q = From s In db.States _
Order By s.StateName _
Select New ListItem(s.StateName, s.StateAbbrev)
ddlMyDropDownList.Items.AddRange(q.ToArray())
Dim r = Request(ddlMyDropDownList.UniqueID)
If r IsNot Nothing Then ddlMyDropDownList.SelectedValue = r
End Sub
Don’t forget to set “EnableViewState=False” on your DropDownList.