2011-08-02 48 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