"DropDownList.SelectedIndex = -1"问题

8 asp.net webforms drop-down-menu

我只想要一个没有选定项目的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");
    }
Run Code Online (Sandbox Code Playgroud)

我在DropDown中添加一个元素的那一刻,它的SelectedIndex更改为0并且不能再设置为-1(我在添加项目后尝试调用SelectedIndex)...我做错了什么?蚂蚁帮助将不胜感激!

小智 18

请记住,如果在执行DataSource/DataBind调用后调用它,myDropDownList.Items.Add将在底部添加一个新的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", ""));
Run Code Online (Sandbox Code Playgroud)

将"请选择"下拉项添加到顶部.

并且如前所述,在下拉列表中始终只有一个项目被选中(我相信ListBoxes是不同的),如果没有明确选择,则默认为前一个.


小智 5

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

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

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

使用 SelectedIndex 属性以编程方式指定或确定 DropDownList 控件中所选项目的索引。DropDownList 控件中的项目始终处于选中状态。您无法同时清除列表中每个项目的选择。

也许 -1 仅适用于获取而不适用于设置索引?如果是这样,我将使用你的“补丁”。


Ale*_*yev 5

可以使用客户端脚本将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>
Run Code Online (Sandbox Code Playgroud)

  • 小评论:使用jQuery 1.6或更新版本,$(elem).attr("selectedIndex")将不再起作用,因为selectedIndex是属性,而不是属性.请改用$(emel).prop("selectedIndex", - 1). (3认同)