John Doe John Doe - 1 year ago 100 Question

How to declare a 2D array to store pictures (using picture boxes)

I am designing a Breakout style game for a project that I am currently working on. I have just finished implementing the ball and the paddle and am having some trouble implementing the bricks for the game. I have a picture of a brick that I want to put in the game. For this, as I need a grid of bricks, I was thinking of declaring a 2D array of pictureboxes (so I can assign the picture of the brick) but I have only been able to declare the array. This is the line of code I have:

Dim Bricks(9, 9) As PictureBox

So, my question is: How do I access each picturebox and assign the image of the brick? and is there a quicker way to do it? Thanks, your help will be very much appreciated.

Answer Source

Note that after you create the Bricks array, this array is still empty, i.e. all its elements are Nothing. You will need to assign the PictureBoxes that are on your form to this array, unless you want to go the other way round and create the picture boxes dynamically.

In the first case do something like this:

Bricks(0,0) = pictureBox1
Bricks(0,1) = pictureBox2

Or with loops

For x As Integer = 0 To 9
    For y As Integer = 0 To 9
        Bricks(x, y) = Controls("pictureBox" & (10 * x + y))

Or (10 * y + x) depending on the order you have chosen.

In the other case (create the picture boxes automatically)

For x As Integer = 0 To 9
    For y As Integer = 0 To 9
        'Create and initialize the PictureBox
        Dim pb AS New PictureBox
        pb.Size = New Size(30, 30)
        pb.Location = New Point(20 + 30 * x, 20 + 30 * y)
        pb.Image = myinitialImage
        AddHandler pb.Click, AddressOf HandlePictureClick

        'Assign the PictureBox to the array
        Bricks(x, y) = pb

        'Add the PictureBox to the Form

Now you can assign a picture like this

Bricks(x, y).Image = myPicture
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download