Steve Butcher
Steve Butcher

Reputation: 91

How to make a click event for runtime created controls in Visual Basic 2010?

I added some controls to my form at runtime and I need them to call a function when clicked. I don't know how many controls will be added but they all need to run the same function. How would I define the event? Can I define events based on all controls of a given class?

Upvotes: 3

Views: 23886

Answers (2)

SysDragon
SysDragon

Reputation: 9888

Simply:

AddHandler Control.Event, AddressOf MethodExecuting

For example:

AddHandler Button1.Click, AddressOf ClickMethod

Upvotes: 2

Parimal Raj
Parimal Raj

Reputation: 20575

A simple example :

Public Class Form1


    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ' creating control
        Dim btn1 As Button = New Button()
        Dim btn2 As Button = New Button()

        btn1.Parent = Me
        btn1.Name = "btn1"
        btn1.Top = 10
        btn1.Text = "Btn1"

        btn2.Parent = Me
        btn2.Name = "btn2"
        btn2.Top = 50
        btn2.Text = "Btn2"

        'adding handler for click event
        AddHandler btn1.Click, AddressOf HandleDynamicButtonClick
        AddHandler btn2.Click, AddressOf HandleDynamicButtonClick


    End Sub

    Private Sub HandleDynamicButtonClick(ByVal sender As Object, ByVal e As EventArgs)
        Dim btn As Button = DirectCast(sender, Button)

        If btn.Name = "btn1" Then
            MessageBox.Show("Btn1 clicked")
        ElseIf btn.Name = "btn2" Then
            MessageBox.Show("Btn2 Clicked")
        End If

    End Sub
End Class

Upvotes: 8

Related Questions