Search code examples
arraysvb.nettagslabel

Assign Array Position to a Label Tag Property


I want to assign an array to the Tag property of 16 Labels. This is what I came up with:

Label1.Tag = FotoArray(0)
Label2.Tag = FotoArray(1)
Label3.Tag = FotoArray(2)
Label4.Tag = FotoArray(3)
Label5.Tag = FotoArray(4)
Label6.Tag = FotoArray(5)
Label7.Tag = FotoArray(6)
Label8.Tag = FotoArray(7)
Label9.Tag = FotoArray(8)
Label10.Tag = FotoArray(9)
Label11.Tag = FotoArray(10)
Label12.Tag = FotoArray(11)
Label16.Tag = FotoArray(12)
Label13.Tag = FotoArray(13)
Label15.Tag = FotoArray(14)
Label14.Tag = FotoArray(15)

Is there a way to do it in a shorter way?


Solution

  • Assuming Label16.Tag = FotoArray(12) is a typo, this should do the work:

    For counter As Integer = 1 To 16
        Dim label As Label = Me.Controls.Find("Label" & counter, True).FirstOrDefault()
        If Not label Is Nothing Then
            label.Tag = FotoArray(counter - 1)
        End If
    Next
    

    You can also simply use Me.Controls(name) instead. The updated code would look like this:

    For counter As Integer = 1 To 16
        Dim label As Label = Me.Controls("Label" & counter)
        If Not label Is Nothing Then
            label.Tag = FotoArray(counter - 1)
        End If
    Next