Hi guys,
I have a total of 72 link labels on a form and I want them to do a similar task.
Is there a way to accomplishing this without writing each labels individual code?

Example function of the link label

Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
Listbox1.Items.Add(Label1.Text)
variable = label1.text
    End Sub

 Private Sub LinkLabel2_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel2.LinkClicked
Listbox1.Items.Add(Label2.Text)
variable = label2.text
    End Sub

As the System.Windows.Forms.LinkLabelLinkClickedEventArgs contains the LinkLabel.Link you can use it to do your work. Yu'll need only one Sub like:

Private Sub LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) 
    Listbox1.Items.Add(e.Link.Text)
    variable = e.Link.Text
End Sub

Then, on the click event of each link label defined, change it to point to this sub.

Hope this helps.

You could also define a click event for just one of the controls in the set then use AddHandler on form load to add the other controls to that handler. It would save a lot of clicking. You would have to modify the original handler to distinguish between the controls. Or, if you don't mind some cut and paste you could add them as follows:

Private Sub lbl01_Click(sender As System.Object, e As System.EventArgs) Handles _
            lbl01.Click,lbl02.Click,lbl03.Click,lbl04.Click,...

Just extend the line for as many controls as you have. This gets a little messy, however, if you have a lot of controls. I recommend the AddHandler method.

Thank you both for your responses, unfortunatley I do not understand what you mean. I have tried both code suggestions but none seem to work as intended. Sorry for the hassle.

Any error? what is the expected result? can you pot something else that helps us to help you?

Try this. I created a form with five labels and one listbox.

Public Class Form1

    Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load

        AddHandler Label1.Click, AddressOf Label_Click
        AddHandler Label2.Click, AddressOf Label_Click
        AddHandler Label3.Click, AddressOf Label_Click
        AddHandler Label4.Click, AddressOf Label_Click
        AddHandler Label5.Click, AddressOf Label_Click

    End Sub

    Private Sub Label_Click(sender As System.Object, e As System.EventArgs)

        Dim label As Label = sender
        ListBox1.Items.Add(label.Text)

    End Sub

End Class

That is brilliant. Thank you for your help!! :) +1

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.