我的表格有tabcontrol和几个标签页,其中包含文本框和复选框中的许多设置 当用户从此表单按退出时,我必须检查数据是否已更改。
为此,我想在表单上输入所有值的字符串,并在退出时将其与所有值的字符串进行比较:
Private Function getsetupstring() As String
Dim setupstring As String = ""
For Each oControl As Control In Me.Controls
If TypeOf oControl Is CheckBox Then
Dim chk As CheckBox = CType(oControl, CheckBox)
setupstring &= chk.Checked.ToString
End If
If TypeOf oControl Is TextBox Then
setupstring &= oControl.Text.Trim.ToString
End If
Next
Return setupstring
End Function
但是该代码不会遍历标签页上的控件,只有TabControl和几个位于表单顶部的按钮。
如何列出所有控件以便我可以选择值?
答案 0 :(得分:2)
Controls
仅包含父控件,而不包含相应的子控件。如果你想获得所有控件(父母和各自的孩子),你可以依赖这些代码:
Dim allControls As List(Of Control) = New List(Of Control)
For Each ctr As Control In Me.Controls
allControls = getAllControls(ctr, allControls)
Next
getAllControls
定义于:
Private Function getAllControls(mainControl As Control, allControls As List(Of Control)) As List(Of Control)
If (Not allControls.Contains(mainControl)) Then allControls.Add(mainControl)
If mainControl.HasChildren Then
For Each child In mainControl.Controls
If (Not allControls.Contains(DirectCast(child, Control))) Then allControls.Add(DirectCast(child, Control))
If DirectCast(child, Control).HasChildren Then getAllControls(DirectCast(child, Control), allControls)
Next
End If
Return allControls
End Function
您拥有的其他替代方法是依赖Controls.Find
方法,searchAllChildren
属性设置为True
。