开发者

Is there a quick way of selecting all items or inverting the selection in a ListView?

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?


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜