Nicholas Head

Filter by APML

ASP.Net Trick: Getting rid of viewstate on DropDownLists

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:

   1: Protected Sub ddlMyDropDownList_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlMyDropDownList.Init
   2:     Dim db = New MyDataContext()
   3:  
   4:     Dim q = From s In db.States _
   5:             Order By s.StateName _
   6:             Select New ListItem(s.StateName, s.StateAbbrev)
   7:  
   8:     ddlMyDropDownList.Items.AddRange(q.ToArray())
   9:  
  10:     Dim r = Request(ddlMyDropDownList.UniqueID)
  11:     If r IsNot Nothing Then ddlMyDropDownList.SelectedValue = r
  12: End Sub

Don’t forget to set “EnableViewState=False” on your DropDownList.

Tags:

asp.net | programming

Comments

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading




Log in

Powered by BlogEngine.NET 1.6.0.0