0

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?

Zarb
  • 17
  • 6
  • Does this answer your question? [Find control by name from Windows Forms controls](https://stackoverflow.com/questions/3898588/find-control-by-name-from-windows-forms-controls) – Étienne Laneville Mar 11 '21 at 17:15

1 Answers1

0

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
Étienne Laneville
  • 4,697
  • 5
  • 13
  • 29