Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
854 views
in Technique[技术] by (71.8m points)

vb.net - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It's pretty easy, no arrays required:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...