How to delete multiple checked items from CheckedListBox

久未见 提交于 2019-12-10 13:54:30

问题


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

I tried this:

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

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 ?


回答1:


you could do something like this:

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.

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.




回答2:


This is because you modify the list you are iterating over. Use a for-statement to prevent this from happening:

for(var i=0; i<List_Frente.CheckedItems.Count; i++)
{
    ((IList)List_Frente.CheckedItems).Remove(List_Frente.CheckedItems[0]);
}

As stated in this MSDN-Article the CheckedListBox.CheckedItemCollection implements the IList.Remove-method explicitly, meaning you will have to cast the instances to IList to make this work.




回答3:


while (checkedListBox.CheckedItems.Count > 0) {
   checkedListBox.Items.RemoveAt(checkedListBox.CheckedIndices[0]);
}



回答4:


This works.

object[] items = new object[checkedListBox.Items.Count];
checkedListBox.Items.CopyTo(items, 0);
checkedListBox.Items.Clear();
checkedListBox.Items.AddRange(items);

I aim to return with an solution that are more beautiful and less hacky.




回答5:


Might be an addon for this post.

To clear all the items.

checkedListBox1.Items.Clear();


来源:https://stackoverflow.com/questions/14590726/how-to-delete-multiple-checked-items-from-checkedlistbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!