arraysvb.netimagelist

Assigning images to a picturebox from an imagelist


I have to assign 16 images that are randomized in an array to pictureboxes. I came up with the idea of creating an imagelist and then assign them to the pictureboxes. Is there a way to shorten this? This is the code that I came up with:

For i = 0 To FotoArray.Length - 1
                ImageList1.Images.Add(Image.FromFile(FotoArray(i)))
            Next
    
            PictureBox1.Image = ImageList1.Images(0)
        PictureBox2.Image = ImageList1.Images(1)
        PictureBox3.Image = ImageList1.Images(2)
        PictureBox4.Image = ImageList1.Images(3)
        PictureBox5.Image = ImageList1.Images(4)
        PictureBox6.Image = ImageList1.Images(5)
        PictureBox7.Image = ImageList1.Images(6)
        PictureBox8.Image = ImageList1.Images(7)
        PictureBox9.Image = ImageList1.Images(8)
        PictureBox10.Image = ImageList1.Images(9)
        PictureBox11.Image = ImageList1.Images(10)
        PictureBox12.Image = ImageList1.Images(11)
        PictureBox13.Image = ImageList1.Images(12)
        PictureBox14.Image = ImageList1.Images(13)
        PictureBox15.Image = ImageList1.Images(14)
        PictureBox16.Image = ImageList1.Images(15)

and also for this

Is there a way to make the same for this labels?

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)

Solution

  • You can make use of the OfType Linq extension method to help make this code succint such as:

        Dim pictureBoxes As List(Of PictureBox) = Me.Controls.OfType(Of PictureBox).ToList()
    
        For counter As Integer = 0 To pictureBoxes.Count - 1
            Dim pb As PictureBox = pictureBoxes(counter)
            pb.Image = ImageList1.Images(counter)
        Next
    

    From MSDN:

    Filters the elements of an IEnumerable based on a specified type.