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
2

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

0
For index As Integer = 1 To 8
   CType(Me.Controls("Button" & index.ToString().Trim()),Button).Text = "Hello"
Next

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.