views:

519

answers:

2

Hi, I am able to get the index of items added to the BindingList. When I try to get the index if the deleted item I get the error

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

Here is my code

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

EDIT: Answers in C# are also welcome....anyone?

A: 

I am a little confused with the wording of your question. However, an item is no longer indexed if it has been removed.

If you need the index that the item was at before it was removed, perhaps storing a static variable, such as Private Shared removedIndex As Integer and setting that before you remove the item, will give you what you want?

Chris
shouldn't the ListChanged event give the index of the changed item in a bindinglist?
Saif Khan
It does - but after the fact, see my reply.
peterchen
+1  A: 

The item is removed before the event fires. This means (without additional code) you cannot get to the item being removed.

You can, however, inherit from BindingList, and override 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;
}

You should also replicate the BindingList constructors. Also, don't try to make it cancellable, as callers may assume calling Remove does indeed remove the item.

peterchen