hide/show 选择下拉列表值时的一些元素

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

所以,我有这些元素、标签和下拉列表,我想根据其他下拉列表中的 selected 值来控制它们的可见性

主下拉列表是 DropDownList1

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

其他元素需要控制其可见性 Label9 和 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>

然后我写c#函数来控制可见性

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

但是这些元素在 select Admin 时仍然可见,我还尝试将这两个元素的可见性初始化为 false,然后在 Teacher 值 selected 但没有任何东西出现在页面中时使它们为真仍然隐藏,这里有什么问题?

AutoPostBack="True"添加到DropDownList1

<asp:DropDownList ID="DropDownList1" runat="server"
 onselectedindexchanged="DropDownList1_SelectedIndexChanged"
 CssClass="dropdownRequestList" AutoPostBack="True">

DropDownList1 启用 post 以便您的下拉菜单可以调用 c# server-side 代码。

<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>

对于下面的 C# 代码,更新 Page_Load 而不是 DropDownList1_SelectedIndexChanged 的可见性以处理以下所有情况。

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;
    }
}