Domanda

How do I make an array of PictureBoxes in Visual Basic?

I'm trying to make a row of PictureBoxes -that's all the same size, and same picture- to display across the form. How could I do this?

I made the array using this:

Dim blk(10) As PictureBox

and the code to place the PictureBoxes is this:

'Create PictureBoxes
    blk(0) = blk_Green()
    blk(0).Image = imgl_blk.Images(0)
    blk(0).Visible = True
    blk(0).SetBounds(10, 10, blk_Green.Width, blk_Green.Height)
    For i = 1 To 10 Step 1
        blk(i) = blk_Green()
        blk(i).Image = imgl_blk.Images(0)
        blk(i).Visible = True
        blk(i).SetBounds(i * 10, 10, blk_Green.Width, blk_Green.Height)'I will change this according to what it needs to be
    Next

imgl_blk is an ImageList, and blk_Green is a ImageBox I've already made on the form.

When I run it, only one of the PictureBoxes will show up, instead of all 10 from the array.

This is what i'm trying to get (Or something like this): What i

This is what happens instead: What Happens

How could I make this work? Thanks in advance!

È stato utile?

Soluzione

If you want to create a control array:

Dim blk() As PictureBox

blk = New PictureBox() {PictureBox1, PictureBox2, PictureBox3, PictureBox4}

Then you can reference PictureBox1 with blk(0), PictureBox2 with blk(1), PictureBox3 with blk(2) and PictureBox4 with blk(3).

Altri suggerimenti

You're assigning the same Object's reference to all 10 PictureBoxes. You need to instantiate each one of your PictureBoxes separately and then assign each one's Image property.

BTW, you should really look into GDI+'s drawing methods such as Graphics.DrawImage() to do this kind of stuff. It would be a lot faster and less of a memory-hog.

You may try this :

Public Class Form1
  Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    Dim Shapes(10) As PictureBox
    For i = 1 To 10

        Shapes(i) = New PictureBox
        Shapes(i).Name = "rect" + Str(i)
        Shapes(i).BackColor = Color.Green

        Shapes(i).Location = New Point(10 + 50 * i, 20)
        Shapes(i).Size = New Size(40, 20)
        Shapes(i).Visible = True
        Me.Controls.Add(Shapes(i))
    Next
  End Sub
End Class
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top