Tuesday, December 16, 2008

Cannot have multiple items selected in a DropDownList

This problem occurs when we try to select more than one item in the drop down at the same time. Also however the most common reason I found this to happen is that the same list item is added to multiple drop downs. Then we to select different values in these different drop downs where same list item was added. Ideally in order to avoid this, we should add new list items to each drop downs. We should carry list item added from one drop down to another
Sample code:
The following code causes error

//bind first dropdown
ListItem listCommon = new ListItem("Please Select One", "0");
ddlFirstDropDown.Items.Clear();
ddlFirstDropDown.Items.Add(listCommon);
ddlFirstDropDown.Items.Add(remaining items);

//bind second dropdown
ddlSecondDropDown.Items.Clear();
ddlSecondDropDown.Items.Add(listCommon);

ddlSecondDropDown.Items.Add(remaining items);

Fix:

//bind first dropdown
ListItem listCommon = new ListItem("Please Select One", "0");
ddlFirstDropDown.Items.Clear();

ddlFirstDropDown.Items.Add(listCommon);
ddlFirstDropDown.Items.Add(remaining items);

//bind second dropdown
ListItem listNewItem= new ListItem("Please Select One", "0");

ddlSecondDropDown.Items.Clear();
ddlSecondDropDown.Items.Add(listNewItem);
ddlSecondDropDown.Items.Add(remaining items);


And secondly always use the following code to select the particular value from drop down
ddlSecondDropDown.SelectedIndex = ddlSecondDropDown.Items.IndexOf (ddlSecondDropDown.Items.FindByValue(string value)));

Never use ddlSecondDropDown.SelectedValue or ddlSecondDropDown.SelectedItem for selecting a particular value from the drop down.


Keeping the above two things in mind should solve the problem.


Cheers

No comments: