Loop through text fields in vb.net

I remember in vb6 you managed to create an array of text fields.

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

      

But in vb.net, you can't create an array? Therefore, if you have a code like this. Is it possible to set it to a 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 = ""

      

+3


source to share


3 answers


If the TextBox controls are only on the main form, you can skip them:

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

      



If they are in a panel, replace the keyword Me

with the panel name.

+5


source


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 inside other controls like 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 answer here )



Private Function GetTextBoxes(root As Control) As IEnumberable(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 the main form:

Dim allBoxes As List(Of TextBox) = GetTextBoxes(Me).ToList()

      

+2


source


For reference, you can create an array of TextBox objects like this:

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

Or, declare an array and loop the TextBox controls to add them to it. However, the approach List(Of TextBox)

will work really well if you need to keep a collection of them, or just scroll through the TextBox controls on the form if you just need to set properties in one sub or function.

+2


source







All Articles