It seems that the DropDownList control in ASP.Net 2.0 really has some issues. Besides the one I mentioned in an earlier post, I recently ran into another annoying problem.

The symptom: while using a custom object data source (e.g. as simple as a value object, I have not tested other data sources yet, but a quick search on this issue on the Internet seemed to suggest that the issue I will be talking here happens with other data sources as well), it seems that changing SelectedValue after the control is bound would sometimes trigger the infamous ‘DropDownList1′ has a SelectedValue which is invalid because it does not exist in the list of items. exception.

This problem is rather frustrating as it does not always happen. It seems to me though that whenever the data source has non-consecutive values bound to SelectedValue, this exception will occur if trying to change the SelectedValue property after the data has already been bound.

After some experiment, I think I found a workaround. While changing SelectedValue triggers the exception, changing SelectedIndex does not. So, if the selected value of a dropdown list must be changed after data bound, change the SelectedIndex instead.

This workaround of course, adds a little bit complexity to the code as you must use some routine to determine the index of th value that is being selected. In most cases though, the added code is no more than a for loop that inspects the data-bound object.

 

Be Sociable, Share!