0

我正在尝试从 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。

4

2 回答 2

1

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

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

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

于 2013-06-21T09:35:36.383 回答
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);
        }
    }

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

于 2013-06-21T09:09:11.620 回答