首页 文章

表格和标签中的循环控件

提问于
浏览
1

我有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和几个位于表单顶部的按钮 .

怎么做才能列出所有控件,以便我可以选择值?

1 回答

  • 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 .

相关问题