选择下拉列表值时隐藏/显示一些元素

时间:2018-03-26 19:11:28

标签: c# asp.net visible

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

主下拉列表是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#函数来控制visiblity

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

但是当选择Admin时,这些元素仍然可见,我也尝试将两个元素的可见性初始化为false,然后在选择教师值时将它们设置为true但页面中没有任何内容显示它们仍然隐藏,这里有什么问题?

2 个答案:

答案 0 :(得分:2)

DropDownList1启用回帖,以便您的下拉列表可以调用c#服务器端代码。

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

答案 1 :(得分:0)

AutoPostBack="True"添加到DropDownList1

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