2011-08-02 47 views
0

当勾选的框未选中时,我想删除该项目。检查/取消选中的麻烦似乎在调用ItemCheck方法后发生。所以,当我删除一个项目,e.Index的混乱,所以它做检查/取消选中后,我删除的项目或抛出一个错误,如果它是最后一个。CheckedListBox操作ItemCheck删除项目?

我发现这个: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; 
      } 
     } 

感谢您的帮助

回答

3

这听起来像您仍然遇到是调用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; 
     }    
    } 
} 

UPDATE

好了 - 我得到它的工作,虽然我不知道它是多么可爱。我使用的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中测试这和它的作品。

+0

这几乎是问题所在。你的想法是好的,但即使if语句阻止我的代码改变e.NewValue,似乎检查/取消选中的默认代码仍然执行并给出NullReferenceException。如果该代码可以停止,我会很好。会有一些方法来覆盖默认代码吗? –

+0

@Simon猫 - 给我15或20分钟来尝试一些事情,如果我修正了这个问题,我会发布更新。 – Tim

+0

@Simon猫 - 好吧,所以花了我一个小时,但我有一个解决方案,应该为你工作。 – Tim