user3697824
user3697824

Reputation: 536

BindingList ListChanged event firing twice

I am using the ListChanged event BindingList(Of Foo) to notify an unbound control when the list contents have changed. I am only worried about items added or removed. The problem is that the event is fired twice for each Add or Delete action.

The app adds an item like this:

For n As Integer = 0 To 5
    a = CreateItem(n)    ' create test object
    BList.Add(a)         ' add to BindingList
Next

The event is processed like this:

Private Sub _BListChanged(sender As Object, e As ListChangedEventArgs) 
           Handles _BListSource.ListChanged
    ' ...
        Select Case e.ListChangedType
            Case ListChangedType.ItemAdded
                ' add item to control
                AddItem(_BListSource(e.NewIndex))

                ' show whats happening
                Console.WriteLine("ev {0} old {1} new {2} obj count {3} name{4}",
                                  e.ListChangedType.ToString,
                                  e.OldIndex.ToString,
                                  e.NewIndex.ToString,
                                  _BListSource.Count.ToString,
                                  _BListSource(e.NewIndex).ToString)

The console debug shows it being called twice (besides the fact that the control doubles up items):

ev ItemAdded old -1 new 0 obj count 1 name Able   
ev ItemAdded old -1 new 0 obj count 1 name Able 
ev ItemAdded old -1 new 1 obj count 2 name Baker 
ev ItemAdded old -1 new 1 obj count 2 name Baker 
ev ItemAdded old -1 new 2 obj count 3 name Charlie 
ev ItemAdded old -1 new 2 obj count 3 name Charlie

Other info:

Is there something analogous to e.Handled or an overall property setting I am missing? I am tempted to inherit from BindingList use some overrides to fix things, but this is otherwise a trivial aspect of the app.

Upvotes: 1

Views: 888

Answers (1)

GazTheDestroyer
GazTheDestroyer

Reputation: 21261

Make sure you're not subscribing to the event twice. Events will callback for every subscriber, even if that subscriber already exists.

Upvotes: 1

Related Questions