Adding to Collections

gqstud79

Newcomer
Joined
Sep 28, 2002
Messages
11
I have created a new collection which I would like to contain labels that are within a particular groupbox on my form, but not the other labels on my form that are outside of the groupbox. I realize i could just add each label to my collection by using a simple "collectionName.add(labelName)" for each label, but I would like to use a "for each" loop with an enclosed "if" statement to test each control on my form to see if it is within the groupbox and then add it to my collection. Hopefully I have explained the situation clearly. Thank you for your help.
 
You explained your situation just fine. :)

You need to declare a Control, then loop for each control in
the GroupBox's Controls property, which is a collection of controls
contained inside the GroupBox. Then you compare their types to
see if the control is a label, and if it is you can add it to your
collection.

Visual Basic:
    Dim ctl As Control
    Dim lbl As New Label()

    For Each ctl In GroupBox1.Controls
      If ctl.GetType Is lbl.GetType Then
        MyCollection.Add(ctl)
      End If
    Next
 
Thank you for your help. That worked perfectly. My mistake was using the "for...each" loop for controls on the entire form and trying to identify which ones where contained in the groupbox, when I could have just been using the "for....each" loop for the groupbox. Thanks again.
 
Back
Top