Results 1 to 3 of 3

Thread: Binding action to button.

  1. #1

    Thread Starter
    New Member
    Join Date
    Feb 2011
    Posts
    3

    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.

  2. #2
    PowerPoster cicatrix's Avatar
    Join Date
    Dec 2009
    Location
    Moscow, Russia
    Posts
    3,654

    Re: Binding action to button.

    Change this like this:

    vb Code:
    1. Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    2.     Dim button As New Button
    3.     button.Text = "Button"
    4.     Me.Controls.Add(button)
    5.     AddHandler button.Click, AddressOf button_click
    6. End Sub
    7.  
    8. Private Sub button_click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    9.     MsgBox ("It works!")
    10. 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'

  3. #3

    Thread Starter
    New Member
    Join Date
    Feb 2011
    Posts
    3

    Re: Binding action to button.

    Thank you!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width