Wine Too
Wine Too

Reputation: 4655

Loop controls in form and tabpages

I have form with tabcontrol and few tab pages which contain many settings in textboxes and checkboxes.
When user press Exit from this form I have to check if data was changed.

For that I thought to make a string on Enter of all values on form and compare it with string of all values on exit:

   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

But that code don't loop through controls which are on tab pages, only TabControl and few buttons which are on top of form.

What to do to get all controls listed so I can pick values?

Upvotes: 1

Views: 4500

Answers (1)

user2480047
user2480047

Reputation:

Controls only contains the parent controls, not the respective children. If you want to get all the controls (parents and respective children), you can rely on a code on these lines:

Dim allControls As List(Of Control) = New List(Of Control)
For Each ctr As Control In Me.Controls
    allControls = getAllControls(ctr, allControls)
Next

Where getAllControls is defined by:

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

Other alternative you have is relying on the Controls.Find method with the searchAllChildren property set to True.

Upvotes: 3

Related Questions