Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net webform DropdownList with Groups using code-behind or jquery solution [duplicate]

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
like image 225
Learning Avatar asked Mar 21 '26 12:03

Learning


1 Answers

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() + '">');
});
like image 174
Anoop H.N Avatar answered Mar 24 '26 03:03

Anoop H.N



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!