Cannot have multiple items selected in a DropDownList

You may receive the error "Cannot have multiple items selected in a DropDownList." when trying to set a value selected in an ASP.NET Dropdownlist.

This error specifically occurs if you are trying to execute a similar code as follows:-

DropDownList1.Items.FindByValue("3").Selected = true;
(or)
DropDownList1.Items.FindByText("Sports").Selected = true;

This error doesnt occur if you try to use

DropDownList1.SelectedIndex = 3;
or
DropDownList1.SelectedItem.Value = "3";
(Wrong way of implementation. But people use this)

The resolution is that, you just have to mention DropDownList1.ClearSelection(); before using DropDownList1.Items.FindByValue("3").Selected = true;

The correct step is as below:-

DropDownList1.ClearSelection();
DropDownList1.Items.FindByValue("3").Selected = true;

or

DropDownList1.ClearSelection();
DropDownList1.Items.FindByText("Sports").Selected = true;

Sometimes you need to fill a dropdownlist with new/other items on a postback.
If you wish to clear the complete list of items in a dropdownlist you can call:

DropDownList1.Items.Clear();


Terug