Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loop over all textboxes in a form, including those inside a groupbox

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?

like image 929
kodkod Avatar asked Jan 12 '11 20:01

kodkod


1 Answers

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
like image 91
Tim Schmelter Avatar answered Oct 23 '22 09:10

Tim Schmelter