問題
有時,當我們試圖指定一個ASP.NET Dropdownlist選中的項目時遇到這樣的報錯"Cannot have multiple items selected in a DropDownList."
使用下面這些代碼有可能出現這個報錯:
DropDownList1.Items.FindByValue("3").Selected = true;
或者
DropDownList1.Items.FindByText("Sports").Selected = true;
如果這樣寫代碼卻不會出現這種報錯:
DropDownList1.SelectedIndex = 3;
DropDownList1.SelectedItem.Value = "3"; (Wrong way of implementation. But people use this)
解決的方法
在DropDownList1.Items.FindByValue("3").Selected = true;的前面加上一句DropDownList1.ClearSelection();
正确代碼示範如下:
DropDownList1.ClearSelection();
為什麼
原因很簡單,當你使用
DropDownList1.Items.FindByText("Sports").Selected = true;這種形式指定某個item的Selected為true時,之前已經選擇的item的Selected值仍然為true,而DropDownList是不允許多個值被同時標明的,是以會報錯。