如何从CheckedListBox中删除多个选中的项目 [英] How to delete multiple checked items from CheckedListBox

查看:17
本文介绍了如何从CheckedListBox中删除多个选中的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何从 checkedlistbox 中删除单个 checkedItem.但是现在,我想一口气删除所有选中的项目.

I know how to remove a single checkedItem from checkedlistbox. But now, I want to remove all the checked items in one go.

我试过了:

foreach (var item in List_Frente.CheckedItems)
            {
                List_Frente.Items.Remove(item);
            }

但正如您可能知道的那样,它给了我一个错误,说此枚举器绑定到的列表已被修改.仅当列表未更改时才能使用枚举器. 如何通过单击删除所有 checkeditems ?

But as you probably know, it gives me an error,saying that, List that this enumerator is bound to has been modified. An enumerator can only be used if the list does not change. How may I remove all checkeditems with a single click ?

推荐答案

你可以这样做:

foreach (var item in List_Frente.CheckedItems.OfType<string>().ToList())
{
    List_Frente.Items.Remove(item);
}

如果你想把它写成一行:

If you want to write it all in one line:

List_Frente.CheckedItems.OfType<string>().ToList().ForEach(List_Frente.Items.Remove);

当然,这仅在您的物品类型相同时才有效.不过看起来还是很粗糙.

This only works if your items are of the same type, of course. Looks still crude, though.

编辑-解释:ToList() 创建一个新列表,因此可以更改原始 CheckedItems 列表,因为枚举器现在枚举我们新创建的列表,而不是原始列表.OfType() 之所以存在,只是因为我们需要一些东西来调用 ToList().

Edit-Explanation: ToList() creates a new list and thus, the original CheckedItems list can be changed, as the enumerator now enumerates our newly created list, not the original. The OfType<string>() is only there because we need something to call ToList() on.

这篇关于如何从CheckedListBox中删除多个选中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆