Getting the index of the item to be removed from the binding list

I can get the index of elements added to the BindingList. When I try to get the index if the deleted item gets an 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: Responses to C # are also welcome .... anyone?

+4
source share
2 answers

The item is deleted before the event occurs. This means that (without additional code) you cannot reach the element to be deleted.

However, you can 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 must also replicate the BindingList constructors. Also, do not try to make it canceled, as callers may suggest that calling Remove does remove the item.

+10
source

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

If you need an index over which the element was before it was deleted, perhaps saving a static variable, for example Private Shared removedIndex As Integer and setting it before deleting the element, will give you what you want?

0
source

All Articles