Tuesday, March 13, 2007

Every once in a while while working with ASP.NET there comes a time when you need to have a DropDownList with a fixed set of items. Or maybe the items are retrieved from the database, but still every instance of the control will have exactly the same items. How to do it efficiently?

Lets look at the simple example of a DropDownList with country names - the one you see on many pages. Wouldn't it be nice to have a reusable control for this?

The simplest way to create a Self Populating DropDownList is to inherit from the standard one, set the DataSource somewhere and call DataBind(). That is the tricky part.

If you have been working with ASP.NET for a while you are probably aware of the ViewState thingy. As good as it is, it can often make your page too large. This is specially true for DataBound controls. A simple Counties DropDownList would make your ViewState huge! So what can be done about it? Just disabling ViewState won't help because usually disabling it breaks some of the other parts of control's functionality.

Dealing with ViewState is simple once you get to know one very important thing. Only changes made after the Init phase of the Life Cycle are persisted to the ViewState! Or more precisely, changes only changes made after the control has started tracking ViewState (TrackViewState method has been called). It means that everything you put to the ViewState before that, will not be persisted. By default controls will have their TrackViewState method called right after the Init phase.

We can use this knowledge to our advantage. If we populate our DropDownList before or during the Init phase we will not affect ViewState. Doing so however has one drawback: we have to perform this operation on each request and not only when IsPostBack is false. This is not an issue if we use some kind of cache and we populate a lots of controls with the same data.

kick it on DotNetKicks.com