Home > Blockchain >  How to create an array of PictureBoxes and use it?
How to create an array of PictureBoxes and use it?

Time:12-20

I thought "brickn()" will creat an array and "NoOfBrick" will be the array length and all array will store in it

Dim brickWidth as Integer = 0
Dim Brickn() As PictureBox  
dim NoOfBrick as Integer       ' array length

Public Function CreateBrick() As PictureBox
  Dim myBrickn As New PictureBox

  With myBrickn
    .Size = Brick.Size
    .Left = BrickWidth
    .Top = 0
    .Image = Brick.Image
    .SizeMode = PictureBoxSizeMode.StretchImage
    .BackColor = Color.Black
  End With

  Return myBrickn
End Function

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
   For i = -75 To Me.Width 
     Brickn(NoOfBrick) = CreateBrick() 'and also how to add array/list here 
     Me.Controls.Add(Brickn(NoOfBrick))
     BrickWidth  = 170 'increasing brick.left on every new brick is created 
     i  = 170          ' increasing looop count according to brick needed    
     NoOfBrick  =1
  Next
End Sub

But this code is throwing error on "Me.Controls.Add(Brickn(NoOfBrick))" this error

System.NullReferenceException: 'Object reference not set to an instance of an object.'

I thought if I will get array of PictureBoxes then I can access control on them for this

Private Sub Boll_control_Tick(sender As Object, e As EventArgs) Handles Boll_control.Tick
  If Ball.Bounds.IntersectsWith(brickn(NoOfBrick).Bounds) Then
    Me.Controls.Remove(brickn(NoOfBrick))
  End If
End Sub

CodePudding user response:

Change:

Dim Brickn() As PictureBox

To:

Dim Brickn As New List(Of PictureBox)

Then, when you want to Add something to "Brickn", you'd do:

Brickn.Add(CreateBrick())

You can still access "Brickn" with array syntax, such as:

Brickn(NoOfBrick).Bounds

The difference is that a List will automatically grow or shrink in size as you add/remove things to it, while an Array has a fixed size (you never actually created the array in your code and gave it a size).

You can do hit testing with something like:

Dim hit = Brickn.Where(Function(brick) Ball.Bounds.IntersectsWith(brick.Bounds))
For Each brick As PictureBox In hit
    Me.Controls.Remove(brick)
    Brickn.Remove(brick)
Next
  • Related