How to code a Button's Click Event?
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.te开发者_开发知识库xt but.location etc. but I how do I create the Click and the code behind it?
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
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.
精彩评论