Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raising events from a List(Of T) in VB.NET

Tags:

vb.net

I've ported a large VB6 to VB.NET project and while it will compile correctly, I've had to comment out most of the event handlers as to get around there being no array collection for winform objects and so putting the various objects that were in at the collection array into a List object.

For example, in VB6 you could have an array of Buttons. In my code I've got

Dim WithEvents cmdButtons As New List(Of Button) 

(and in the Load event, the List is propagated)

Obviously, you can't fire an event on a container. Is there though a way to fire the events from the contents of the container (which will have different names)?

In the Button creation code, the event name is there, but from what I understand the handler won't intercept as the Handles part of the code is not there (commented out).

like image 852
Nodoid Avatar asked Oct 05 '22 15:10

Nodoid


1 Answers

I'm not exactly sure what you're after, but if you want to be able to add event handlers to some buttons in a container and also have those buttons referenced in a List, you can do something like

Public Class Form1

    Dim myButtons As List(Of Button)

    Private Sub AddButtonsToList(targetContainer As Control)
        myButtons = New List(Of Button)

        For Each c In targetContainer.Controls
            If TypeOf c Is Button Then
                Dim bn = DirectCast(c, Button)
                AddHandler bn.Click, AddressOf SomeButton_Click
                myButtons.Add(bn)
            End If
        Next
    End Sub

    Private Sub SomeButton_Click(sender As Object, e As EventArgs)
        Dim bn = DirectCast(sender, Button)
        MsgBox("You clicked " & bn.Name)
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ' GroupBox1 has some Buttons in it
        AddButtonsToList(GroupBox1)
    End Sub

End Class
like image 176
Andrew Morton Avatar answered Oct 13 '22 10:10

Andrew Morton