2

I have a need to group items in the Listbox similar to the OPTGROUP in a html SELECT.

Any suggestions is greatly appreciated.

Sandeep Polavarapu
  • 382
  • 1
  • 6
  • 25
  • possible duplicate of [Dropdownlist control with s for asp.net (webforms)?](http://stackoverflow.com/questions/130020/dropdownlist-control-with-optgroups-for-asp-net-webforms) – Chase Florell Nov 22 '10 at 06:03

4 Answers4

3

Refactored Sandeep's answer:

http://jsfiddle.net/kgBr9/

HTML

<select id="mySelect">
    <option optGroup='a'>1</option>
    <option optGroup='a'>1</option>
    <option optGroup='a'>1</option>
    <option optGroup='b'>2</option>
    <option optGroup='b'>2</option>
</select>

JQuery

function SetupOptGroups(select) {
    var optGroups=new Array();    
    var i = 0;

    $(select).find("[optGroup]").each(function(index, domEle) {
        var optGroup = $(this).attr("optGroup");
        if ($.inArray(optGroup, optGroups)==-1) optGroups[i++] = optGroup;
    });

    for(i=0; i < optGroups.length; i++){
        $("option[optGroup='"+optGroups[i]+"']").wrapAll("<optgroup label='"+optGroups[i]+"'>");
    }
}
Homer
  • 7,594
  • 14
  • 69
  • 109
  • 1
    Note this line should include the `$(select).find()` in order to not group ALL of your select's options into one: `$(select).find("option[optGroup='"+optGroups[i]+"']").wrapAll("");` – Steven M Feb 23 '13 at 01:36
  • Is there anyway to sort the placed optGroups, I tried jQuery sort but it does not work. – Nick N. Sep 11 '13 at 10:01
2

I accomplished this requirement by adding an attribute to options and attribute value will be the Optgroup name i want to have. And in the client side i used this code to render dropdown with optgroupsvar optGroup = "";

var i = 0;
$(this).find("option").each(function () {
    if (optGroup !== "")
        optGroup += "," + $(this).attr("OptGroup");
    else
        optGroup = $(this).attr("OptGroup");
});
var optGroups = $.unique(optGroup.split(","));
for (var optGroupEle in optGroups) {
    if ($("optgroup[label='" + optGroups[optGroupEle] + "']").html() == null)
        $("option[OptGroup='" + optGroups[optGroupEle] + "']").wrapAll("<optgroup label='" + optGroups[optGroupEle] + "'/>");
}
Druid
  • 6,423
  • 4
  • 41
  • 56
Sandeep Polavarapu
  • 382
  • 1
  • 6
  • 25
0

You can add an Item and disable, change the color, the final efect is the same, i.e.

itemVersion.Attributes.Add("disabled", "true") itemVersion.Attributes.Add("style", "color:#CCCCCC") ddlAspectoOrigen.Items.Add(itemVersion)

Doberon
  • 611
  • 9
  • 19
0

You can use the HTML SELECT control and access all properties of this from the codebehind like a listbox. You only need to add the label runat="server".

Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
lorca
  • 1
  • While this may answer the question, [it would be preferable](http://meta.stackoverflow.com/q/8259) to include more of the essential parts of the answer here, and provide the link for reference. – Nathan Tuggy Jun 11 '15 at 02:47