Cannot have multiple items selected in a DropDownList

Saturday, 08 March 2008

Posted by Sébastien Lachance with Comments (0)

Cannot have multiple items selected in a DropDownList.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: Cannot have multiple items selected in a DropDownList.
Source Error:

 

Line 253:  total = parseFloat(lblTotal.innerHTML.replace('$', '').replace(',', '.'));
Line 254: fBudget = parseFloat(budget.replace('$', '').replace(',', '.'));
Line 255: var lblWarningContract = document.getElementById('<%= lblWarningContract.ClientID %>');
Line 256:
Line 257: if (total > fBudget)

I spent at least one hour figuring this out. The Source Error  does not contain any valid information. After a lot of debugging, I finally found the solution : you should never use the same item twice on two different dropdownlist.

ListItem item = new ListItem(" -- Select one -- ", "-1");

ddlLoadingContact.Items.Insert(0, item);
ddlUnloadingContact.Items.Insert(0, item);

 

A ListItem have a property called Selected that tells which one (the item) the dropdownlist should display as selected. If you use the same ListItem in more that one dropdownlist and you select this item in the DropDownA and a different item in DropDownB. The DropDownB will have two ListItem with the Selected property set to true. Since this is the same item in both dropdownlist.

ddlLoadingContact.SelectedValue = "-1"; //item will have the Selected property set to true
ddlUnloadingContact.SelectedValue = "John"; //another item will have the Selected property set to true. And both are contained in this dropdownlist.
 
 



blog comments powered by Disqus