ASP.NET Dropdownlist with groups

2014, Mar 17    

looks like it’s not possible to have optgroups in an ASP.NET Dropdownlist without subclassing. Today I found a very useful snippet on stackoverflow that allows to group items on client side and I want to share it with the world:


private void AddItemToList(DropDownList list, string title, string value, string group = string.Empty) {
   ListItem item = new ListItem(title, value);
   if (!String.IsNullOrEmpty(group))
       item.Attributes["data-category"] = group;


var groups = {};
$("select option[data-category]").each(function () {
     groups[$.trim($(this).attr("data-category"))] = true;
$.each(groups, function (c) {
     $("select option[data-category='"+c+"']").wrapAll('<optgroup label="' + c + '">');

Hope it helps!

Did you like this post? Then