Thursday, July 24, 2008

Managing DataBound DropDownLists Properly

So I found a tricky problem with databound DropDownLists that causes the selectedIndexChanged event to fire more than you probably intended.

Normally when you add one - you might DataBind it, and then do something like

my_ddl.Items.Add(new ListItem("Select . . . "));

This can become tricky pretty fast if your DropDownList does anything major - like add a selection to a form. The problem is that dropdownlists seem to be loaded with a SelectedIndex of -1. This means that when they are unbound (aka have no data at all), they don't want to put 0 (because that would indicate an item) - so its a -1.

So you bind your data, and then add a top level ListItem for convenience - and now the selected Index is 0 - so SelectedIndexChanged event fires!

The simple fix is to force all of your DDL's to initialize to 0 - and always have a top item! That way, if a user selects the top item, the event does not fire, but any other databound item will work fine.

So, in Page_load, do this

protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
return;

my_ddl.SelectedIndex = 0;
}

Note that this only needs to be done for databound controls / controls created programmatically. I have not extensively tested, so I am not 100% on what controls this affects, but I am pretty sure that ones created declaratively in the ASPX page will not have this problem

Hamy

No comments: