Aysha Almaqtari
Aysha Almaqtari

Reputation: 241

add event to button in vb.net

Public Class Form1
    Dim i As Integer = 0
    Dim txt As New TextBox()
    Dim btn As New Button()

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        btn.Name = "btnMove"
        btn.Size = New Size(60, 20)
        btn.Location = New Point(220, 20)
        btn.Text = "move"
        btn.TextAlign = ContentAlignment.MiddleCenter
        Me.Controls.Add(btn)
        Me.BringToFront()
    End Sub

    Private Sub btnMove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn.Click

    End Sub
End Class

this is my code and i want to add an event to btn Button i hope that i make my problem clear and sorry for my bad English

Upvotes: 0

Views: 3421

Answers (2)

Hans Passant
Hans Passant

Reputation: 942518

   Private Sub btnMove_Click(...) Handles btn.Click

The Handles keyword requires you to declare the control that generates the event with the WithEvents keyword. Fix:

   Dim WithEvents btn As New Button()

The alternative is to subscribe the event explicitly with the AddHandler keyword. In which case you omit the Handles keyword and write it like this instead:

Private Sub Form1_Load(...) Handles MyBase.Load
   '' etc..
   AddHandler btn.Click, AddressOf btnMove_click
End Sub

Using the designer to add these controls is certainly the best way, it avoids little mistakes like this.

Upvotes: 1

senthilkumar2185
senthilkumar2185

Reputation: 2578

Public Class Form2
    Dim btn As New Button
    Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        btn.Name = "btnMove"
        btn.Size = New Size(60, 20)
        btn.Location = New Point(220, 30)
        btn.Text = "Move"
        btn.TextAlign = ContentAlignment.MiddleCenter
        Me.Controls.Add(btn)
        Me.BringToFront()
        AddHandler btn.Click, AddressOf btnMove_click
    End Sub
    Private Sub btnMove_click(ByVal sender As Object, ByVal e As System.EventArgs)
        MsgBox("welcome to salfkjsadlkf")
    End Sub
End Class

Upvotes: 1

Related Questions