Register   |   Login

 

Spark Your Solution

 Scott's Technology Blog Minimize

Apr 2

Written by: Scott Davis
4/2/2008 10:38 PM

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

 

Tags:

1 comments so far...

Re: A DropDownList cannot have mulitple items selected

OK, after further review, there appears to be a better way. The method of selecting the list item, by finding it in the Items collection is still my preferred way, but only when the loop is adding the items to the ddl (manual add: you are not using a data bound source).

But, if you just want to find and select the item, here is a significant shortcut.

ddlControl.SelectedIndex = ddlControl.Items.IndexOf(ddlControl.Items.FindByValue(targetValue));

By scott on   4/3/2008 9:11 AM

Your name:
Title:
Comment:
Add Comment    Cancel  

  
 Blog Dates Minimize

 Print   
 Search Minimize

 Print