Is there an event that triggers if the number of ListViewItems in a ListView changes? (Windows Forms)

StackOverflow https://stackoverflow.com/questions/47169

  •  09-06-2019
  •  | 
  •  

Question

I'd like to enable/disable some other controls based on how many items are in my ListView control. I can't find any event that would do this, either on the ListView itself or on the ListViewItemCollection. Maybe there's a way to generically watch any collection in C# for changes?

I'd be happy with other events too, even ones that sometimes fire when the items don't change, but for example the ControlAdded and Layout events didn't work :(.

Was it helpful?

Solution

@Domenic

Not too sure, Never quite got that far in the thought process.

Another solution might be to extend ListView, and when adding and removing stuff, instead of calling .items.add, and items.remove, you call your other functions. It would still be possible to add and remove without events being raised, but with a little code review to make sure .items.add and .items.remove weren't called directly, it could work out quite well. Here's a little example. I only showed 1 Add function, but there are 6 you would have to implement, if you wanted to have use of all the available add functions. There's also .AddRange, and .Clear that you might want to take a look at.

Public Class MonitoredListView
    Inherits ListView

    Public Event ItemAdded()
    Public Event ItemRemoved()

    Public Sub New()
        MyBase.New()
    End Sub

    Public Function AddItem(ByVal Text As String) As ListViewItem
        RaiseEvent ItemAdded()

        MyBase.Items.Add(Text)
    End Function

    Public Sub RemoveItem(ByVal Item As ListViewItem)
        RaiseEvent ItemRemoved()

        MyBase.Items.Remove(Item)
    End Sub

End Class

OTHER TIPS

I can't find any events that you could use. Perhaps you could subclass ListViewItemCollection, and raise your own event when something is added, with code similar to this.

Public Class MyListViewItemCollection
    Inherits ListView.ListViewItemCollection

    Public Event ItemAdded(ByVal Item As ListViewItem)

    Sub New(ByVal owner As ListView)
        MyBase.New(owner)
    End Sub

    Public Overrides Function Add(ByVal value As System.Windows.Forms.ListViewItem) As System.Windows.Forms.ListViewItem
        Dim Item As ListViewItem

        Item = MyBase.Add(value)

        RaiseEvent ItemAdded(Item)

        Return Item
    End Function
End Class

I think the best thing that you can do here is to subclass ListView and provide the events that you want.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top