如何清除 GroupBox 中的每个 TextBox

How to clear every TextBox inside a GroupBox

我在清空 GroupBox 中的每个文本框时遇到问题,因为我的循环仅在 textbox1 具有值时清除所有文本框,但如果我尝试绕过 textbox1 并跳转到输入数据到 textbox2,我的ClearCtrlText方法不行。

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

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
        End If
    Next
End Sub

您需要像这样 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

我很想把它写成扩展方法:

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()

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

里面的 Panel