One CLICK Event for Multiple LABEL Controls

jtstanish

Newcomer
Joined
Dec 10, 2004
Messages
10
I have over 100 label controls on a single form. How can I have them all call the same subroutine when any one of them is clicked? I also need to pass the address of the control to the subroutine so that I can change the properties to the control that was clicked! I NEED A CODE EXAMPLE.
:o
 
You have to use AddHandler to do that.

It is used like this: AddHandler <Object>.<Event>, AddressOf <EventHandler>

The way I did it, you have to write your own form code.

I created an array of labels, and initialized them in the SetupLabels subroutine.

In a For...Next loop, I setup the label, and added a handler to the label.

Visual Basic:
Public Class Form1
    Inherits System.Windows.Forms.Form

    Dim Labels(10) As Label

    Public Sub New()
        MyBase.New()

        SetupLabels()

    End Sub
    
    Private Sub SetupLabels()

        Dim Looper As Integer

        For Looper = 0 To Labels.Length - 1

            ' Create a new label
            Labels(Looper) = New Label

            ' Setup Label here
            Labels(Looper).Text = Looper.ToString()

            Labels(Looper).Top = Looper * 25

            ' Adds a click event handler to the current label
            ' AddressOf is needed to get the address of the subroutine
            AddHandler Labels(Looper).Click, AddressOf LabelsClick

        Next

        ' Adds the controls to the form's ControlCollection
        Controls.AddRange(Labels)

    End Sub

    ' This is the event handler for all of the labels:
    Sub LabelsClick(ByVal sender As Object, ByVal e As EventArgs)

        MessageBox.Show(CType(sender, Label).Text)

    End Sub

End Class
 
Last edited:
Back
Top