Noob2Java
Noob2Java

Reputation: 223

VB.NET get control name from button created at run time

I have this code to create 3 buttons at run time, which seems to be working ok.

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        Dim rawData As String
        Dim FILE_NAME As String = "C:\temp\test.txt"
        Dim data() As String

        Dim objReader As New System.IO.StreamReader(FILE_NAME)

        Do While objReader.Peek() <> -1
            rawData = objReader.ReadLine() ' & vbNewLine
            data = Split(rawData, ",")
            'data 0 = X loc, data 1 = Y loc, data 2 = Part Num, data 3 = Reference Des

            Dim dynamicButton As New Button
            dynamicButton.Location = New Point(data(0), data(1))
            dynamicButton.Height = 20
            dynamicButton.Width = 20
            dynamicButton.FlatStyle = FlatStyle.Flat
            dynamicButton.BackColor = Color.Transparent
            dynamicButton.ForeColor = Color.FromArgb(10, Color.Transparent)
            'dynamicButton.Text = "+"
            dynamicButton.Name = data(2)
            dynamicButton.FlatAppearance.BorderColor = Color.White
            'dynamicButton.Font = New Font("Georgia", 6)
            AddHandler dynamicButton.Click, AddressOf DynamicButton_Click
            Controls.Add(dynamicButton)
            Dim myToolTipText = data(3)
            ToolTip1.SetToolTip(dynamicButton, myToolTipText)
        Loop

    End Sub

I want to get the control name that was created when I click a button, but I cannot seem to get what I need. I have been doing this on the dynamicButton_click event.

 Private Sub DynamicButton_Click(ByVal sender As Object, ByVal e As System.EventArgs)

        For Each cntrl In Me.Controls
            If TypeOf cntrl Is Button Then

                MsgBox("")
                Exit Sub
            End If
        Next
    End Sub

Upvotes: 0

Views: 656

Answers (2)

Pete -S-
Pete -S-

Reputation: 562

You attached an event handler to the dynamic button and that is hitting?

Couple ways you can do this:

This will give you the button you just clicked without needing to loop, the sender is the button. You need to cast it from the object to button:

MessageBox.Show(DirectCast(sender, Button).Name)

Otherwise, inside your loop, cast cntrl (the generic Control object) to the specific Button control object and then get the name.

Dim btn as Button = DirectCast(cntrl, Button)
MessageBox.Show(btn.Name)

Upvotes: 0

Idle_Mind
Idle_Mind

Reputation: 39122

All you need to do is cast the sender variable to button. It will tell you which control was the source of the event:

Private Sub DynamicButton_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    Dim btn As Button = DirectCast(sender, Button)
    MessageBox.Show("You clicked: " & btn.Name)
End Sub

Upvotes: 1

Related Questions