I want to remove several checked items from checkedListBox but I can't.This is my example. I was trying it but i was imposiible to get.
for (int i = 0; i < checkedListBox1.Items.Count; i++){
if (checkedListBox1.GetItemChecked(i))
{
checkedListBox1.Items.Remove(checkedListBox1.CheckedItems[i]);
}
}
Let's say you have a CheckedListBox of 2 items, both checked. If you delete item 1
then item 2
becomes the new item 1
and hence will never be deleted.
This is what's going on in detail:
i
is initialized to 0. i
is less than checkedListBox1.Items.Count
(which is 2). Loop entered.checkedListBox1.GetItemChecked(i)
returns true. checkedListBox1.Items.Remove(checkedListBox1.CheckedItems[i])
removes item at index 0. i
is incremented to 1. i
is not less than checkedListBox1.Items.Count
(which is 1) and the loop exits. hence item 2
will not be deleted.
Reverse the loop and it should work:
for (int i = checkedListBox1.Items.Count - 1; i >= 0; i--)
{
if (checkedListBox1.GetItemChecked(i))
{
checkedListBox1.Items.Remove(checkedListBox1.Items[i]);
}
}
Another way of doing this is as follows:
while (checkedListBox1.CheckedItems.Count > 0)
{
checkedListBox1.Items.RemoveAt(checkedListBox.CheckedIndices[0]);
}
And another:
while (checkedListBox1.CheckedItems.Count > 0)
{
checkedListBox1.Items.Remove(checkedListBox1.CheckedItems[0]);
}
Yet another:
foreach (var i in checkedListBox1.CheckedIndices)
{
checkedListBox1.Items.RemoveAt(i);
}
Going on:
for(var i = 0; i < checkedListBox1.CheckedItems.Count; i++)
{
((IList) checkedListBox1.CheckedItems).Remove(checkedListBox1.CheckedItems[0]);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.