Group < optgroup > in DropDownList using jQuery C#

In this article I‘ll show you how to create groups in the ASP.NET DropdownList control using JQuery.
In this example we are using JQuery’s native support for wrapping elements into other elements with the help of wrapAll() method. It takes only 1 line of code and we can have the groups created in the HTML. However, the drawback of this approach is the groups will disappear on postback.

For Example, we going to create two groups in Dropdownlist as you see above image.
– LessThanFifty
– GreaterThanFifty

First, we bound Dropdownlist using datatable in Page_Load codebehind

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataTable table = new DataTable();
            table.Columns.Add("ID", typeof(int));
            table.Columns.Add("Number", typeof(int));
            //
            // Here we add five DataRows.
            //
            table.Rows.Add(1,57);
            table.Rows.Add(2, 23);
            table.Rows.Add(3, 99);
            table.Rows.Add(4, 8);
            table.Rows.Add(5, 74);

            DropDownList1.DataSource = table;
            DropDownList1.DataValueField = "ID";
            DropDownList1.DataTextField = "Number";
                        
            DropDownList1.DataBind();
        }
    }

Now We have to create a new attribute for every DropdownList item when Dropdownlist is bound (DropDownList1_DataBound). This new attribute will be used for grouping in the JQuery code.

protected void DropDownList1_DataBound(object sender, EventArgs e)
    {
        foreach (ListItem item in ((DropDownList)sender).Items)
        {
            if (System.Int32.Parse(item.Text ) < 50)
                item.Attributes.Add("classification", "LessThanFifty");
            else
                item.Attributes.Add("classification", "GreaterThanFifty");
        } 
    }

Last we use JQuery WrapAll() method to group two different classification attribute (LessThanFifty and GreaterThanFifty)

<script type="text/javascript">
        
        $(document).ready(function() {
            //Create groups for dropdown list
            $("select#DropDownList1 option[classification='LessThanFifty']").wrapAll("<optgroup label='Less than fifty'>");
            $("select#DropDownList1 option[classification='GreaterThanFifty']").wrapAll("<optgroup label='Greater than fifty'>"); 
        });
    
    </script>

Here is full html page code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Ashish Blog</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
    <script type="text/javascript">
        
        $(document).ready(function() {
            //Create groups for dropdown list
            $("select#DropDownList1 option[classification='LessThanFifty']").wrapAll("<optgroup label='Less than fifty'>");
            $("select#DropDownList1 option[classification='GreaterThanFifty']").wrapAll("<optgroup label='Greater than fifty'>"); 
        });
    
    </script>
    <style>
    optgroup
    {
        background-color:Gray ;
    }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <h1>ASP.NET DropdownList with group</h1>
    <div>
        <asp:DropDownList ID="DropDownList1" runat="server" Width="200px"
            ondatabound="DropDownList1_DataBound">
        </asp:DropDownList>
    </div>
    </form>
</body>
</html>

Thanks.

11 responses to “Group < optgroup > in DropDownList using jQuery C#”

  1. I altered it so I sent into the text a prefixed option group name like so: GroupName~TextToDisplay then modified Databound like so:

    protected void DropDown1_DataBound(object sender, EventArgs e)
    {
    foreach (ListItem item in ((DropDownList)sender).Items)
    {
    var arrayItem = item.Text.Split(‘~’);
    item.Text = arrayItem[1].ToString();
    item.Attributes.Add(“classification”, arrayItem[0].ToString());
    }
    }

  2. PS Had to add this line at end of jQuery call to fix bug in Firefox that would not have the SELECTED option selected.

    $(“select#DropDown1 option[selected]”).removeAttr(“selected”).attr(“selected”, “selected”);

  3. Should the jquery be called after the databind process i s over

    $(document).ready(function() {
    //Create groups for dropdown list
    $(“select#DropDownList1 option[classification=’LessThanFifty’]”).wrapAll(“”);
    $(“select#DropDownList1 option[classification=’GreaterThanFifty’]”).wrapAll(“”);
    });
    this is being called when the page is loaded before the dropdown being filled.

    • We can use on page who implements master page
      just inspect dropdown and check its ID
      change
      $(“select#DropDownList1 option[classification=’LessThanFifty’]”).wrapAll(“”);
      TO

      $(“select#ctl00_ContentPlaceHolder1_DropDownList1 option[classification=’LessThanFifty’]”).wrapAll(“”);

Leave a Reply