I have several textboxes in a winform, some of them are inside a groupbox. I tried to loop over all textboxes in my form:
For Each c As Control In Me.Controls
If c.GetType Is GetType(TextBox) Then
' Do something
End If
Next
But it seemed to skip those inside the groupbox and loop only over the other textboxes of the form. So I added another For Each loop for the groupbox textboxes:
For Each c As Control In GroupBox1.Controls
If c.GetType Is GetType(TextBox) Then
' Do something
End If
Next
I wonder: is there a way to loop over all textboxes in a form--including those inside a groupbox--with a single For Each loop? Or any better/more elegant way to do it?
You can use this function, linq might be a more elegant way.
Dim allTxt As New List(Of Control)
For Each txt As TextBox In FindControlRecursive(allTxt, Me, GetType(TextBox))
'....'
Next
Public Shared Function FindControlRecursive(ByVal list As List(Of Control), ByVal parent As Control, ByVal ctrlType As System.Type) As List(Of Control)
If parent Is Nothing Then Return list
If parent.GetType Is ctrlType Then
list.Add(parent)
End If
For Each child As Control In parent.Controls
FindControlRecursive(list, child, ctrlType)
Next
Return list
End Function
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With