Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Web.HttpException: Cannot have multiple items selected in a DropDownList

During page load, index 0 was already selected. Then this code statement selected index 1:

dropDownList.Items.FindByValue(myValue).Selected = true; 
// assume myValue is found at index 1 of dropDownList.Items

On completion of page load, the page reads: "System.Web.HttpException: Cannot have multiple items selected in a DropDownList."

Why did I get the exception? And how can I fix it?

like image 262
Bill Paetzke Avatar asked Oct 21 '09 20:10

Bill Paetzke


2 Answers

I noticed that both index 0 and index 1 had the properties "Selected" set to true (dropDownList.Items[0].Selected and dropDownList.Items[1].Selected both were true). However, dropDownList.SelectedIndex was still 0, even though index 1 was set most recently.

I tried resolving this by clearing the list selection beforehand.

dropDownList.ClearSelection();
dropDownList.Items.FindByValue(myValue).Selected = true;

But that didn't help. Same exception occurred.

What did help, was setting the selected value another way:

dropDownList.SelectedIndex = dropDownList.Items.IndexOf(dropDownList.Items.FindByValue(myValue));

Now the selection change propogates throughout the list.

So, don't use dropDownList.Items[x].Selected = true/false to change the selected value of a DropDownList. Instead, use dropDownList.SelectedIndex = x;

like image 181
Bill Paetzke Avatar answered Oct 22 '22 17:10

Bill Paetzke


I just had this problem, and found out it was caused by something different. I was adding the same ListItem instance to multiple dropdowns:

ListItem item = new ListItem("Foo", "1");
ListItem item2 = new ListItem("Bar", "2");
ddl1.Items.Add(item);
ddl2.Items.Add(item);
ddl1.Items.Add(item2);
ddl2.Items.Add(item2);

Then setting the SelectedValue:

ddl1.SelectedValue = "1"; //sets the Selected property of item
ddl2.SelectedValue = "2"; //sets the Selected property of item2

Switching to adding separate instances of ListItem fixed the problem.

My guess is that when you set the SelectedValue of the DropDownList, it sets the Selected property on the appropriate ListItem in its Items collection. So in this case, at the end of the second code block, both items are selected in both dropdowns.

like image 19
Tom Hamming Avatar answered Oct 22 '22 16:10

Tom Hamming