2009-08-07 163 views
4

我能夠獲得添加到BindingList的項目的索引。當我試圖讓索引,如果刪除的項目出現錯誤從綁定列表中獲取已刪除項目的索引

Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index 

這裏是我的代碼

Private Sub cmdRemove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdRemove.Click 

    For i As Integer = 0 To _assignedSelection.SelectedCount - 1 
     Dim item As Jurisdiction = CType(_assignedSelection.GetSelectedRow(i), Jurisdiction) 
     _list.Remove(item) 
    Next 

End Sub 


Private Sub list_Change(ByVal sender As Object, ByVal e As ListChangedEventArgs) Handles _list.ListChanged 

    If (_list.Count > 0) Then 


     Select Case e.ListChangedType 
      Case ListChangedType.ItemAdded 
       _dal.InsertJurisdiction(_list.Item(e.NewIndex)) 
      Case ListChangedType.ItemDeleted 
       'MsgBox(e.NewIndex.ToString) 
       _dal.DeleteJurisdiction(_list.Item(e.NewIndex)) <--------HERE 
     End Select 

    End If 

End Sub 

編輯:在C#的答案,也歡迎任何人....?

回答

10

該項目被刪除之前事件發生。這意味着(沒有額外的代碼),你不能到達被刪除的項目。

你可以,但是,從繼承的BindingList,並重寫的removeItem:

public class BindingListWithRemoving<T> : BindingList<T> 
{ 
    protected override void RemoveItem(int index) 
    { 
     if (BeforeRemove != null) 
      BeforeRemove(this, 
        new ListChangedEventArgs(ListChangedType.ItemDeleted, index)); 

     base.RemoveItem(index); 
    } 

    public event EventHandler<ListChangedEventArgs> BeforeRemove; 
} 

你也應該複製的BindingList構造。此外,請勿嘗試將其取消,因爲致電者可能會認爲致電Remove確實刪除了該物品。

+1

這是一個記錄了幾個解決方法的錯誤(如peterchen友好提供的)! http://link.microsoft.com/VisualStudio/feedback/details/148506/listchangedtype-itemdeleted-is-useless-because-listchangedeventargs-newindex-is-already-gone – Harrison 2011-02-22 18:03:09

+0

@哈里森:感謝您的連接鏈接! – peterchen 2011-02-22 19:24:54

+0

這個事件的主要目的是傳達UI控件應該刪除的位置。 – 2016-09-05 09:37:44

0

我有點困惑你的問題的措辭。但是,如果某個項目已被刪除,則該項目不再被編入索引。

如果您需要項目在刪除之前所處的索引,可能是存儲了一個靜態變量(例如Private Shared removedIndex As Integer),並在刪除項目之前設置該變量會給您想要的內容?

+0

不應該ListChanged事件給綁定列表中更改的項目的索引? – 2009-08-13 06:44:00

+0

它確實 - 但事後,請看我的回覆。 – peterchen 2010-02-21 14:54:19

相關問題