Creating controls at runtime and adding events

thanosm2003

Newcomer
Joined
Feb 28, 2008
Messages
1
The following code creates a new command button, at run time, named btnTest1. How can i add events(like btnTest1_click) to this object? How can i add code that hadles the events for this object? :(
Dim myButton As Button = New Button()
Me.Controls.Add(myButton)
myButton.Name = "btnTest1"
myButton.Size = New Size(45, 45)
myButton.Location = New Point(10, 10)
 
You'll have to have the event code written already, but then you would just do:

AddHandler myButton.Click, AddressOf btnTest1_click
 
Here is a complete sample of what Machaira suggested:

Code:
    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim myButton As System.Windows.Forms.Button = New System.Windows.Forms.Button
        myButton.Location = New System.Drawing.Point(10, 10)
        myButton.Name = "btnTest1"
        myButton.Size = New System.Drawing.Size(175, 43)
        myButton.TabIndex = 0
        myButton.Text = "Click me, please."
        With myButton
            AddHandler .Click, AddressOf myButton_Click
        End With
        Me.Controls.Add(myButton)
    End Sub

    Private Sub myButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim ClickedButton As Button = sender
        ClickedButton.Text = "I have been clicked!"
    End Sub
 
Back
Top