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?
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
Itemscollection on virtual lists.On a virtual list, the best you can do is something like you first suggested::
HashSetis .Net 3.5. If you don’t have that, use aDictionaryto 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 aRetrieveItemevent.