Richard's Rant

Principal .NET Consultant, MCSD Certified

The dreaded ArgumentOutOfRangeException when DataBinding a DropDownList in ASP.NET 2.0/3.5

For most of the time, I love .NET. It truly makes my programming life so much easier than it was in my VB 6 and COBOL days. But someetimes, you come across something that makes you want to take the .NET framework designers and punch them senseless.  I am, of course, talking about that wonderful "by design" feature of ASP.NET 2.0 data binding that results in the dreaded "dropdownlist has a SelectedValue which is invalid because it does not exist in the list of items".

Now, the error is not a bad thing. You first populate a DropDownList with reference data from a database (or a Business object) that serves as an input field so that users do not have to enter data in.  Then, you put that DropDownList into a gridview/listview/formview etc, and retrieve a record from the database that contains a field whose value is represented by the DropDownList data.

BUT, say that the database returns a null value, or that the value of an historical record contains a reference value that is no longer valid, or even that there is a data corruption issue. What result do we get?  A horrid screen that is presented to the user informing them that a "dropdownlist has a SelectedValue which is invalid because it does not exist in the list of items". And a user is supposed to understand this how?

Anyway, after a massive amount of searching, I have come up with a solution that works for me. (Just a s a side note, I have tried the AppendDataBoundItems="true" but this only works when you know what values are missing from the drop down. Not really a solution IMHO). The solution I found was courtesy of WebApps.com. The upshot is that for the DropDownList, you handle a OnDataBound event, where you essentially set the value yourself if it is there, otherwise set the value to a default item. Simple, yet elegant.

Why Microsoft has not made such a solution easily discoverable, is beyond me.

And as a note, the same thing happens in .NET 3.5, so they have in no way listened to gripes about this. I mean, how hard is it to allow the programmer to catch the exception and handle it? (And if anyone reading this knows a better way, then please let me know.)

Anyway, hope that helps someone. (My apologies for the rant)

 

Comments

No Comments

Leave a Comment

(required) 

(required) 

(optional)

(required)