Unchecking wrong item in CheckedListBox
I'm trying to make an option, to remove all unchecked items in a checked listbox. Everything is going fine, but when I get 2 or more items with the same name, it goes wrong.
For example: I got 3 items in the listbox with the same name, with the first one checked. Now I run the event, but now the last 2 are removed, and the first one is unchecked...
private void removeAllUncheckedProcessesToolStripMenuItem_Click(object sender, EventArgs e)
{
int i = 0;
while (true)
{
if (clbInstant.Items.Count - i == 0)
{
break;
}
if (clbInstant.GetItemCheckState(i) == CheckState.Checked)
{
i++;
}
else
{
clbInstant.Items.Remove(clbInstant.Items[i]);
}
}
}
If I run the debugger, it enters the loop, does i++
, repeats the l开发者_开发问答oop again, goes to the else, before the else, checkstate of clbInstant(0)
is checked, the checkstate of clbInstant(1)
is unchecked and i
is 1. But after the else, I got 2 items remain, with both unchecked.
Now it runs the loop for the second last time, and it removes the last unchecked item, with the result of 1 unchecked item remain...
If I have items with different names, I got no problem at all...
Why dont you try this instead.
foreach(object itemChecked in checkedListBox1)
{
if(checkedListBox1.GetItemCheckState(checkedListBox1.Items.IndexOf(itemChecked))== CheckState.UnChecked)
checkedListBox1.Items.Remove(itemChecked)
}
精彩评论