How to code a Button's Click Event? - vb.net

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?

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.

Related

VB: adding object to a tabcontrol tab which doiesnt exist at this time

i want to add a tabcontrol tab by pressing on a button:
Dim inp As String
inp = TextBox6.Text
TabControl2.TabPages.Add(inp)
and when i open this tabpage some object should be already created like a button and a textbox, etc.
i havent found any type of onload events for a tabpage so i tried to add this with:
TabPage8.Controls.Add(New Button())
tabpage8 would be the name of the new created tabpage but like vb already told me, i cant add objects to a tabpage which doesnt exist at that time.
is there any way i can do that or have you any other ideas which could help me?
Your code is close. Try the following:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TabControl2.TabPages.Add("Test")
Dim tp = TabControl2.TabPages(TabControl2.TabPages.Count - 1)
Dim b = New Button()
b.Text = "My Button"
tp.Controls.Add(b)
AddHandler b.Click, AddressOf MyButton_Click
End Sub
Private Sub MyButton_Click(sender As Object, e As EventArgs)
MessageBox.Show("MyButton clicked")
End Sub
This code grabs the last page added and adds a button to it. It also configures the button as needed and adds an event handler.

loop button to check which was clicked

In VB.net form, I have 20 buttons. They are named from btnLoc1 ~ btnLoc20. I do not want to code each button click event.
How to loop through each button to check which was clicked?
Do I need to implement timer tick to listen for button click event?
You can create a single event handler for all the Buttons. Select all the buttons in the designer, open the Properties window, click the Events button and then double-click the Click event. That will generate a Click event handler, just like when you double-click a Button in the designer, except this one will have multiple items in the Handles clause. You can then use the sender parameter to acces the Button that was clicked, e.g.
Private Sub Buttons_Click(sender As Object, e As EventArgs) Handles Button1.Click,
Button2.Click,
Button3.Click
Dim btn = DirectCast(sender, Button)
'Use btn here.
End Sub
The question then is, what do you want to do with that Button? If you want to do something different for each Button then you really should be creating separate event handlers. Alternatively, you might have a list of data and you want to use the item in that list that corresponds to the Button that was clicked. There are numerous ways to do that. One is to put the data in the Tag property of the Button itself and retrieve it from there. Another is to use concurrent indexes, e.g.
Dim buttons = Controls.OfType(Of Button)().ToArray()
Dim data = {"First", "Second", "Third"}
MessageBox.Show(data(buttons.IndexOf(btn)))
Obviously you need to ensure that the Button array and the data array do line up.
For being noticed if button was clicked - eventhandler is best choice.
But you can create only one eventhandler for all buttons
Private Sub Button_Click(sender As Object, e As EventArgs)
Dim button As Button = DirectCast(sender, Button)
MessageBox($"Button '{button.Name}' was clicked")
End Sub
Then in constructor
Public Sub New()
InitializeComponennts()
AddHandler Button1.Click, AddressOf Me.Button_Click
AddHandler Button2.Click, AddressOf Me.Button_Click
AddHandler Button3.Click, AddressOf Me.Button_Click
' and so on
End Sub
If you want to get information about how much each button was clicked, simply create dictionary and add click amount in one eventhandler
Private ButtonsClickAmount As New Dictionary(Of String, Integer)()
Private Sub Button_Click(sender As Object, e As EventArgs)
Dim button As Button = DirectCast(sender, Button)
If ButtonsClickAmount.ContainKey(button.Name) = True Then
ButtonsClickAmount(button.Name) += 1
Else
ButtonsClickAmount.Add(button.Name, 1)
End If
End Sub

How to notice any change on a form

I have a form with many different radiobuttons, checkboxes and textboxes. Depending on their values I start my calculations. The results are shown on the same form and panel. If any of my controls (checkboxes, ...) changes, I want to immediatly update the results without a need to press any update-button.
I could define a statsChanged-sub for every single control on the form but there are so many. Isn't there a way/event of the form starting whenever a control is changed? It should be something like controlOnFormChanged. How can I get a sub that starts whenever a any control on the form changed?
Thank you in advance!
You could wire up the events that correspond to the desired change manually to a specific event handler:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Iterate through all controls and handle them according to their type
For Each c As Control In Me.Controls
If TypeOf (c) Is CheckBox Then
AddHandler CType(c, CheckBox).CheckedChanged, AddressOf SomethingChanged
ElseIf TypeOf (c) Is RadioButton Then
AddHandler CType(c, RadioButton).CheckedChanged, AddressOf SomethingChanged
ElseIf TypeOf (c) Is TextBox Then
AddHandler CType(c, TextBox).TextChanged, AddressOf SomethingChanged
ElseIf ......
......
End If
Next
End Sub
Private Sub SomethingChanged(sender As Object, e As EventArgs)
'Whatever it is you do
End Sub
End Class
Whenever one of the events on a control fires the sub SomethingChanged is called, allowing you to update your results.
Please be aware: If you have controls in subcontainers like Panels you need to modify this method and iteratively get all controls in all containers.
Here is, for example, a solution to this:
http://kon-phum.com/tutors/pascal/programming_cs_getcontrolsonform.html
Public Shared Function GetAllControls(ctrls As IList) As List(Of Control)
Dim RetCtrls As New List(Of Control)()
For Each ctl As Control In ctrls
RetCtrls.Add(ctl)
Dim SubCtrls As List(Of Control) = GetAllControls(ctl.Controls)
RetCtrls.AddRange(SubCtrls)
Next
Return RetCtrls
End Function

Save a form on generated button click

I am trying to insert form fields on a dynamically generated button event. The form is also generated dynamically. However, the submit event handler is not triggering. Here is my code:
Protected Sub BindForm()
'select query for fetching record from database
'dynamically generated button
Dim btnSubmit As New Button()
btnSubmit.ID = "btnSubmit"
btnSubmit.Text = "Save"
AddHandler btnSubmit.Click, AddressOf Me.btnSubmit_click
form1.Controls.Add(btnSubmit)
End Sub
' Dynamic button click event
Protected Sub btnSubmit_click(ByVal sender As Object, ByVal e As EventArgs)
Dim Query As String = "INSERT INTO table column values some_value"
End Sub
You need to create, add, and hookup the event in the OnInit method of the Page. After doing that it will bind the control on post back and fire the event.
Protected Overrides Sub OnInit(e As EventArgs)
Dim btnSubmit As New Button()
btnSubmit.ID = "btnSubmit"
btnSubmit.Text = "Save"
AddHandler btnSubmit.Click, AddressOf Me.btnSubmit_click
form1.Controls.Add(btnSubmit)
End Sub 'OnInit

Raising events from a List(Of T) in VB.NET

I've ported a large VB6 to VB.NET project and while it will compile correctly, I've had to comment out most of the event handlers as to get around there being no array collection for winform objects and so putting the various objects that were in at the collection array into a List object.
For example, in VB6 you could have an array of Buttons. In my code I've got
Dim WithEvents cmdButtons As New List(Of Button)
(and in the Load event, the List is propagated)
Obviously, you can't fire an event on a container. Is there though a way to fire the events from the contents of the container (which will have different names)?
In the Button creation code, the event name is there, but from what I understand the handler won't intercept as the Handles part of the code is not there (commented out).
I'm not exactly sure what you're after, but if you want to be able to add event handlers to some buttons in a container and also have those buttons referenced in a List, you can do something like
Public Class Form1
Dim myButtons As List(Of Button)
Private Sub AddButtonsToList(targetContainer As Control)
myButtons = New List(Of Button)
For Each c In targetContainer.Controls
If TypeOf c Is Button Then
Dim bn = DirectCast(c, Button)
AddHandler bn.Click, AddressOf SomeButton_Click
myButtons.Add(bn)
End If
Next
End Sub
Private Sub SomeButton_Click(sender As Object, e As EventArgs)
Dim bn = DirectCast(sender, Button)
MsgBox("You clicked " & bn.Name)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' GroupBox1 has some Buttons in it
AddButtonsToList(GroupBox1)
End Sub
End Class