If you work on ASP.NET DropDownList, most likely you will encounter a situation when you need to pre-select an item in the DropDownList. You might see people using the following way to do that after the DropDownList is bound:
this.ddlSchools.SelectedValue = oSchool.AdminID
This works very well if you are sure that the value you assign to the DropDownList actually is one of the DropDownList items, otherwise, you will get an ArgumentOutOfRangeException. So the safe way to do this is to compare each item value in the DropDownList to the value you need to assign to, if found, then set the corresponding DropDownList.Selected = true, otherwise set DropDownList.Selected = false. The code snippet looks like the following:
foreach (ListItem li in this.ddlSchools.Items)
{
if (li.Value == oSchool.AdminID)
{
li.Selected = true;
}
else
{
li.Selected = false;
}
}
I have been using this way for a while and it’s been working until today suddenly this error appears:
System.Web.HttpException: Cannot have multiple items selected in a DropDownList.
After some investigation, I found the problem lies in the fact that there are several items in the DropDownList have empty string as their value, and the value of oSchool.AdminID is also empty (this is due to some data error in the database), so the following line has been executed multiple times and multiple items are selected, but since DropDownList control only allows single selection, thus the error occurred:
li.Selected = true;
The quick fix (actually I should have done this in the first place to avoid this kind of error and also to improve the performance) is add “break” after the line of code above:
li.Selected = true;
break;
This line will fix the exception error, but in my case it still causes a minor problem. In my case, when there is no match found in the DropDownList items, then no item will be pre-selected, but because of the data error in my database, the first item with value=”” will always be pre-selected when oSchool.AdminID=””. So the best solution is to check if oSchool.AdminID=””, if no, then loop through the DropDownList items to pre-select the correct item; if yes, then skip the loop so no item will be pre-selected. Here is the modified code snippet:
if (oSchool.AdminID != "")
{
foreach (ListItem li in this.ddlSchools.Items)
{
if (li.Value == oSchool.AdminID)
{
li.Selected = true;
}
else
{
li.Selected = false;
}
}
}