3

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

4

2 回答 2

5

Either

ListView1.SelectedItems.Clear();

or

ListView1.SelectedIndices.Clear();

should do the trick for select none, anyway.

于 2008-09-17T20:22:12.133 回答
4

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.

于 2011-05-23T13:10:19.523 回答