VB.NET - Iterating through controls in a container object

You can skip the GetType and CType dance with TryCast:

Dim dtp as DateTimePicker = TryCast(ctrl, DateTimePicker)
If dtp IsNot Nothing then dtp.Value = Now()

That'll save you about 10 lines.

An extension method off the Control class should keep it pretty tidy:

<Extension()> _
Public Shared Sub ClearValue(c as Control, recursive as Boolean)
   Dim dtp as DateTimePicker = TryCast(c, DateTimePicker)
   If dtp IsNot Nothing Then dtp.Value = Now()
   ' Blah, Blah, Blah
End Sub

Edit: If the thought of Evil extension methods that ignore NullReferenceExceptions don't make you cringe:

<Extension()> _
Public Shared Sub ClearValue(c as CheckBox)
   If c IsNot Nothing Then c.Checked = False
End Sub

TryCast(ctrl, CheckBox).ClearValue()

here is the code to get all control of a Form's All GroupControls and you can do something in the GroupBox Control

Private Sub GetControls()
    For Each GroupBoxCntrol As Control In Me.Controls
        If TypeOf GroupBoxCntrol Is GroupBox Then
            For Each cntrl As Control In GroupBoxCntrol.Controls
                'do somethin here

            Next
        End If

    Next
End Sub

Why not just have one routine

ClearAllControls(ByRef container As Control, Optional ByVal Recurse As Boolean = True)

You can recurse into it regardless of what level in the hierarchy you begin the call, from the form level down to a single container.

Also, on the TextBox controls, I use Textbox.Text = String.Empty

Tags:

Vb.Net