Can a control name be referred to by a variable?

HDokes

Active member
Joined
Jun 28, 2003
Messages
32
I have 99 buttons on a page of which I need to be able to perform a sweeping change of their .text and .tag properties. For convenience I have named the buttons "btnButton1" through "btnButton99". There are other buttons on the form I do not wish to change. I figure the easiest way to do this is through a routine as follows:

dim x as int16
dim ButtonName as string

for x = 1 to 99
ButtonName = "form.btnbutton" & ltrim(str(x)) set the specific button
ButtonName.text = "sometext"
ButtonName.tag = "sometag"
next x

Is something like this feasable in VB .NET? I realize that the variable at this time is a string and would have to have its type changed to a control however Im not sure if this can be done so that it is the content of the variable which is referenced as the control.
 
Code:
    Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
        Dim x As Control
        For Each x In Me.Controls
            If TypeOf x Is Button Then
                x.Text = "new text"
            End If
        Next
    End Sub

if you wanted to make them all have a different name, youd have to make a loop and a string as the button name or something. like this :
Code:
    Private Sub Button7_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button7.Click
        Dim arrButtons As New ArrayList()
        Dim i As Integer
        Dim strButton As String = "Button"
        Dim btn As Control
        For i = 0 To 6
            arrButtons.Add(strButton & i)
            For Each btn In Me.Controls
                If btn.Name = arrButtons(i) Then
                    btn.Text = "item: " & i
                End If
            Next
        Next
    End Sub
 
Hi there,

Thanks very much for the examples..... I applied the 2nd example and it is working like a charm!
 
Back
Top