Binding action to button.
First of all I'd like to say that I'm completely new to programming and VB. Therefore I have a stupid problem.
I want to make a form that makes a button when loaded. How can I make this button work (meaning that something happens when button is clicked)?
At the moment my code is:
Public Class Form1
Dim button As New Button
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
button.Text = "Button"
Me.Controls.Add(button)
End Sub
Private Sub button_click()
MsgBox ("It works!")
End Sub
End Class
Of course, this code doesn't work. It makes succesfully a button on the form, but that button does noting.
I hope I made myself clear about what my aim is.
Re: Binding action to button.
Change this like this:
vb Code:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim button As New Button
button.Text = "Button"
Me.Controls.Add(button)
AddHandler button.Click, AddressOf button_click
End Sub
Private Sub button_click(ByVal sender As System.Object, ByVal e As System.EventArgs)
MsgBox ("It works!")
End Sub
If you add controls dynamically (from the code). You should add handlers like I showed you. If you added your button to your form (it is added with WithEvents keyword) then you should use Handles keyword (look at the form_load sub and how it ends 'Handles Me.Load'
Re: Binding action to button.