【问题标题】:How to delete all items from a group in ListView component c#如何从 ListView 组件 c# 中的组中删除所有项目
【发布时间】:2013-06-21 09:01:00
【问题描述】:

我正在尝试从 ListView 组件 (C# .NET 4.0) 中的 ListViewGroup 中删除所有项目。我尝试了以下方法,但它们返回了意想不到的行为。

    listView1.Groups[4].Items.Clear(); // Does only remove the item from the group, 
                                       // but is then placed in a new Default group.

foreach (ListViewItem item in listView1.Groups[4].Items)
{ 
    item.Remove(); 
}
// This throws an error which says that the list is changed.

我现在用listView1.Items.Clear();清空组内所有项目,并一一读取。但是,这会导致我的 GUI 在执行此操作时闪烁。我想知道如何删除组中的所有项目。所以我只需要重新添加项目组(我想要的,因为项目的数量不同,名称和子项目也不同)。

注意:该组称为lvgChannels,索引为4。

【问题讨论】:

    标签: c# .net winforms listview


    【解决方案1】:

    试试这个:

    List<ListViewItem> remove = new List<ListViewItem>();
    
            foreach (ListViewItem item in listView1.Groups[4].Items)
            {
                remove.Add(item);
            }
    
            foreach (ListViewItem item in remove)
            {
                listView1.Items.Remove(item);
            }
        }
    

    您的第二个语句的问题是您从正在迭代的列表中删除了一个项目。

    【讨论】:

    • 我知道你在做什么,但是从第一组中删除的项目到底是怎样的?您不只是将项目从组中复制到项目列表中,然后从该列表中删除项目吗?
    • 我自己不考虑这个我觉得很愚蠢,它有效,非常感谢:)
    【解决方案2】:

    您需要从列表视图本身中删除该组中列出的所有项目的项目。

    for (int i = listView1.Groups[4].Items.Count; i > 0; i--)
    {
        listView1.Items.Remove(listView1.Groups[4].Items[i-1]);
    }
    

    您的代码的问题是您正在执行递增而不是递减。每次删除一个项目时计数递减,因此 for 循环应该从最大计数开始并递减到 0。

    【讨论】:

    • 他的代码的这个问题就是你提到的,除了他正在对正在迭代的列表进行更改,解决方案是使用for循环而不是foreach,只是像你一样。
    猜你喜欢
    • 2011-03-01
    • 2017-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-19
    • 2021-05-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多