简体   繁体   English

取消选中CheckedListBox中的错误项目

[英]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. 例如:我在列表框中获得了3个具有相同名称的项目,其中第一个已选中。 Now I run the event, but now the last 2 are removed, and the first one is unchecked... 现在我运行该事件,但是现在删除了最后2个,并且未选中第一个...

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. 如果我运行调试器,它将进入循环,执行i++ ,再次重复循环,转到else,在else之前,检查clbInstant(0)的检查状态,不检查clbInstant(1)的检查状态,并且i为1但是,在其他情况之后,我剩下2个项目,并且都未选中。 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... 现在,它第二次运行循环,并删除最后一个未选中的项目,结果剩下1个未选中的项目...

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)
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM