Listing controls

gdubbs

Member
Joined
Oct 26, 2004
Messages
11
Location
USA
Programming Experience
Beginner
Hi! I am trying to use a sub to list controls in a form. The form has controls on it as well as in a groupbox. I am doing this using a sub command

I have gotten it to list all the controls in the form as well as the groupbox, but searately. My book says that each control has a controls count property that tells wheather there are items inside the control. Thus, by checking that, my sub can recurse deeper into that control and get the names of the items in there. I cannot figure out how to do this??

Any help is appreciated! Here is a sample of the code that I have to get all teh items listed.

Sub ControlList()
Dim Ctrl As Control
Dim grpCtrl As Control

For Each Ctrl In Me.Controls
MsgBox("The controls are: " & Ctrl.Name)
Next Ctrl

For Each grpCtrl In GroupBox1.Controls
MsgBox("The grouped controls are: " & grpCtrl.Name)
Next grpCtrl
End Sub

I also forgot to add that I need the items to appear in a list in a messagebox. As you can see, right now they are just in their own messageboxes.
 
Last edited:

Paszt

Staff member
Joined
Jun 3, 2004
Messages
1,500
Location
Raleigh, NC - USA
Programming Experience
Beginner
Here's some quickly thrown together code:

VB.NET:
Private strControls As String
Private Sub NameControls(ByVal mainCtrl As Control, _
  Optional ByVal bChild As Boolean = False)
    Dim ctrl As Control
    For Each ctrl In mainCtrl.Controls
        If bChild Then strControls &= "     "
        strControls &= ctrl.Name & vbCrLf
        'could use 'If ctrl.Controls.Count > 1 Then'
        If ctrl.HasChildren Then
            NameControls(ctrl, True)
        End If
    Next
End Sub

Private Sub ListControlsInMsgBox()
    strControls = "The controls are: " & vbCrLf
    NameControls(Me)
    MessageBox.Show(strControls)
End Sub

If the control is a child control, it will be indented five spaces. This gives a kind of tree view of the control's hierarchy.
 
Top Bottom