VB.NET Iteration Form Forms

I have a few boxes of lettering in my design form that all share a naming convention lbl_#.text

where # ranges from 1 to 60. I want to create a loop that iterates through each lbl_#.text

one adding some extra value, say from 2 for this question theoretical goal.

Something such that the end result is the following:

lbl_1.text = "2"
lbl_2.text = "4"
lbl_3.text = "6"
lbl_60.text = "120"


I'm not sure how to access each of these labels via encoding, I know how to explicitly list each label and assign a value: /


source to share

3 answers

Use the Controls collection:

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles    MyBase.Load
        Dim i As Integer
       For i = 1 To 3
            Dim myLabel As Label = CType(Me.Controls("lbl_" & i), Label)
            myLabel.Text = ...whatever value you want to put here
    End Sub
End Class




There are several options here.

  • In this situation, the labels will often have a common container such as a panel or group box control. In this case:

    For Each formLabel As Label In myContainerControl.Controls.OfType(Of Label)()
    Next formLabel

    Of course, this mixes logical groups with visual groupings, and the two don't always align. And you can also ...

  • Add them all to an array (or List (Of Label) or any other enumerable):

    Dim formLabels(60) As Label = {lbl_1, lbl_2, lbl_3 .... }
    For Each formLabel As Label in formLabels
    Next formLabel

  • Use the .Name property:

    For Each formLabel As Label In Controls.Where(Function(c) c.Name.StartsWith("lbl_"))
    Next formLabel

  • Some combination of the above (for example, code in a form load event to create a list based on the name property).

The ultimate strategy is to think in terms of data source binding, where your labels are created as part of a DataGridView, FlowLayoutPanel, or similar. You can then iterate over the rows in the grid or panel.



If you don't know how many labels there are, one option is to use Do Loop.

    Dim lblTarget As Label = Nothing
    Dim intCursor As Integer = 1
    Dim bolFirstIteration As Boolean = True

    Do Until lblTarget Is Nothing AndAlso Not bolFirstIteration

        If bolFirstIteration Then

            bolFirstIteration = False

        End If

        lblTarget = CType(Me.Controls("lbl_" & intCursor.ToString()), Label)

        If Not lblTarget Is Nothing Then

            lblTarget.Text = (intCursor * 2).ToString()

        End If

        intCursor += 1





All Articles