Wednesday 3 August 2011

OptGroup with asp:Dropdownlist

Most are aware that the out of the box DropdownList that comes with asp.NET doesnt allow for OptGroups. These are quite handy when it comes to structuring the layout.

One way around this is to use jQuery to insert the items required to make optgroup work.

Define your asp:DropdownList, remember to set the cssclass attribute as this makes it easier to find.

In this case I had a dropdown with the css class of eventDropDown attached.

In the data returned to the Dropdown I make sure 2 extra rows are added to separate the 2 sets of options, in this case one is PE and one is OE.

initially the data is bound with the separators (slightly edited)
<select>
<option>PE</option>
<option>ONE</option>
<option>OE</option>
<option>TWO</option>
</select>

using the :contains selector that comes with the standard jQuery libraray I was able to find the option of PE and OE to be replaced with my optgroup choices.
I have made the assumption that if PE exists, then so does OE. Makes life a bit easier.

<script type="text/ecmascript">
var item = $('.eventDropDown option:contains("PE")');
if (item != null) {
item.replaceWith("<optGroup label='Preferred Events' />");
item = $('.eventDropDown option:contains("OE")');
item.replaceWith("<optGroup label='Other Events' />");
}
</script>

I'm not sure on the accessibility level of what I am doing, but visually this will work for most cases where you want this to happen.

If you do want proper option groups do your site in MVC and make your own custom control, its fun. this is a way out for a control in ASP.NET.