简体   繁体   中英

How to deselect a single Item in a listbox

I have a listbox on my asp page, and I was wondering if there was anyway in code behind or javascript to deselect a selected item in my listbox. the selection mode is single.

Any help please? I tried adding a handler on selectedindexchanged...but it doesn't hit it if I am clicking on the same selectedItem.

I fixed my issue as Andrew pointed out, by setting the SelectedIndex = -1; But, this created weird behavior since now I would have A checkboxList being populated from the selected list item I chose, and there was no Idea to see which list item populated it after wards.

So What I did was added 2 more lines of code on top of what andrew suggested and it worked great.

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

Thanks for pushing me in the right direction!

You can use the following workaround if your SelectionMode="Single" and you want to deselect an item on second click.

Create a property in your page to keep the last selected list item value using session. I am assuming the selected value in your listbox is always int

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

    }
    set { Session["ListBoxLastSelected"] = value; }
}

Create the following method

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

On your Page_Load add the below code

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM