Clearing many textbox controls in vb.net at once

32,501

Solution 1

You could put them in an array then loop through the array:

For Each txt In {txtint1, txtext1, txttot1, txtint2, txtext2, txttot2, txtint3, txtext3, txttot3, txtint4, txtext4, txttot4, txtint5, txtext5, txttot5, txtint6, txtext6, txttot7, txtint8, txtext8, txttot8}
    txt.Clear()
Next

Solution 2

You can iterate over all controls on the form which are contained in root.Controls and see if it is of type a textbox TypeOf ctrl Is TextBox, then you can clear the text in that control CType(ctrl, TextBox).Text = String.Empty

Well!! You need to use recursion to loop through all controls

Adding the code:

Public Sub ClearTextBox(parent As Control)

    For Each child As Control In parent.Controls
        ClearTextBox(child)
    Next

    If TryCast(parent, TextBox) IsNot Nothing Then
        TryCast(parent, TextBox).Text = [String].Empty
    End If

End Sub

Solution 3

I tried one of the examples here but this seems to work for me:

Dim a As Control
    For Each a In Me.Controls
        If TypeOf a Is TextBox Then
            a.Text = Nothing
        End If
    Next

Solution 4

Try this

For Each txt As Control In Me.Controls.OfType(Of TextBox)()
   txt.Text = ""
Next
Share:
32,501
Random User
Author by

Random User

Student

Updated on February 21, 2021

Comments

  • Random User
    Random User about 3 years

    I am using the following code to clear the

    txtint1.Clear()
    txtext1.Clear()
    txttot1.Clear()
    txtint2.Clear()
    txtext2.Clear()
    txttot2.Clear()
    txtint3.Clear()
    txtext3.Clear()
    txttot3.Clear()
    txtint4.Clear()
    txtext4.Clear()
    txttot4.Clear()
    txtint5.Clear()
    txtext5.Clear()
    txttot5.Clear()
    txtint6.Clear()
    txtext6.Clear()
    txttot7.Clear()
    txtint8.Clear()
    txtext8.Clear()
    txttot8.Clear()
    

    Is there any possibility to clear all the textbox controls at once or with few lines of code?