Yesterday, as I was plugging away on an ASP WebForms application to add some new features, I encountered an error I had not yet seen.
“SelectedValue which is invalid because it does not exist in the list of items”
Although Googling turned up a lot of results, I could not really find anything that fit the bill as a solution. I did find a few threads on StackOverflow, though usually these discussions were followed up with additional people asking how the original asker resolved the issue.
For me, it turns out that I was calling the block of code that performed the list population and databind multiple times. Populating and calling DataBind on this DropDownList multiple times, resulted in the above error. In the end (after much forehead beating), the solution was an easy one – checking items before attempting to populate and bind to ensure the list was not already initialized.
if (yourDropDownList.Items.Count() == 0) //only populate and bind if not already done…
//populate and bind
That is it – just checking to ensure the items for the drop down list have not already been populated. Of course, you really should have your application structured so that this logic is only hit once…. This said, if a complete refactor/rewrite is not in the cards for your application at this time, you can just perform this simple check to work around the exception.
Hope this helps someone!