Zeemee Zeemee - 1 year ago 91
C# Question

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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download