Dotnet: ListChangedType.ItemDeleted is useless?

The ListChanged event for IBindingList raises the type ListChangedType.ItemDeleted when items are deleted, possibly by the user deleting a row in the datagrid control associated with this list. The problem is that NewIndex in the list is invalid in this case, it was deleted, and the item that was deleted is not available. There should be an ItemDeleting event, but I doubt they will ever fix it.

+5
source share
4 answers

Yes, this is pretty annoying, but there is an easy workaround. I create a class BindingListBase<T>that I use for all my lists instead of the usual one BindingList<T>. Since my class inherits from BindingList<T>, I have access to all its protected members, including the method RemovedItem.

This allows me to choose when the item will be deleted. You can do what I do and have a list of mRemovedItems to which I always add items, or create my own “ItemRemoved” event.

See my sample code below:

Public MustInherit Class BindingListBase(Of T)
    Inherits BindingList(Of T)

    Protected mRemovedItems As New List(Of T)

    Protected Overrides Sub ClearItems()
        MyBase.ClearItems()
        mRemovedItems.Clear()
    End Sub

    Protected Overrides Sub RemoveItem(ByVal index As Integer)
        Dim item As T = MyBase.Item(index)

        MyBase.RemoveItem(index)

        mRemovedItems.Add(item)
    End Sub

    Public ReadOnly Property RemovedItems as List(Of T)
        Get
            Return mRemovedItems
        End Get
    End Property
End Class
+8
source

. NewIndex - , , , , .

, ItemDeleting?

+2

BindingList, ItemRemoved,

public class ItemRemovedEventArgs : EventArgs
{
    public Object Item { get; set; }

    public ItemRemovedEventArgs(Object item)
    {
        this.Item = item;
    }
}

public delegate void ItemRmoveEventHandler(Object sender, ItemRemovedEventArgs e);

public class BindingListRedux<T> : BindingList<T>
{
    public BindingListRedux() : base() { }

    public BindingListRedux(IList<T> list) : base(list) { }

    public event ItemRmoveEventHandler ItemRemoved;

    protected void OnItemRemoved(ItemRemovedEventArgs e)
    {
        if (ItemRemoved != null)
        {
            ItemRemoved(this, e);
        }
    }

    protected override void RemoveItem(int index)
    {
        Object item = base[index];
        base.RemoveItem(index);
        this.OnItemRemoved(new ItemRemovedEventArgs(item));
    }
}
+2

- , , .. ListChanging. , .

Sunlight ... , , , . - , , GUI, , . , GUI . HighestSeverityChanged , ( ), , GUI .

+1

All Articles