0

In visual basic I want to be able to access a button's name using the number stored in a variable. For example if I have 24 buttons that are all named 'Button' with the numbers 1, 2, 3... 22, 23, 24 after it. If I want to then change the text in the first eight buttons how would I do that.

Here's my example to help show what I mean:

    For i = 1 to 8
        Button(i).text = "Hello"
    Next
Jackster
  • 17
  • 4

3 Answers3

1

The proposed solutions so far will fail if the Buttons are not directly contained by the Form itself. What if they are in a different container? You could simple change "Me" to "Panel1", for instance, but that doesn't help if the Buttons are spread across multiple containers.

To make it work, regardless of the Buttons locations, use the Controls.Find() method with the "searchAllChildren" option:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim ctlName As String
    Dim matches() As Control
    For i As Integer = 1 To 8
        ctlName = "Button" & i
        matches = Me.Controls.Find(ctlName, True)
        If matches.Length > 0 AndAlso TypeOf matches(0) Is Button Then
            Dim btn As Button = DirectCast(matches(0), Button)
            btn.Text = "Hello #" & i
        End If
    Next
End Sub
Idle_Mind
  • 38,363
  • 3
  • 29
  • 40
0

Use LINQ and you're good to go:

Dim yourButtonArray = yourForm.Controls.OfType(of Button).ToArray
' takes all controls whose Type is Button
For each button in yourButtonArray.Take(8)
    button.Text = "Hello"
Next

Or

Dim yourButtonArray = yourForm.Controls.Cast(of Control).Where(
    Function(b) b.Name.StartsWith("Button")
    ).ToArray
' takes all controls whose name starts with "Button" regardless of its type
For each button in yourButtonArray.Take(8)
    button.Text = "Hello"
Next

In any case, .Take(8) will iterate on the first 8 items stored inside yourButtonArray

Nimantha
  • 6,405
  • 6
  • 28
  • 69
VBobCat
  • 2,527
  • 4
  • 29
  • 56
0
For index As Integer = 1 To 8
   CType(Me.Controls("Button" & index.ToString().Trim()),Button).Text = "Hello"
Next
F0r3v3r-A-N00b
  • 2,903
  • 4
  • 26
  • 36