Access several controls with a for in visual basic

浪尽此生 提交于 2019-12-29 08:24:24

问题


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.


回答1:


It's pretty easy, no arrays required:

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



回答2:


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


来源:https://stackoverflow.com/questions/19839927/access-several-controls-with-a-for-in-visual-basic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!