Dynamic Dropdownlist

Posted by – July 12, 2007

Came across a strange problem today. I was dynamically filling a dropdown list, and also was dynamically creating checkboxes from the database. Basically I have a list of options, and the user needs to select a primary choice (via dropdown) and then a bunch of alternates (via checkboxes). I assumed the best way to do this was:


CheckBoxList checkSet = new CheckBoxList();

ListItem leaf = new ListItem();
leaf.Text = categoryList[i].name;
leaf.Value = categoryList[i].categoryId.ToString();
checkSet.Items.Add(leaf);

//primaryCategory is the dropdownlist defined in aspx file
primaryCategory.Items.Add(leaf);

At first everything appeared great. However, when I tried to submit the form somtimes, i would get the following error:
Cannot have multiple items selected in a DropDownList. This confused me, because I wasn’t trying to set the selected value through code. After some digging, I realized they when I select the checkbox item and then post back the form, asp.net sees that the checkbox was selected before, so sets it’s “selected” property to ‘selected’. My code then adds the item to both the dropdown and checkbox list. However, the dropdown had a selected value of it’s own, and therefore I get the error.

The solution, although it seems odd, is to create two different items in code: one for the dropdownlist, and one for the checkbox.


CheckBoxList checkSet = new CheckBoxList();

//add to checkboxlist
ListItem leaf = new ListItem();
leaf.Text = categoryList[i].name;
leaf.Value = categoryList[i].categoryId.ToString();
checkSet.Items.Add(leaf);

//add to dropdownlist
leaf = new ListItem();
leaf.Text = categoryList[i].name;
leaf.Value = categoryList[i].categoryId.ToString();
primaryCategory.Items.Add(leaf);

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>