Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# CheckedListBox操作项检查是否删除项?_C#_Winforms_Checkedlistbox - Fatal编程技术网

C# CheckedListBox操作项检查是否删除项?

C# CheckedListBox操作项检查是否删除项?,c#,winforms,checkedlistbox,C#,Winforms,Checkedlistbox,当选中的框未选中时,我想删除该项。问题在于,在调用ItemCheck方法之后,检查/取消检查似乎发生了。因此,当我删除一个打乱e.索引的项目时,它会在我删除的项目之后对该项目进行检查/取消检查,或者如果它是最后一个项目,则会抛出一个错误 我发现:它有重置e.NewValue的提示,部分工作,但当我删除最后一项时,它仍然抛出一个错误 我没有简单地使用鼠标事件的原因是我希望键盘导航仍然是可能的,以防万一 这是我现在的代码 private void checked_ItemCheck(object s

当选中的框未选中时,我想删除该项。问题在于,在调用ItemCheck方法之后,检查/取消检查似乎发生了。因此,当我删除一个打乱e.索引的项目时,它会在我删除的项目之后对该项目进行检查/取消检查,或者如果它是最后一个项目,则会抛出一个错误

我发现:它有重置e.NewValue的提示,部分工作,但当我删除最后一项时,它仍然抛出一个错误

我没有简单地使用鼠标事件的原因是我希望键盘导航仍然是可能的,以防万一

这是我现在的代码

private void checked_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            if (e.NewValue == CheckState.Unchecked)
            {
                checked.Items.RemoveAt(e.Index);
                e.NewValue = CheckState.Checked;
            }
        }

感谢您的帮助

听起来您唯一仍然遇到的问题是在删除最后一项后调用
e.NewValue
,对吗?如果是这种情况,请尝试以下方法:

private void checked_ItemCheck(object sender, ItemCheckEventArgs e)
{
    if (e.NewValue == CheckState.Unchecked)
    {
        checked.Items.RemoveAt(e.Index);

        // If there are no items left, skip the CheckState.Checked call
        if (checked.Items.Count > 0)
        {
            e.NewValue = CheckState.Checked;
        }             
    }
} 
更新

好吧,我把它弄到手了,不过我不知道它有多漂亮。我使用了SelectedIndexChanged事件:

private void checked_SelectedIndexChanged(object sender, EventArgs e)
{

    CheckedListBox clb = (CheckedListBox)sender;
    int index = clb.SelectedIndex;

    // When you remove an item from the Items collection, it fires the SelectedIndexChanged
    // event again, with SelectedIndex = -1.  Hence the check for index != -1 first, 
    // to prevent an invalid selectedindex error
    if (index != -1 && clb.GetItemCheckState(index) == CheckState.Unchecked)
    {
        clb.Items.RemoveAt(index);
    }
}

我已经在VS 2010中对此进行了测试,并且效果良好。

这几乎就是问题所在。您的想法很好,但即使if语句阻止我的代码更改e.NewValue,似乎用于检查/取消检查的默认代码仍然会执行,并给出一个NullReferenceException。如果代码能被停止,我会很好。有什么方法可以覆盖默认代码吗?@Simon the Cat-给我15或20分钟的时间来尝试一些东西,如果我解决了这个问题,我会发布一个更新。@Simon the Cat-好的,所以我花了一个小时,但我有一个解决方案应该适合你。嘿,太好了!谢谢你花了一个小时来解决这个问题。那一次我撞到了砖墙。