循环遍历表单中的所有文本框,包括分组框内的文本框 [英] loop over all textboxes in a form, including those inside a groupbox
问题描述
我在一个 winform 中有几个文本框,其中一些在一个分组框内.我试图遍历表单中的所有文本框:
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
但它似乎跳过了 groupbox 内的那些,而只在表单的其他文本框上循环.所以我为 groupbox 文本框添加了另一个 For Each 循环:
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
我想知道:有没有办法用单个 For Each 循环遍历表单中的所有文本框(包括分组框内的文本框)?或者有什么更好/更优雅的方式来做到这一点?
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?
推荐答案
你可以使用这个功能,linq 可能是一种更优雅的方式.
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
这篇关于循环遍历表单中的所有文本框,包括分组框内的文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!