Search code examples
asp.netdrop-down-menucascadingdropdown

aspx simple cascade dropdowns


Maybe this was asked before, if yes, then sorry :)

I am creating a simple form in aspx that has 2 dropdownlists and one button

In first ddl I have options lets say:

  • All
  • Nokia
  • Samsung

Second contains subcategories.

  • All
  • 3310
  • N95
  • Galaxy ACE
  • Galaxy SII

If in first user select All in second he will see only All.
If he selects Nokia he will see All, 3310 and N95,
If he selects Samsung he will get All, Galaxy Ace and Galaxy SII.

I found couple of articles how to do that with server, to populate second dropdownlist from server.

In my situation I don't need server, because I will have about 10 items and 3 categories.

How to do that? Simple aspx or javascript.

I will be grateful. Thanks!


Solution

  • try below code.

    <asp:DropDownList runat="server" AutoPostBack="true" ID="ddlCategories" OnSelectedIndexChanged="ddlCategories_SelectedIndexChanged">
                <asp:ListItem Text="All" Value="All" />
                <asp:ListItem Text="Nokia" Value="Nokia" />
                <asp:ListItem Text="Samsung" Value="Samsung" />
            </asp:DropDownList>
            <asp:DropDownList runat="server" AppendDataBoundItems="true" ID="ddlSubCategories">
                <asp:ListItem Text="All" Value="All" />
            </asp:DropDownList>
    

    Because you are not using database we have to hard code the values.

    protected void ddlCategories_SelectedIndexChanged(object sender, EventArgs e)
        {
            ddlSubCategories.Items.Clear();   
            if (string.Compare(ddlCategories.SelectedValue, "Nokia", true) == 0)
            {
                ddlSubCategories.Items.Add(new ListItem("3310", "3310"));
                ddlSubCategories.Items.Add(new ListItem("N95", "N95"));
            }
            else if (string.Compare(ddlCategories.SelectedValue, "Samsung", true) == 0)
            {
                ddlSubCategories.Items.Add(new ListItem("Galaxy Ace", "Galaxy Ace"));
                ddlSubCategories.Items.Add(new ListItem("Galaxy SII", "Galaxy SII"));
            }
            ddlSubCategories.Items.Insert(0, new ListItem("All", "All"));
        }
    

    Hope it helps. If you want to go for javascript route find below link.

    Populate one dropdown based on selection in another