12

how to select all listview items ?

stuartd
  • 70,509
  • 14
  • 132
  • 163
pedram
  • 3,647
  • 6
  • 24
  • 28
  • There are many technologies and many types of listview in the C# world: asp.net, winforms, silverlight, wpf. Some more information and/or some code would help. – Steve Danner Aug 04 '10 at 13:01
  • 1
    Since most of the answers are for winforms, it probably wouldn't hurt anything to just add that tag. – jrh Jun 07 '18 at 17:09

4 Answers4

22

If there aren't very many items, this will do it:

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

If there are a lot of items, see this answer for how to use LVM_SETITEMSTATE.

stuartd
  • 70,509
  • 14
  • 132
  • 163
  • 1
    What if you have thousands of items? Is there a way of making this approach faster? – Alex Apr 24 '13 at 11:24
  • 1
    Calling [LVM_SETITEMSTATE](https://learn.microsoft.com/en-gb/windows/win32/controls/lvm-setitemstate) passing -1 as the index is the low-level way to set all items. – stuartd May 26 '20 at 00:31
  • @stuartd it would be helpful to post your own answer with C# code to do this rather then posting a vague comment. – HackSlash Jun 03 '20 at 16:57
  • @stuartd I have no mean intent. I'm saying that your comment could be a good answer and should stand on it's own. The link you provided has some information about C++ so it would be helpful to give an example of how you would use this in C# code. – HackSlash Jun 03 '20 at 17:10
  • 1
    OK, sorry. I didn't add it to the question because I've never actually had to use it. There's a C# example at https://stackoverflow.com/a/37146677/43846 though – stuartd Jun 03 '20 at 17:23
9

Just pass your listview and checkstate to the function.

public void CheckAllItems(ListView lvw, bool check)
{
    lvw.Items.OfType<ListViewItem>().ToList().ForEach(item => item.Checked = check);
}
Chandan Kumar
  • 4,570
  • 4
  • 42
  • 62
2

for UWP c# this is how I did it.

I have a Listview called, MembersList. to select all members I used the built-in method SellectAll() from the listview class.

The following code worked for me:

MembersList.SellectAll();

  • yes you can select all items in the listview with this code in my case i use imagelistview imageListView1.SelectAll(); – Anas Oct 24 '22 at 20:51
2

There is already an accepted answer for this but I use something similar to this:

lv.BeginUpdate();
List<ListViewItem> items = (from i in lv.Items).ToList;
items.ForEach(i => i.Selected == true);
lv.EndUpdate();

It seems to run much faster if there's several thousand items. Also, since we're using BeginUpdate() and EndUpdate(), the ListView control doesn't update after selecting each item.

artdanil
  • 4,952
  • 2
  • 32
  • 49
Jason
  • 31
  • 3