Home > other >  Select All Controls on Form
Select All Controls on Form

Time:12-01

I am trying to implement a clear all button on a form that clears the textbox contents and unchecks all checkboxes. The issue is that the controls that need to be accessed are contained within Groupboxes and thus cannot be acessed via Me.Controls collection. I saw a similar post here: VB Uncheck all checked checkboxes in forms, but the answer seems to be more complex than I would expect it should be. Is there any easier way other than in that post.

I tried this code, which logically to me should work but it does not:

'Get textboes and clears them
For Each ctrGroupBoxes As Control In Me.Controls.OfType(Of GroupBox)
    For Each ctrControls As Control In ctrGroupBoxes.Controls.OfType(Of TextBox)
        ctrControls.Text = ""
    Next
Next
'Get checkboxes and unchecks them
For Each ctrGroupBoxes As Control In Me.Controls.OfType(Of GroupBox)
    For Each ctrControls As Control In ctrGroupBoxes.Controls.OfType(Of CheckBox)
        DirectCast(ctrControls, CheckBox).Checked = False
    Next
Next

I know the inner for loops work as I used it to clear each GroupBox individually for a different button on the form.

Any assistance would be appreciated.

CodePudding user response:

Here's one option that should work regardless of the UI hierarchy:

Dim cntrl = GetNextControl(Me, True)

Do Until cntrl Is Nothing
    Dim tb = TryCast(cntrl, TextBox)

    If tb IsNot Nothing Then
        tb.Clear()
    Else
        Dim cb = TryCast(cntrl, CheckBox)

        If cb IsNot Nothing Then
            cb.Checked = False
        End If
    End If

    cntrl = GetNextControl(cntrl, True)
Loop

That will follow the Tab order on the form

CodePudding user response:

A recursive function really isn't that difficult:

Public Class Form1

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

    Private Sub ClearForm(ByVal C As Control)
        For Each ctl As Control In C.Controls
            If TypeOf ctl Is TextBox Then
                ctl.Text = ""
            ElseIf TypeOf ctl Is CheckBox Then
                DirectCast(ctl, CheckBox).Checked = False
            ElseIf ctl.HasChildren Then
                ClearForm(ctl)
            End If
        Next
    End Sub

End Class
  • Related