Question

What is a good way to select all or select no items in a listview without using:

foreach (ListViewItem item in listView1.Items)
{
 item.Selected = true;
}

or

foreach (ListViewItem item in listView1.Items)
{
 item.Selected = false;
}

I know the underlying Win32 listview common control supports LVM_SETITEMSTATE message which you can use to set the selected state, and by passing -1 as the index it will apply to all items. I'd rather not be PInvoking messages to the control that happens to be behind the .NET Listview control (I don't want to be a bad developer and rely on undocumented behavior - for when they change it to a fully managed ListView class)

Bump

Pseudo Masochist has the SelectNone case:

ListView1.SelectedItems.Clear(); 

Now just need the SelectAll code

Was it helpful?

Solution

Wow this is old... :D

SELECT ALL

 listView1.BeginUpdate(); 
 foreach (ListViewItem i in listView1.Items)
 {
     i.Selected = true;
 }
 listView1.EndUpdate();

SELECT INVERSE

 listView1.BeginUpdate(); 
 foreach (ListViewItem i in listView1.Items)
 {
     i.Selected = !i.Selected;
 }
 listView1.EndUpdate();

BeginUpdate and EndUpdate are used to disable/enable the control redrawing while its content is being updated... I figure it would select all quicker, since it would refresh only once, and not listView.Items.Count times.

OTHER TIPS

Either

ListView1.SelectedItems.Clear();

or

ListView1.SelectedIndices.Clear();

should do the trick for select none, anyway.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top