user2027369
user2027369

Reputation: 63

Array of pictureboxes (Am I doing it right?)

So I declared an array of pictureboxes with a class scope like so:

Dim picArray() As PictureBox = {Me.pic1, Me.pic2, Me.pic3}

Where pic1, pic2, and pic3 are pictureboxes that are already on the form.

A button event then does the following.

For Each pic As PictureBox In picArray
        pic.Left += 15
    Next

I expected the code to move all pictureboxes to the right when the button is clicked but an error occurs saying that I should declare the pictureboxes as New. What should I do?

Upvotes: 2

Views: 2627

Answers (3)

Jens
Jens

Reputation: 6375

The problem is that you declare the array inline. The array objects are nothing in this case. I myself don't know exactly why. The solution is to initialize the array in the Form.Load event like this:

Public Class Form1

  Dim pbs() As PictureBox
  Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
      For Each p As PictureBox In pbs
          p.Left += 15
      Next
  End Sub

  Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
      pbs = {Me.PictureBox1, Me.PictureBox2, Me.PictureBox3}
  End Sub

End Class

This works. It is often nice to create a controls array to quickly adjust settings for various similar controls in a loop afterwards but I usually only create the array locally in the sub.

Upvotes: 1

Bhavesh Kachhadiya
Bhavesh Kachhadiya

Reputation: 3962

In stead of making a pic array.

Why you are not using already available picture boxs on current form in this way:

For Each pic As Control In Me.Controls
    If TypeOf pic Is PictureBox Then
       pic.Left += 15
    End If
Next

As you want to move all pic this will be more helpful

Upvotes: 1

Haji
Haji

Reputation: 2077

You are already have picture boxes in form. So no need to create array of picture box. If you are dynamically creating the controls then only you should specify the picture box in coding..

Use the below coding to move all the picture box in you forms

   For Each pic As Control In Me.Controls
        If TypeOf (pic) Is PictureBox Then
            pic.Left += 15
        End If
    Next

Upvotes: 0

Related Questions