如何取消选择列表框中的单个项目

本文关键字:单个 项目 列表 选择 何取消 取消 | 更新日期: 2023-09-27 17:58:43

我的asp页面上有一个列表框,我想知道是否有代码隐藏或javascript可以取消选择列表框中的选定项目。选择模式是单一的。

请帮忙吗?我尝试在选定的索引上添加处理程序已更改。。。但如果我点击同一个selectedItem,它不会击中它。

如何取消选择列表框中的单个项目

正如Andrew所指出的,我通过设置SelectedIndex=-1解决了我的问题;但是,这造成了奇怪的行为,因为现在我会从我选择的列表项中填充一个复选框列表,并且不知道在病房之后填充了哪个列表项。

因此,我所做的是在andrew建议的基础上再添加了两行代码,效果很好。

            var index = lstGroups.SelectedIndex;
            lstGroups.SelectedIndex = -1;
            lstGroups.Items[index].Attributes["style"] = "background-color:lightblue";

谢谢你把我推向正确的方向!

如果您的SelectionMode="Single"想要在第二次单击时取消选择项目,则可以使用以下解决方法。

在页面中创建一个属性,以使用会话保留上次选择的列表项值。我假设您列表框中选择的值总是int

public int ListBoxLastSelected
{
    get
    {
        if (Session["ListBoxLastSelected"] != null)
            return Convert.ToInt32(Session["ListBoxLastSelected"]);
        return -1;
    }
    set { Session["ListBoxLastSelected"] = value; }
}

创建以下方法

private void EnableListboxDeselect()
{
    if (!IsPostBack)
    {
        // Register a postback event whenever you click on the list item
        ClientScriptManager cs = Page.ClientScript;
        lstMyList.Attributes.Add("onclick", cs.GetPostBackEventReference(lstMyList, "clientClick"));
        Session["ListBoxLastSelected"] = null;
    }
    if (IsPostBack)
    {
        // Ensure the postback is from js side
        if (Request["__EVENTARGUMENT"] != null && Request["__EVENTARGUMENT"] == "clientClick")
        {
            if (CorpListLastSelected == Convert.ToInt32(lstMyList.SelectedValue))
            {
                lstMyList.ClearSelection();
                CorpListLastSelected = -1;
            }
            else
            {
                ListBoxLastSelected= Convert.ToInt32(lstMyList.SelectedValue);
            }
        }
    }
}

在您的Page_Load上添加以下代码

protected void Page_Load(object sender, EventArgs e)
{
     EnableListboxDeselect();
}