Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I unselect item in ListView?

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.

like image 603
Zeemee Avatar asked Aug 17 '11 07:08

Zeemee


4 Answers

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.

like image 187
Vladimir Avatar answered Oct 23 '22 14:10

Vladimir


myListView.SelectedItems.Clear();
like image 27
Dave Avatar answered Oct 23 '22 15:10

Dave


I know this is late but in case someone else needed the solution I would like to add to the solution.

You need to set the Focused property to false to avoid deselected items having focus.

for (int i = 0; i < this.myListView.SelectedIndices.Count; i++)
{
    this.myListView.Items[this.myListView.SelectedIndices[i]].Selected = false;
    this.myListView.Items[this.myListView.SelectedIndices[i]].Focused = false;
}
like image 3
Brian Overby Avatar answered Oct 23 '22 13:10

Brian Overby


this is easier.

this.myListView.SelectedIndex = -1;
this.myListView.Update();
like image 1
Jason Jakob Avatar answered Oct 23 '22 13:10

Jason Jakob