3

I remember in vb6 you were able to create the array of textboxes.

Textbox1(0), Textbox1(1) ..... ,

But in vb.net you can't create array ? So if you have code like this . Is it possible set it into for loop ?

        TextBox1.Text = ""
        TextBox2.Text = ""
        TextBox3.Text = ""
        TextBox4.Text = ""
        TextBox5.Text = ""
        TextBox6.Text = ""
        TextBox7.Text = ""
        TextBox8.Text = ""
        TextBox9.Text = ""
        TextBox10.Text = ""
        TextBox11.Text = ""
        TextBox12.Text = ""
        TextBox13.Text = ""
        TextBox14.Text = ""
        TextBox15.Text = ""
Anel Hodzic
  • 209
  • 2
  • 4
  • 13
  • 1
    You _could_ try searching next time. http://stackoverflow.com/questions/13504280/for-each-textbox-loop – Justin Ryan Jun 02 '15 at 19:24
  • Also [here](http://stackoverflow.com/questions/5299435/how-to-create-control-arrays-in-vb-net), [here](http://stackoverflow.com/questions/199521/vb-net-iterating-through-controls-in-a-container-object), etc... – Justin Ryan Jun 02 '15 at 19:26

3 Answers3

9

If the TextBox controls are just on the main form, then you can loop through them:

For Each tb As TextBox In Me.Controls.OfType(Of TextBox)()
  tb.Text = String.Empty
Next

If they are in a panel, then replace the Me keyword with the name of the panel.

LarsTech
  • 80,625
  • 14
  • 153
  • 225
2

You can create a List and loop through it:

Dim boxes As New List(Of TextBox)() From { _
    TextBox1, _
    TextBox2 _
}
boxes.Add(TextBox3)

For Each tb As TextBox In boxes
    tb.Text = ""
Next

If you have a Form with TextBox controls down inside other controls such as a Panel, or GroupBox, you can try to use a recursive function like this to get them all. (This is basically a C# to VB conversion of the answer here)

Private Function GetTextBoxes(root As Control) As IEnumerable(Of TextBox)
    Dim container = TryCast(root, ContainerControl)
    If container IsNot Nothing Then
        For Each c As Control In container.Controls
            For Each i As Control In GetTextBoxes(c)
                Yield i
            Next
        Next
    End If
End Function

To create a list from your main form:

Dim allBoxes As List(Of TextBox) = GetTextBoxes(Me).ToList()
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
jwatts1980
  • 7,254
  • 2
  • 28
  • 44
2

For reference, you CAN create an Array of TextBox objects, in the following manner:

Dim tbArray() As TextBox = New TextBox() {TextBox1, TextBox2, TextBox3}

Or, declare the array and loop through the TextBox controls to add them to it. However, the List(Of TextBox) approach will work just fine if you need to keep a collection of them, or simply looping through the TextBox controls on the form if you just need to set the properties in one sub or function.

RianBattle
  • 898
  • 6
  • 20