What would be the best approach to create the following:
A groupbox that contains
several labels
a groupbox with an array of 8 labels in it

Then the main form would have 4 of these groupboxs (object?) and I would need the ability to change the color and text of all the various labels within any of the groupboxes, using an index similar to what we could do with control arrays in VB6.

I would think an object would make the most sense but can you have control elements in an object and display them on the form?

This will do it quick and dirty

Public Class Form1

    Private groups(3) As GroupBox

    Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load

        Me.SuspendLayout()

        'create 4 groups

        For g = 0 To 3

            groups(g) = New GroupBox

            With groups(g)

                .Text = "Group " & g
                .Size = New System.Drawing.Size(160, 220)
                .Location = New System.Drawing.Point(13 + 165 * g, 13)

                'create 8 labels within this group

                For i As Integer = 0 To 7

                    Dim label As New Label
                    With label
                        .Text = "label " & i
                        .Size = New System.Drawing.Size(60, 13)
                        .Location = New System.Drawing.Point(18, 23 + 25 * i)
                    End With

                    .Controls.Add(label)

                Next

            End With

            Me.Controls.Add(groups(g))

        Next

        Me.ResumeLayout()

    End Sub

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

        'change text and colour for the third label in the third group

        With groups(2).Controls(2)
            .Text = "splunge"
            .BackColor = Color.Aqua
        End With

    End Sub

End Class

If you wanted to pretty it up you could define a custom groupbox class which would have an array of labels. Note that when I define the positions of the new labels and group boxes I add a few pixels for spacing (group width is 160 but next width is 13+165*g). You could also (I think) subclass the groupbox control but I've never gotten that fancy and am not familiar with the technique.

This gets a little messier when you want to add handlers for events but this is probably not a concern for just labels.

Edited 4 Years Ago by Reverend Jim: n/a

Thanks, this looks like what I needed to get point in the right direction. I would eventually want a click event on the groupbox, but I'll worry about that after I get the form working.

Edited 4 Years Ago by dksmall: n/a

Actually everything in the groupbox would tie to the same click event, which would pop up a menu. I added the AddHandler stuff today, looks like it's all doing what I wanted. Thanks!

This question has already been answered. Start a new discussion instead.