3

I want to group data in DropDownList in asp.net webform

Drop-down pull data from the database table and below is the sample data in table

ID      Name                CatID   
1       Project One         1           
2       Project Two         1         
3       Project Three       2           
4       Project Four        2           
5       General             3           
6       Cat 1               1
7       Cat 2               2
8       Cat 3               3

enter image description here

I tried few ways to do it from Code behind direct but it didnt work as intended.

I also tried jquery to implement same using the following example but it has static conditional value so this wont work either

Below is the code i have for now

public void getDonationForDDGrouping()
{
    SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["SQLConnectionString"].ToString());
    if (con.State == ConnectionState.Closed)
    {
        con.Open();
    }
    SqlCommand cmd = new SqlCommand("select ID, Name, CatID from Project ", con);
    cmd.ExecuteNonQuery();
    SqlDataAdapter adp = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    adp.Fill(ds);
    con.Close();

    ListItem newItem;
    DataTable dt = new DataTable();
    dt = ds.Tables[0];


    foreach (DataRow drow in dt.Rows)
    {
        newItem = new ListItem(drow["Name"].ToString(), drow["ID"].ToString());
        newItem.Attributes["OptionGroup"] = drow["ParentID"].ToString();
        ddlOptionGroup.Items.Add(newItem);
    }
}


How can group them with or without use of jQuery. It would be good to do all from code behind

Desired output

Cat 1
--Item 1
--item 2
Cat 2
--
General
--Project Two
General
--Project One
--Project Four
--Project Three
Project One
Learning
  • 19,469
  • 39
  • 180
  • 373
  • @AnoopH.N, Solution you are referring to is very old, I am looking at both side solution jquery as well as Codebehind – Learning Feb 14 '17 at 07:43

2 Answers2

3

Change the code as below at server side,

foreach (DataRow drow in dt.Rows)
    {
        newItem = new ListItem(drow["Name"].ToString(), drow["ID"].ToString());
        newItem.Attributes["data-category"] = drow["ParentID"].ToString();//Instead of ID, Pass Category Name.
        ddlOptionGroup.Items.Add(newItem);
    }

At Client Side using Jquery,

   var groups = {};
$("select option[data-category]").each(function () {
     groups[$(this).attr("data-category")] = true;
});

$.each(groups, function (c) {
     $("select option[data-category='"+c+"']").wrapAll('<optgroup label="' + $("select option[data-category='"+c+"']").html() + '">');
});
Anoop H.N
  • 1,244
  • 1
  • 15
  • 31
  • Appreciate that, but it doent work, i set up the fiddle which actual output http://codepen.io/anon/pen/rjPYBV – Learning Feb 14 '17 at 08:02
  • I have updated the code. Please check and let me know if you are facing any problem. – Anoop H.N Feb 14 '17 at 09:34
  • In the line newItem.Attributes["data-category"] = drow["ParentID"].ToString(); Instead of parent Id, you provide the category name. – Anoop H.N Feb 14 '17 at 09:37
  • I have updated question & fiddle with your latest update. Output is still wrng and i have also put desired output to under what the output should be http://codepen.io/anon/pen/rjPYBV – Learning Feb 14 '17 at 09:44
  • As i mentioned in the comment, you need to add category name instead of drow["ParentID"].ToString(); – Anoop H.N Feb 14 '17 at 09:46
  • In actual code it is parentID not Category Name – Learning Feb 14 '17 at 10:16
1

Here is Sample Code for this

public class DropDownListAdapter : 
   System.Web.UI.WebControls.Adapters.WebControlAdapter {
protected override void RenderContents(HtmlTextWriter writer) {
    DropDownList list = this.Control as DropDownList;
    string currentOptionGroup;
    List<string> renderedOptionGroups = new List<string>();
    foreach(ListItem item in list.Items) {
        if(item.Attributes["OptionGroup"] == null) {
            RenderListItem(item, writer);
        } else {
            currentOptionGroup = item.Attributes["OptionGroup"];
            if(renderedOptionGroups.Contains(currentOptionGroup)) {
                RenderListItem(item, writer);
            } else {
                if(renderedOptionGroups.Count > 0) {
                    RenderOptionGroupEndTag(writer);
                }
                RenderOptionGroupBeginTag(currentOptionGroup, 
                                          writer);
                renderedOptionGroups.Add(currentOptionGroup);
                RenderListItem(item, writer);
            }
        }
    }
    if(renderedOptionGroups.Count > 0) {
        RenderOptionGroupEndTag(writer);
    }
}
private void RenderOptionGroupBeginTag(string name, 
             HtmlTextWriter writer) {
    writer.WriteBeginTag("optgroup");
    writer.WriteAttribute("label", name);
    writer.Write(HtmlTextWriter.TagRightChar);
    writer.WriteLine();
}
private void RenderOptionGroupEndTag(HtmlTextWriter writer) {
    writer.WriteEndTag("optgroup");
    writer.WriteLine();
}
private void RenderListItem(ListItem item, 
             HtmlTextWriter writer) {
    writer.WriteBeginTag("option");
    writer.WriteAttribute("value", item.Value, true);
    if(item.Selected) {
        writer.WriteAttribute("selected", "selected", false);
    }
    foreach(string key in item.Attributes.Keys) {
        writer.WriteAttribute(key, item.Attributes[key]);
    }
    writer.Write(HtmlTextWriter.TagRightChar);
    HttpUtility.HtmlEncode(item.Text, writer);
    writer.WriteEndTag("option");
    writer.WriteLine();
}

}

Reference: https://www.codeproject.com/articles/15505/asp-net-dropdownlist-with-optiongroup-support