distante
distante

Reputation: 7005

Access several controls with a for in visual basic

I Got this form with several Labels inside a GroupBox, all with the same name plus a number (similar to the default Label1, Label2, LabelN)

I'm changing the look and content of this labels with a sub(), but I can't figure out how to refer to each label without write the complete name it's possible to do something like:

To All Labels inside Group Box 
Sub(LabelN)

Currently I'm creating an Array of labels and assigning the names when the form loads, something like:

 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        LabelMatrix(0) = Label1
        LabelMatrix(1) = Label2
        LabelMatrix(2) = Label3
        LabelMatrix(3) = Label4
....
    End Sub

But I suppose there must be a better (and smarter) way to do this.

I wanted to do it in a way that I get the total of the Labels objects in the Groups box but my efforts were unsuccessful.

Upvotes: 0

Views: 354

Answers (2)

Joel Coehoorn
Joel Coehoorn

Reputation: 415881

It's pretty easy, no arrays required:

For Each lbl As Label In MyGroupBox.Controls.OfType(Of Label)()
    ' ... do something with "lbl"
Next lbl

Upvotes: 2

Idle_Mind
Idle_Mind

Reputation: 39132

You can use a loop to build the control names, and Controls.Find() to get a reference to the desired control. Something like:

    Dim lbl As Label
    Dim matches() As Control
    For i As Integer = 1 To 10
        matches = Me.Controls.Find("Label" & i, True)
        If matches.Length > 0 AndAlso TypeOf matches(0) Is Label Then
            lbl = DirectCast(matches(0), Label)
            ' ... do something with "lbl" ...
        End If
    Next

Upvotes: 1

Related Questions