Geeks With Blogs
IDeploy adventures of a geek without a parachute

Via Dino Esposito ...

Imagine your page includes a drop-down list control filled with 300 country names. Do you think it will be persisted across postbacks? To this question, my answer would be NO. Wrong. The right answer is true. And where do you think all that stuff is stored across postbacks? In the viewstate, of course.

You may have heard (from me, for example) that data-bound controls don't persist their data source to the viewstate. For list controls (drop-down, checkboxlist, listbox), this is not exactly true. When you call DataBind on any of these, the data source is broken into pieces and loaded into the Items collection. And the Items collection is persisted to the viewstate.

To save your pages something like 10KB of viewstate per each country-list control in the form, you have to:

  1. Disable the viewstate for the control
  2. Retrieve the list of country from the cache and bind

You still have one problem left--the index of the selected item is lost across postback. This is another weird thing of list controls. The SelectedIndex property is NOT explicitly persisted to the viewstate and is NOT set out of posted data (the whys of this are currently beyond me). The property takes its value from the Selected property of the Items collection. As you can easily figure out, SelectedIndex is then implicitly persisted to the viewstate. That's why it gets lost across postbacks.

Workarounds? Just one--resort to the old fashioned but still effective Page.Request["countrylist"]. In Page_Load, it just returns the text of the selected item. Map that to an index position and you're done.

(thanks to paul wilson for pointing this out)...

There's a much easier work-around -- rebind your list in the Init event ! This is simple page life-cycle stuff -- the posted value is restored immediately before the Load event, so you must get your values back in the list at an earlier stage. Another option, not my recommendation but necessary for some cases where your list is itself dynamically created based on some criteria you've stored in ViewState, is to rebind your list in an override of LoadViewState.

Posted on Wednesday, March 23, 2005 11:41 AM Tips | Back to top

Copyright © Scott G. | Powered by: