System.Web.HttpException:不能在DropDownList中选择多个项目

问题描述:

在页面加载,索引0被已被选中。那么这个code语句,选择索引1:

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

在页面加载完成后,页面上写着:System.Web.HttpException:不能在DropDownList中选择多个项目

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?

我注意到,这两个指数0和指数1例属性选择设置为true(dropDownList.Items [0] .Selected和dropDownList.Items [1 ] .Selected两者都是如此)。然而,dropDownList.SelectedIndex仍然为0,即使指数1最新设定。

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));

现在的选择变化propogates整个列表。

Now the selection change propogates throughout the list.

所以,不要使用dropDownList.Items [X] .Selected =真/假来改变一个DropDownList的选定值。相反,使用dropDownList.SelectedIndex = X;

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