While doing a little Ajax web programming, I hit this javascript error that stumped me longer than I care to admit. Unfortunately the javascript error doesn't tell you which dropdown has the multiple selection, so not a trivial one to debug if you have several controls in the mix.
Error: "Sys.WebForms.PageRequestManagerServerErrorException: Cannot have multiple items selected in a DropDownList."
I was changing the selected values based on other activity in the form. Because I was using AJAX (which uses Javascript to do the magic), not your typically web request that would re-populating the drop down list all over again on the server side, I was causing the error by using the code below. Note: the drop down list remembered the selected item from the last web request. Setting the selected property of one item, doesn't clear the other selected flags.
foreach (ListItem li in ddlControl.Items)
{
if (li.Value.Equals(targetValue))
{
li.Selected = true;
break;
}
}
This is how I fixed it
foreach (ListItem li in ddlControl.Items)
{
if (li.Value.Equals(targetValue))
{
ddlControl.SelectedIndex = ddlControl.Items.IndexOf(li);
break;
}
}
As I was writing this, I initially felt I could have done it this way, but realized that wouldn't work if I filled the drop down from a database and ended up with two values that had the same value.
foreach (ListItem li in ddlControl.Items)
{
li.Selected = li.Value.Equals(targetValue);
}
Many thanks to Daniel de Andres's blog for the solution. http://blogs.clearscreen.com/enadan/archive/2006/02/13/2794.aspx