Search code examples
vb.netwinformstextbox

How to clear every TextBox inside a GroupBox


I am having problem with emptying every TextBoxes inside a GroupBox, because my loop only clears all TextBoxes if textbox1 has value but if I try to bypass textbox1 and jump to input data to textbox2, my ClearCtrlText method doesn't work.

Please see my loop code if there's a need for change:

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

Solution

  • I would be tempted to write this as an extension method:

    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
    

    You can then call it on a control as though it was a member, e.g.

    GroupBox1.ClearTextBoxes()
    

    This method also includes the recursion required to access child controls inside child containers, e.g. a Panel inside the GroupBox.