tags:

views:

133

answers:

3

When an item is added to the BindingList, the ListChange event lets me know so I can react accordingly.

However, when an item is Removed from the list, the ListChange event comes too late, as the item is no longer in the list. How can you catch the removal before it has been removed?

I need to identify the object so I can remove an event handler that has been attached to it.

+2  A: 

The current implementation of BindingList<T> doesn't appear to support this. Your best option may be to create your own implementation of BindingList which has a Removing event:

public class MyBindingList<T> : BindingList<T>
{
    public event ListChangedEventHandler Removing;

    protected void OnRemoving(ListChangedEventArgs e)
    {
        if(Removing != null)
        {
            Removing(this, e);
        }
    }

    protected override void RemoveItem(int index)
    {
        if(index > -1 && index < this.Count)
        {
            OnRemoving(new ListChangedEventArgs(ListChangedType.ItemDeleted, index));
            base.RemoveItem(index);
        }
    }
}
Rex M
Thanks for that - I was able to apply your C# code to my VB application and it works well.
Bill
+1  A: 

The VB implentation of Rex's C# code.

Imports System.ComponentModel

Public Class MyBindingList
    Inherits BindingList(Of T)

    Public Event Removing As ListChangedEventHandler

    Protected Overrides Sub RemoveItem(ByVal index As Integer)
        If index > -1 AndAlso index < Me.Count Then
            RaiseEvent Removing(Me, New ListChangedEventArgs(ListChangedType.ItemDeleted, index))
        End If
        MyBase.RemoveItem(index)
    End Sub

End Class
Bill
A: 

I have tried the option described by "Rex M" in overriding the RemoveItem method. However, the Clear() method does not trigger this method. I'm still looking for a solution for that. But, maybe it doesn't apply to you.

bsh152s