如何根据特定条件隐藏/显示下拉列表项?

时间:2018-03-02 10:48:44

标签: c# html webforms

这是我的下拉前端代码:

<asp:DropDownList ID="ddlSearch" runat="server" CssClass="form-control">
    <asp:ListItem Value="1" Text="Ref No" />
    <asp:ListItem Value="2" Text="Name" />
    <asp:ListItem Value="3" Text="contact" />
</asp:DropDownList>

1 个答案:

答案 0 :(得分:0)

您可以使用.FindByValue上的.FindByTextddlSearch.Items方法获取该项目。然后将项目的.Enabled属性设置为false,将其隐藏在UI上。

因此,例如,如果您需要隐藏值为“1”的项目,则可以执行以下操作:

ddlSearch.Items.FindByValue("1").Enabled = false;

请注意,在生产代码中,您希望在FindByValue之后进行空检查,但为简单起见,我省略了它。例如,以下是检查空值的方法:

var listitem = ddlSearch.Items.FindByValue("1");
if (listitem != null) 
{
    listitem.Enabled = false;
}
else 
{
    // Throw an exception or display an error that the list item wasn't found.
}
相关问题