views:

42

answers:

2

I'm using winform and fb.net. Can someone provide me with an example of how to create a buttons click event? I have dim but as windows.forms.button but.name but.text but.location etc. but I how do I create the Click and the code behind it?

+1  A: 

You can use:

AddHandler button.Click, AddressOf HandlerMethod

In VB you can specify that a method handles a particular event for a particular control, if you're not creating it on the fly - you only need AddHandler when you're (say) dynamically populating a form with a set of buttons.

Here's a short but complete example:

Imports System.Windows.Forms

Public Class Test

    <STAThread>
    Public Shared Sub Main()
        Dim f As New Form()
        Dim b As New Button()
        b.Text = "Click me!"
        AddHandler b.Click, AddressOf ClickHandler
        f.Controls.Add(b)
        Application.Run(f)
    End Sub

    Private Shared Sub ClickHandler(sender As Object, e As EventArgs)
        Dim b As Button = DirectCast(sender, Button)
        b.Text = "Clicked"
    End Sub

End Class

EDIT: To close the form, the simplest way is to get the form of the originating control:

    Private Shared Sub ClickHandler(sender As Object, e As EventArgs)
        Dim c As Control = DirectCast(sender, Control)
        Dim f as Form = c.FindForm()
        f.Close()
    End Sub
Jon Skeet
This is great. Just what I was looking for. But still one missing piece for me. How would I close the form on which the button is placed from ClickHandler? In your example that would be f
bochur1
@bochur1: In what way is "this site not set up for this"? People post code all the time. But don't post it in a comment - edit it into your original code.
Jon Skeet
Ignore my msg about it not working. It's working great. Thanks so much!
bochur1
A: 

In the winforms designer, add a button then double-click it. This will create the event (based on the button's name) and take you to the event's code.

SteveCav
Just for clarity, it's not creating the *event* - it's creating the *event handler*. The button itself publishes the event, whether anyone subscribes to it or not.
Jon Skeet