Link to home
Start Free TrialLog in
Avatar of michelsf
michelsf

asked on

VB.NET: How to Handle Events of Objects inside a Generic List

Hello,
i developed code that works fine so far but now i would like to upgrade from a single element to multiple elements using a generic list (that´s what i thought of, maybe you know something better) so i changed my codeing from

Protected WithEvents MyObject
to
Protected WithEvents myList As List(Of MyObject)

i used to handle the CurrentChanged event of MyObject

so i thought i could do something lilke this

change from
Private Sub _CurrentChanged() Handles  MyObject.CurrentChanged
to
Private Sub _CurrentChanged() Handles MyList.ITEM.CurrentChanged

which does not work, and i did not yet find a solution for my simple problem, can anyone help ?

Kind Regards Frank





Avatar of kaufmed
kaufmed
Flag of United States of America image

When you add events to your list, you have to add handlers to them also. An example is below. Also, I think the "WithEvents" clause is meaningless for a List, but I'd love to know otherwise  :)
Protected myList As List(Of MyObject)

...

' create temp var
Dim obj As New MyObject()
' add the handler
AddHandler(obj.CurrentChanged, AddressOf _CurrentChanged)
' add to list
Me.myList.Add(obj)

...

Private Sub _CurrentChanged()

Open in new window

>>  When you add events to your list,

That should say, "when you add *objects* to your list..."
So typically you'd "wire up" all the dynamic instances with AddHandler() as outlined by kaufmed...

...does the CurrentChanged() event of MyObject provide a "sender" or "source" parameter so you can distinguish which instance fired the event?

For instance, most .Net events have a "sender" parameter tells which button fired the event:
Public Class Form1

    Private Buttons As New List(Of Button)

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        For i As Integer = 1 To 5
            Dim btn As New Button
            btn.Text = "Button #" & i
            AddHandler btn.Click, AddressOf btn_Click
            FlowLayoutPanel1.Controls.Add(btn)
            Buttons.Add(btn)
        Next
    End Sub

    Private Sub btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim btn As Button = CType(sender, Button)
        MessageBox.Show("You clicked on: " & btn.Text)
    End Sub

End Class

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of michelsf
michelsf

ASKER

Thank you guys works fine !!!