views:

97

answers:

3

I can quickly clear the selection of a ListView using its SelectedIndices.Clear method, but if I want to select all the items, I have to do this:

for (int i = 0; i < lv.SelectedIndices.Count; i++)
{
    if (!lv.SelectedIndices.Contains(i))
        lv.SelectedIndices.Add(i);
}

and to invert the selection,

for (int i = 0; i < lv.SelectedIndices.Count; i++)
{
    if (lv.SelectedIndices.Contains(i))
        lv.SelectedIndices.Add(i);
    else
        lv.SelectedIndices.Remove(i);
}

Is there a quicker way?

+2  A: 

Use the ListViewItem.Selected property:

foreach(ListViewItem item in lv.Items)
    item.Selected = true;


foreach(ListViewItem item in lv.Items)
    item.Selected = !item.Selected;

EDIT: This won't work in virtual mode.

SLaks
it's more concise, but is it quicker? Does it work in virtual mode?
Simon
@Simon: Yes, it will work in virtual mode. In virtual mode, it will be slower, but without virtual mode, it will have the same performance.
SLaks
A: 

You can just set the Selected property of the ListViewItem class.

Giorgi
+1  A: 

To quickly select all the items in a ListView, have look at the long answer to this question. The method outlined there is virtually instantaneous, even for lists of 100,000 objects AND it works on virtual lists.

ObjectListView provides many helpful shortcuts like that.

However, there is no way to automatically invert the selection. SLaks method will work for normal ListViews, but not for virtual lists since you can't enumerate the Items collection on virtual lists.

On a virtual list, the best you can do is something like you first suggested::

static public InvertSelection(ListView lv) {
    // Build a hashset of the currently selected indicies
    int[] selectedArray = new int[lv.SelectedIndices.Count];
    lv.SelectedIndices.CopyTo(selectedArray, 0);
    HashSet<int> selected = new HashSet<int>();
    selected.AddRange(selectedArray);

    // Reselect everything that wasn't selected before
    lv.SelectedIndices.Clear();
    for (int i=0; i<lv.VirtualListSize; i++) {
        if (!selected.Contains(i))
            lv.SelectedIndices.Add(i);
    }
}

HashSet is .Net 3.5. If you don't have that, use a Dictionary to give fast lookups.

Be aware, this will still not be lightning fast for large virtual lists. Every lv.SelectedIndices.Add(i) call will still trigger a RetrieveItem event.

Grammarian
Brilliant - the long answer is exactly what I was after. For inverting, I'll probably either clear then add, or select all and remove, depending on whether 50% of the rows are selected.
Simon
Actually, you can use the `Items` collection in Virtual Mode. However, it will create the ListViewItem in the indexer, so you should avoid it where possible. (I checked the source)
SLaks
@SLaks You can use `Items`, but you *cannot* enumerate it. If you try, it will throw an exception.
Grammarian