Skip to main content
 首页 » 编程设计

c#之CheckedListBox Action ItemCheck 删除项目

2024年02月23日15mfryf

当不选中检查的盒子时,我想删除该项目。问题是检查/取消检查似乎发生在调用 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; 
            } 
        } 

感谢帮助

请您参考如下方法:

听起来您仍然遇到的唯一问题是在删除最后一项后调用 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 中对此进行了测试并且它有效。