如何清除GroupBox中的每个TextBox

时间:2018-11-26 01:22:18

标签: vb.net winforms textbox

我在清空GroupBox中的每个TextBox时遇到问题,因为我的循环仅在textbox1有值的情况下清除所有TextBox,但是如果我尝试绕过textbox1并跳转到{{1 }},我的textbox2方法不起作用。

如果需要更改,请查看我的循环代码:

ClearCtrlText

2 个答案:

答案 0 :(得分:2)

我很想将其写为扩展方法:

Imports System.Runtime.CompilerServices

Public Module ControlExtensions

    <Extension>
    Public Sub ClearTextBoxes(source As Control)
        For Each child As Control In source.Controls
            Dim tb = TryCast(child, TextBox)

            If tb Is Nothing Then
                child.ClearTextBoxes()
            Else
                tb.Clear()
            End If
        Next
    End Sub

End Module

然后您可以在控件上调用它,就像它是成员一样,例如

GroupBox1.ClearTextBoxes()

此方法还包括访问子容器内的子控件所需的递归,例如Panel内的GroupBox

答案 1 :(得分:1)

您需要 RECURSE 放入这样的表单内的容器中:

Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        ClearCtrlText(Me)
    End Sub

    Public Sub ClearCtrlText(ByVal root As Control)
        For Each ctrl As Control In root.Controls
            If TypeOf ctrl Is TextBox Then ' textbox set to empty string
                If ctrl.Text <> "" Then
                    ctrl.Text = Nothing
                End If
            ElseIf ctrl.HasChildren Then
                ClearCtrlText(ctrl)
            End If
        Next
    End Sub

End Class