How can I unselect item in ListView?

Zeemee picture Zeemee · Aug 17, 2011 · Viewed 49.5k times · Source

I have a ListView with a couple of items in it. When the ListView looses focus, the last selected ListViewItem is still "selected" with a gray background.
I would like to achieve that on ListView.FocusLost, the selection is gone and therefore the ListView.SelectedIndexChanged event will occur.
Any ideas?

I am using .NET CF 3.5.

Answer

Vladimir picture Vladimir · Aug 17, 2011

Suppose you are accessing the ListView from a parent form/control.

You can add this piece of code in the form's/control's constructor/load event:

this.myListView.LostFocus += (s, e) => this.myListView.SelectedIndices.Clear();

Ok, so in your case, you would replace that delegate with:

if (this.myListView.SelectedIndices.Count > 0)
    for (int i = 0; i < this.myListView.SelectedIndices.Count; i++)
    {
        this.myListView.Items[this.myListView.SelectedIndices[i]].Selected = false;
    }

You can give the code a nicer form, btw.