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

后端 未结 3 570
我在风中等你
我在风中等你 2021-02-03 11:55

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

dropDownList.Items.FindByValue(myValue).Selected = true; 
// assume my         


        
3条回答
  •  闹比i
    闹比i (楼主)
    2021-02-03 12:40

    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.

提交回复
热议问题