|
-
Sep 2nd, 2021, 09:15 AM
#1
Thread Starter
Addicted Member
Get button name on click
Hello all, I am creating a bunch of buttons on a form at runtime, which seems to all work great. The issue that is driving me nuts... I cannot seem to get the right button name when clicking one of them on the form. Each button location, name etc is coming from a text file. I have no problems with adding the buttons, naming them, applying tooltips etc. Only what is going on after the fact is where my trouble is.
Code:
Sub CreateBtns()
Dim rawData As String
Dim FILE_NAME As String = "C:\temp\test.txt"
Dim data()
Dim objReader As New System.IO.StreamReader(FILE_NAME)
Top = 0
Left = 0
Do While objReader.Peek() <> -1
rawData = objReader.ReadLine()
data = Split(rawData, ",")
Dim dynamicButton As New Button
dynamicButton.Height = 5
dynamicButton.Width = 5
dynamicButton.Location = New Point(CInt(data(2)), CInt(data(3)))
dynamicButton.FlatStyle = FlatStyle.Flat
dynamicButton.BackColor = Color.Magenta
dynamicButton.ForeColor = Color.Magenta
dynamicButton.BackColor = Color.Transparent
dynamicButton.ForeColor = Color.FromArgb(10, Color.Transparent)
dynamicButton.Name = data(0)
dynamicButton.FlatAppearance.BorderColor = Color.Aqua
dynamicButton.Font = New Font("Georgia", 6)
AddHandler dynamicButton.Click, AddressOf DynamicButton_Click
Controls.Add(dynamicButton)
Dim myToolTipText = data(0) & " / " & data(1)
ToolTip1.SetToolTip(dynamicButton, myToolTipText)
Loop
End Sub
Private Sub DynamicButton_Click(ByVal sender As Object, e As MouseEventArgs)
For Each cntrl In Me.Controls
If TypeOf cntrl Is Button Then
Dim btn As Button = DirectCast(cntrl, Button)
'''>>> Getting name is always wrong (btn.name)
Exit Sub
End If
Next
End Sub
-
Sep 2nd, 2021, 09:31 AM
#2
Re: Get button name on click
Code:
Private Sub DynamicButton_Click(ByVal sender As Object, e As MouseEventArgs)
For Each cntrl In Me.Controls
If TypeOf cntrl Is Button Then
Dim btn As Button = DirectCast(cntrl, Button)
'''>>> Getting name is always wrong (btn.name)
Exit Sub
End If
Next
End Sub
You want the name of the button clicked? Then why arent' you looking at the sender object? that's the thing that was clicked...
Code:
Private Sub DynamicButton_Click(ByVal sender As Object, e As MouseEventArgs)
MessageBox.Show(DirectCast(sender, Button).Name)
End Sub
your code is currently looping through all the controls on the form, finding the first button it comes to and giving you the name of THAT button... not the one clicked...
-tg
-
Sep 2nd, 2021, 09:36 AM
#3
Thread Starter
Addicted Member
Re: Get button name on click
techgnome..... thank you, that did what I needed. I knew I was doing something stupid there. Thanks a bunch!
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|