tags:

views:

33

answers:

1

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 loop 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 diferent names, I got no problem at all...

What to do...

A: 

Why dont you try this instead.

    foreach(object itemChecked in checkedListBox1) 
    {
       if(checkedListBox1.GetItemCheckState(checkedListBox1.Items.IndexOf(itemChecked))== CheckState.UnChecked)
          checkedListBox1.Items.Remove(itemChecked)
    }
kyndigs
Revised answer.
kyndigs
.CheckedItems is possible, but for some reason .UncheckedItems is not...
Ivar
Sorry that was a typo :p sorted now, this should go through all list items and remove unchecked ones.
kyndigs
If I use it and I check 1 or more checkboxes, it does nothing.When I check none, I get a 'InvalidOperationException was unhandled' message.
Ivar
Remove the .CheckedItems from the foreach part.
kyndigs