Im currently trying to make dynamically created buttons disappear when clicked.
I have a Private Sub that handles when the button is clicked and increases the players score. However, i do not know how to make the specific object disappear as all the Objects are called the same name as they are created by the same subroutine set on a timer ( a new button made every 2 seconds).
I have tried adding every new button created to an array but am still struggling to make the program figure out which button has been clicked.
Any help would be greatly appreciated.
One of the parameters on your button click event handler should be sender As Object, which is a reference to the button that was clicked. You just need to cast it to a button object, the set the Visible property to false. Here is an example:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim b As Button = CType(sender, Button)
b.Visible = False
End Sub
Further to #Icemanind's answer, you can actually do it in one line:
CType(sender, Button).Visible = False
This works without validation because you know that sender is of type Button.
If you have multiple buttons to handle, you can also add additional events to the handler so you don't end up with a zillion individual handlers:
Protected Sub Button_Click(s As Object, e As EventArgs) _
Handles _
Button1.Click, Button2.Click, Button3.Click
CType(s, Button).Visible = False
End Sub
Yet another option is to add the same handler to multiple buttons rather than adding buttons to the handler:
In Form instantiation (Sub New()):
AddHandler Button1.Click, AddressOf Button_Click
AddHandler Button2.Click, AddressOf Button_Click
AddHandler Button3.Click, AddressOf Button_Click
In Form class code:
Protected Sub Button_Click(s As Object, e As EventArgs)
CType(s, Button).Visible = False
End Sub
This last method works well with dynamic controls because you can add the handlers on the fly:
Dim button As Button
For i As Integer = 0 To 9
button = New Button With {.Name = $"Button{i}", .Text = $"Button{i}", .Left = 42, .Top = 50 + (i * 30)}
Me.Controls.Add(button)
AddHandler button.Click, AddressOf Button_Click
Next i
Related
how can I control some controls that will be created automatically during the execution of the application?
My add control
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim NewCheckbox As CheckBox
For i As Integer = 2 To 14
NewCheckbox = New CheckBox
NewCheckbox.Size = New Drawing.Size(15, 14)
NewCheckbox.Location = New Point(98, 40)
NewCheckbox.Name = "cbcard" & i
Me.Controls.Add(NewCheckbox)
next
My checkbox control add, I gave an example to create a checkbox control, but it should be valid for any form of control, be it textbox or button.
how can i detect these controls that are not created but will be created during execution?
checkbox name will be cbcard1, cbcard2, cbcard3 up to 14.
but I want this to be in the form of a handler, or it should probably work with a timer.
Private Sub Checkbox_Changed(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Checkbox.Changed
If Checkbox.checked = true
MsgBox("")
End If
End Sub
You can subscribe to the event using the AddHandler syntax.
For i As Integer = 2 To 14
NewCheckbox = New CheckBox
NewCheckbox.Size = New Drawing.Size(15, 14)
NewCheckbox.Location = New Point(98, 40)
NewCheckbox.Name = "cbcard" & i
Me.Controls.Add(NewCheckbox)
'subscribe to the CheckChanged event (as an example)
AddHandler NewCheckbox.CheckChanged, AddressOf Checkbox_Changed
Next
'all dynamically created checkboxes were subscribed to this event
Private Sub Checkbox_Changed(ByVal sender As System.Object, ByVal e As System.EventArgs)
'sender is the specific checkbox that was changed out of all subscribed checkboxes
Dim checkBox = DirectCast(sender, CheckBox)
If checkbox.checked = true Then MsgBox(checkBox.Name)
End Sub
Im making a class that will show a form with some text and a OK button. But I can't seem to find how to handle clicking the OK button. Here is the code that im having problems with:
Private Sub ok_click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles myForm.okButton.Click
'code
End Sub
Runtime form is called myForm
Runtime button is called okButton
How I can fix this?
You'd use AddHandler:
' ... run-time control is created ...
Dim btn As New Button
btn.Text = "Hello World!"
AddHandler btn.Click, AddressOf ok_click
In your existing handler, you do NOT use the "Handles" keyword on the end. If you need a reference to the button, use the "sender" parameter:
Private Sub ok_click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim btn As Button = DirectCast(sender, Button)
' ... do something with "btn" ...
btn.Enabled = False
End Sub
I am creating some tabs and I need two things to work that I can't get to work. I need to AddHandler for a Textbox.Keypress event AND a Button.Click event. I can make these things work outside of the tabcontrol but not in.
In the example below my text box and buttons have same name from on tab to the another, I thought that might be my problem but even changing names between tabs does not work. I assume I need to be more specific in the AddHandler part to give the tab name as well as control. There is a logic in my real code to allow me to give unique names to each tab panel and controls, but i can't get the simple part to work.
I left some of the things I tried commented, but I tried LOTS and LOTS of other things.
Public Class Form1
Public Sub addTab(tabPageName As String)
Dim tabpage As New TabPage
tabpage.Text = tabPageName
tabpage.Name = "tabPage1" 'real code has logic to make sure names are unique
Dim label1 As New Label
Dim txtCreator As New TextBox
Dim combox1 As New ComboBox
Dim tabPageButton2 As New Button
tabPageButton2.Parent = tabpage
label1.Parent = tabpage
txtCreator.Parent = tabpage
combox1.Parent = tabpage
label1.Location = New Point(10, 10)
txtCreator.Location = New Point(150, 10)
combox1.Location = New Point(300, 10)
tabPageButton2.Location = New Point(20, 40)
label1.Text = "Creator"
txtCreator.Name = "txtCreator"
'fill the comboboxes...this will come from a database but testing now.
combox1.Items.Add("one")
combox1.Items.Add("two")
combox1.Items.Add("three") 'ok that works so should work from DB no problem.
tabRoleClass.TabPages.Add(tabpage)
End Sub
Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
addTab("First Tab")
AddHandler Controls("tabRoleClass.tabPage1.tabPageButton2").Click, AddressOf tabPageButton_click
'AddHandler CType(Controls("tabPageButton"), Button).Click, AddressOf tabPageButton_click
'AddHandler Controls("tabPageButton").Click, AddressOf tabPageButton_click
AddHandler CType(Controls("txtCreator"), TextBox).KeyPress, AddressOf txtcreator_keypress 'the Keypress to call lookup
End Sub
Private Sub tabPageButton_click(sender As System.Object, e As System.EventArgs) 'Handles tabPageButton.click
MessageBox.Show(tabRoleClass.SelectedTab.Name.ToString)
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
addTab("Second Tab")
tabRoleClass.SelectedIndex = tabRoleClass.TabCount - 1
'AddHandler Controls("tabRoleClass.tabPage1.tabPageButton2").Click, AddressOf tabPageButton_click
'AddHandler CType(Controls("tabPageButton"), Button).Click, AddressOf tabPageButton_click
'AddHandler Controls("tabPageButton").Click, AddressOf tabPageButton_click
'AddHandler CType(Controls("txtCreator"), TextBox).KeyPress, AddressOf txtcreator_keypress 'the Keypress to call lookup
End Sub
Private Sub txtcreator_keypress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) 'Handles txtCreator.KeyPress
MessageBox.Show("keypress worked on " & tabRoleClass.SelectedTab.Name.ToString)
End Sub
End Class
This is a very confusing question and your code could really do with some cleaning, but you need to add the AddHandler code to the addTab subroutine as pointed out by #Plutonix:
Public Sub addTab(tabPageName As String)
Dim tabpage As New TabPage
Dim tabPageButton As New Button
Dim txtCreator As New TextBox
/.../
AddHandler tabPageButton.Click, AddressOf tabPageButton_click
AddHandler txtCreator.KeyDown, AddressOf txtcreator_keypress
tabRoleClass.TabPages.Add(tabpage)
End Sub
Private Sub tabPageButton_click()
MessageBox.Show(tabRoleClass.SelectedTab.Name.ToString)
End Sub
Private Sub txtcreator_keypress()
MessageBox.Show("keypress worked on " & tabRoleClass.SelectedTab.Name.ToString)
End Sub
Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
addTab("First Tab")
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
addTab("Second Tab")
tabRoleClass.SelectedIndex = tabRoleClass.TabCount - 1
End Sub
AddHandler works by adding event handlers to your controls. This means that each time an event is raised during this runtime, the new event handler will handle the event; everytime you click your tabPageButton the associated event tabPageButton_click will handle it.
Therefore, you will only need to add the handler once, preferably upon the creation of the control. There is absolutely no need to create them upon every single keypress, for example. You should look up event handlers on MSDN.
Hope this helps!
Sorry if the code was confusing, I cut up my actual code to make a "sample" and I can see the confusion. Now of course I AM confused, I originally had the AddHandler INSIDE the addTab sub that creates the tab and it didn't work there, I incorrectly assumed the reason was that the control was not yet created so I moved it out. Moving it back in this sub this morning worked perfectly, I don't know what I did wrong but its working GREAT by moving it up to where it belongs, thanks A LOT, I worked on this for 2 days trying and googling things. Next time I will post real code instead of a sample to be less confusing and also remove my commented attemps (I thought those would help show what I was trying but I think it didn't)
can someone help me, how to create button/control like that in VB.NET .. that i mean, how to create/use style like that when i pointing the cursor or click the control, the style like transparent. that style different from button style.. please help me.. i have search everywhere but nothing. thank's before
Here is the image:
If you want to accomplish what you are looking for take a look at this example it might help you work out any issues you have:
Sub Main()
Dim myButton As Button = New Button()
myButton.Text = "Hello World"
myButton.BackColor = Color.Blue
myButton.FlatAppearance.BorderColor = Color.LightBlue
myButton.FlatAppearance.BorderSize = 2
AddHandler myButton.Click, AddressOf Me.OnMyButtonClick
AddHandler myButton.MouseHover, AddressOf Me.OnMyButtonEnter
AddHandler myButton.MouseLeave, AddressOf Me.OnMyButtonLeave
Panel1.Controls.Add(myButton)
End Sub
As you can see I have created a new button, and can modify all of the attributes of the button that you were looking for: Back color, Border color, and Border width, even the content like text or the image. Now you will want to create the events that will perform the actions that you are looking to accomplish:
Private Sub OnMyButtonClick(sender As Object, e As EventArgs)
Dim currentButton As Button = CType(sender, Button)
currentButton.Text = "I have been clicked!"
currentButton.BackColor = Color.LightBlue
currentButton.FlatAppearance.BorderColor = Color.Blue
currentButton.FlatAppearance.BorderSize = 1
End Sub
Private Sub OnMyButtonEnter(sender As Object, e As EventArgs)
Dim currentButton As Button = CType(sender, Button)
currentButton.BackColor = Color.LightGreen
End Sub
Private Sub OnMyButtonLeave(sender As Object, e As EventArgs)
Dim currentButton As Button = CType(sender, Button)
currentButton.BackColor = Color.Blue
End Sub
As you can see we have defined the 3 events you were looking to capture Mouse Click, Mouse Hover, and Mouse Leave, and within each one we can modify the button as we please. From here you can make a global parameter that monitors the color of the button, or you can monitor the state, from there you can know within each event what you want to do. Take for instance the Mouse Leave event.
You showed that you want to create a border, but have a white background as you can see, all you would have to do is just:
myButton.BackColor = Color.White
myButton.FlatAppearance.BorderColor = Color.LightBlue
That's easy enough, but there is one very important part that you need to know. If you want your button to actually perform events, ones that you created, you have to attach them to the button. Lets that a look at this:
AddHandler myButton.Click, AddressOf Me.OnMyButtonClick
AddHandler myButton.MouseHover, AddressOf Me.OnMyButtonEnter
AddHandler myButton.MouseLeave, AddressOf Me.OnMyButtonLeave
As you can see from the above code you instruct the program what to do when a certain event occurs such as Mouse Click. An important part to do with event handlers is to attach them after creation so that they will perform the actions right away. That is why I placed the attachment of the event handler in the Main() before I added the button to Panel1.
Let's try with this:
Import your image to resource.
You will need 3 different image: Normal, Hover and Clicked. Change this to your image name: CustomButtonN, CustomButtonH and CustomButtonC.
Add a Class with any name. Then add the code below:
Inherits Windows.Forms.Button 'To make this class as button command
Public Sub New()
Me.FlatStyle = Windows.Forms.FlatStyle.Flat 'Make it flat
Me.FlatAppearance.BorderSize = 0 'With borderless
Me.FlatAppearance.MouseDownBackColor = Color.Transparent 'You know this
Me.FlatAppearance.MouseOverBackColor = Color.Transparent 'And this
Me.BackColor = Color.Transparent 'Transparent key
Me.ForeColor = Color.Black 'Text color
Me.Width = 32 'Button width
Me.Height = 32 'Button height
Me.BackgroundImage = My.Resources.CustomButtonN 'Normal
Me.BackgroundImageLayout = ImageLayout.Stretch 'To stretch the image
End Sub
Private Sub CustomButton_MouseDown(ByVal sender As Object, _
ByVal e As MouseEventArgs) Handles Me.MouseDown
Me.BackgroundImage = My.Resources.CustomButtonC 'Click event
End Sub
Private Sub CustomButton_MouseHover(ByVal sender As Object, _
ByVal e As EventArgs) Handles Me.MouseHover
Me.BackgroundImage = My.Resources.MiniButtonH 'Hover event
End Sub
Private Sub CustomButton_MouseLeave(ByVal sender As Object, _
ByVal e As EventArgs) Handles Me.MouseLeave
Me.BackgroundImage = My.Resources.CustomButtonN 'Leave even
End Sub
Private Sub CustomButton_MouseUp(ByVal sender As Object, _
ByVal e As MouseEventArgs) Handles Me.MouseUp
Me.BackgroundImage = My.Resources.CustomButtonH 'Click release
End Sub
Note: You must compile the project after adding a class or editing:
Press F5 to start it and then wait for 3 sec, then stop it.
Finally see your Toolbox panel click your button name then put to your form.
As a new user to VB, I am struggling to see why this code works in one project but not in another. This code works fine if I create a new project and 2 new forms but when I place in my project, it doesn't fire at all on either left or right click.
I have tried a try/catch statement, but no errors are being reported. How do I go about troubleshooting this to find out the error. I have tried to rem out code and run after each comment but still the same. I have even tried removing all other code on the form leaving just the 2 subs but no joy. Any help would be greatly appreciated.
frmMain
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'StorageDataSet1.Customers' table. You can move, or remove it, as needed.
Me.CustomersTableAdapter.Fill(Me.StorageDataSet1.Customers)
'TODO: This line of code loads data into the 'StorageDataSet.User' table. You can move, or remove it, as needed.
Me.UserTableAdapter.Fill(Me.StorageDataSet.User)
'Dim frmDepartmentsLive As New frmDepartment
'frmDepartmentsLive.Owner = Me
'frmDepartmentsLive.ShowDialog()
lblDate.Text = Now
Timer1.Start()
rdoCustomer.Enabled = False
rdoCustomer.Checked = True
rdoDepartment.Enabled = False
rdoDepartment.Checked = False
For Each ctrl In Me.Controls
If TypeOf ctrl Is Button Then
AddHandler CType(ctrl, Button).MouseDown, AddressOf btn_MouseDown
End If
Next
End Sub
Private Sub btn_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs)
If (e.Button = MouseButtons.Right) Then
Dim btn = CType(sender, Button)
frmRacks.buttonName = btn.Name.Replace("btn", "")
frmRacks.Show()
ElseIf (e.Button = MouseButtons.Left) Then
MessageBox.Show("To be coded")
End If
End Sub
frmRacks
Public Class frmRacks
Public buttonName As String
Private Sub racksfrm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
lblRacks.Text = buttonName
End Sub
Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
Me.Close()
End Sub
End Class
Since the controls are on a panel, they are members of that panel's controls array, not the form's. This -- and other things -- are apparent if you look thru the form's designer (on solution explorer, click Show All, then open formXXX.designer.vb). DOnt change anything, but it shows how controls are created and added. So...
For Each ctrl In thepanelName.Controls
If TypeOf ctrl Is Button Then
AddHandler CType(ctrl, Button).MouseDown, AddressOf btn_MouseDown
End If
Next
If it is ONLY those buttons on the panel you can short cut it:
For Each btn As Button In thepanelName.Controls
AddHandler CType(ctrl, Button).MouseDown, AddressOf btn_MouseDown
Next