我在winform中有几个文本框,其中一些在groupbox中.我试图遍历我的表单中的所有文本框: For Each c As Control In Me.Controls If c.GetType Is GetType(TextBox) Then ' Do something End IfNext 但它似乎跳过了grou
For Each c As Control In Me.Controls If c.GetType Is GetType(TextBox) Then ' Do something End If Next
但它似乎跳过了groupbox中的那些并且仅循环到表单的其他文本框.所以我为groupbox文本框添加了另一个For Each循环:
For Each c As Control In GroupBox1.Controls If c.GetType Is GetType(TextBox) Then ' Do something End If Next
我想知道:有没有办法循环遍历表单中的所有文本框 – 包括组框内的文本框 – 只有一个For Each循环?或者更好/更优雅的方式来做到这一点?
提前致谢.
你可以使用这个功能, linq可能是一个更优雅的方式.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