Clearing many textbox controls in vb.net at once

不想你离开。 提交于 2019-12-21 17:52:18

问题


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?


回答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



回答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



回答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



回答4:


try this one

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

or

Dim a As Control
    For Each a In Me.Controls
        If TypeOf a Is TextBox Then
            a.clear()
        End If
    Next

if .Clear() is a member of textbox property then use it. i guess .clear() is not a member of textbox properties.




回答5:


This is my code that I personally use it in my projects ^_^

ClearAll TextBoxes : For Each TxtBox In Me.Controls.OfType(Of TextBox) TxtBox.Clear() Next TxtBox




回答6:


I had to cast the Control as a TextBox to make this work. Something about the control object not being accessible. There may be a more direct way but I was unable to find one.

I got the idea from https://stackoverflow.com/a/16264904/11242863

Private Sub clearAllTextBoxes()
    Dim formControl As Control
    Dim txtBox As TextBox
    For Each formControl In Me.Controls
        If TypeOf formControl Is TextBox Then
            txtBox = TryCast(formControl, TextBox)
            txtBox.Clear()
        End If
    Next
End Sub

I hope this helps someone,

Tim R



来源:https://stackoverflow.com/questions/17906065/clearing-many-textbox-controls-in-vb-net-at-once

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!