Search code examples
c#asp.netvisible

hide/show some elements when drop-down list value selected


So, I have these elements, label and drop-down list I want to control their visibility according to the selected value in other drop-down list

the main drop-down list is DropDownList1

<asp:DropDownList ID="DropDownList1" runat="server" onselectedindexchanged="DropDownList1_SelectedIndexChanged" 
                        CssClass="dropdownRequestList">
                         <asp:ListItem>Teacher</asp:ListItem>
                         <asp:ListItem>Admin</asp:ListItem>
                    </asp:DropDownList> 

and other element need to control their visibility Label9 and DropDownList2

 <asp:Label ID="Label9" runat="server" Text="Department  :-" CssClass="lable" 
                        Visible="True"></asp:Label>
                </td>
                <td class="tx">
                    <asp:DropDownList ID="DropDownList2" runat="server" 
                        DataSourceID="SqlDataSource1" DataTextField="Department" 
                        DataValueField="Department" Visible="True" AutoPostBack="True">
                    </asp:DropDownList>

then I write c# function to control the visiblity

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (DropDownList1.SelectedItem.Text != "Teacher")
        {
            Label9.Visible = false;
            DropDownList2.Visible = false;
        }
    }

But those elements still visible when select Admin, I also try to initialize visibility for both elements as false then make them true when Teacher value selected but no things appear in page and they still hidden, What is the wrong here ?


Solution

  • Enable post back on for DropDownList1 so your drop down can call the c# server-side code.

    <asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
        CssClass="dropdownRequestList" AutoPostBack="True">
        <asp:ListItem>Teacher</asp:ListItem>
        <asp:ListItem>Admin</asp:ListItem>
    </asp:DropDownList>
    

    And for c# code below update the visibility on Page_Load instead of DropDownList1_SelectedIndexChanged to handle all cases as below.

    protected void Page_Load(object sender, EventArgs e)
    {
        if (DropDownList1.SelectedItem.Text != "Teacher")
        {
            Label9.Visible = false;
            DropDownList2.Visible = false;
        }
        else
        {
            Label9.Visible = true;
            DropDownList2.Visible = true;
        }
    }