【问题标题】:CheckedListBox Action ItemCheck to remove items?CheckedListBox Action ItemCheck 删除项目?
【发布时间】:2011-08-02 22:21:00
【问题描述】:

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

我发现了这个:Getting the ListView ItemCheck to stop!,它有重置 e.NewValue 的提示,它部分有效,但是当我删除最后一项时它仍然会引发错误。

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

这是我现在的代码。

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

感谢您的帮助

【问题讨论】:

    标签: c# winforms checkedlistbox


    【解决方案1】:

    听起来您仍然遇到的唯一问题是在删除最后一项后调用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 - 好的,我花了一个小时,但我有一个适合你的解决方案。
    • 嘿,效果很好!感谢您抽出一个小时来解决这个问题。我在那上面撞了一堵砖墙。
    猜你喜欢
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多