" DropDownList.SelectedIndex = -1"问题

时间:2020-03-05 18:58:19  来源:igfitidea点击:

我只想要一个没有选定项目的ASP.NET DropDownList。到目前为止,将SelectedIndex设置为-1无济于事。我正在使用带有AJAX的Framework 3.5,即此DropDownList在UpdatePanel中。
这是我在做什么:

protected void Page_Load (object sender, EventArgs e)
    {
        this.myDropDownList.SelectedIndex = -1;
        this.myDropDownList.ClearSelection();

        this.myDropDownList.Items.Add("Item1");
        this.myDropDownList.Items.Add("Item2");
    }

当我在DropDown中添加元素时,其SelectedIndex更改为0,并且无法再设置为-1(我也尝试在添加项目之后调用SelectedIndex)...我在做什么错?蚂蚁的帮助将不胜感激!

解决方案

回答

我很确定下拉菜单必须选择一些项目。我通常会添加一个空列表项

this.myDropDownList.Items.Add("");

作为我的第一个清单项目,并据此进行。

回答

仅当控件首次初始化且集合内没有任何项目时,selectedIndex才能为-1.

像在WinForm上一样,不可能在Web下拉列表中选择任何项目。

我发现最好拥有:
this.myDropDownList.Items.Add(new ListItem("请选择...",""));

通过这种方式,我向用户传达了他们需要选择一个项目的信息,我们可以检查SelectedIndex == 0以进行验证

回答

我正在阅读以下内容:
http://msdn.microsoft.com/zh-CN/library/a5kfekd2.aspx

它说:
若要获取所选项目的索引值,请读取SelectedIndex属性的值。索引从零开始。如果未选择任何内容,则该属性的值为-1.

同时,在http://msdn.microsoft.com/zh-cn/library/system.web.ui.webcontrols.dropdownlist.selectedindex(VS.80).aspx中,我们看到:

使用SelectedIndex属性以编程方式指定或者确定DropDownList控件中所选项目的索引。始终在DropDownList控件中选择一个项目。我们不能同时清除列表中每个项目的选择。

也许-1仅对获取有效,而不对设置索引有效?如果是这样,我将使用"补丁"。

回答

切记myDropDownList.Items.Add将在执行DataSource / DataBind调用后在底部添加一个新的Listitem元素,因此请使用myDropDownList.Items.Insert方法,例如...

myDropDownList.DataSource = DataAccess.GetDropDownItems(); // Psuedo Code
myDropDownList.DataTextField = "Value";
myDropDownList.DataValueField = "Id";
myDropDownList.DataBind();

myDropDownList.Items.Insert(0, new ListItem("Please select", ""));

将在顶部添加"请选择"下拉项。

如前所述,在下拉菜单中始终会选择一个项目(我相信列表框是不同的),并且如果未明确选择任何项目,则默认为顶部项目。

回答

可以使用客户端脚本将DropDownList的selectedIndex属性设置为-1(即清除选择):

<form id="form1" runat="server">
    <asp:DropDownList ID="DropDownList1" runat="server">
        <asp:ListItem Value="A"></asp:ListItem>
        <asp:ListItem Value="B"></asp:ListItem>
        <asp:ListItem Value="C"></asp:ListItem>
    </asp:DropDownList>
    <button id="СlearButton">Clear</button>
</form>

<script src="jquery-1.2.6.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function()
    {
        $("#СlearButton").click(function()
        {
            $("#DropDownList1").attr("selectedIndex", -1); // pay attention to property casing
        })

        $("#ClearButton").click();
    })
</script>