有没有快速的方法来选择所有项目或反转ListView中的选择?

时间:2010-02-22 14:54:35

标签: c# .net winforms listview

我可以使用其SelectedIndices.Clear方法快速清除ListView的选择,但如果我想选择所有项目,我必须这样做:

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

并反转选择,

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

有更快的方法吗?

3 个答案:

答案 0 :(得分:2)

使用ListViewItem.Selected属性:

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


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

编辑:这在虚拟模式下无效。

答案 1 :(得分:1)

快速选择ListView中的所有项目,请查看this question的长答案。这里概述的方法几乎是即时的,即使对于100,000个对象的列表也是如此。它可以在虚拟列表上运行。

ObjectListView提供许多等有用的快捷方式。

但是,无法自动反转选择。 SLaks方法适用于普通ListView,但不适用于虚拟列表,因为您无法枚举虚拟列表上的Items集合。

在虚拟列表中,您可以做的最好的事情就像您最初建议的那样::

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是.Net 3.5。如果您没有,请使用Dictionary进行快速查找。

请注意,对于大型虚拟列表,这仍然不会太快。每次lv.SelectedIndices.Add(i)来电都会触发RetrieveItem事件。

答案 2 :(得分:0)

您只需设置ListViewItem类的Selected属性即可。