我的程式碼:
Public Class Form1
Dim pictureBox As PictureBox() = New PictureBox(80) {}
Dim attachObstaclesMinimum As Integer = 20
Dim attachObstaclesMaximum As Integer = 50
Private Sub setPictureBox(sender As Object, e As EventArgs) Handles Me.Load
For y = 0 To 8
For x = 0 To 8
Dim i As Integer = y * 9 + x
Me.Controls.Add(pictureBox(i))
pictureBox(i) = New PictureBox
pictureBox(i).Name = "pictureBox" & i
pictureBox(i).Text = i
pictureBox(i).Size = New Size(50, 50)
pictureBox(i).Location = New Point(50 * (x) + 12, 50 * (y) + 12)
Next
Next
End Sub
Private Sub ButtonSet_Click(sender As Object, e As EventArgs) Handles ButtonSet.Click
For y = 0 To 8
For x = 0 To 8
Dim i As Integer = y * 9 + x
pictureBox(i).BackColor = Color.White
Next
Next
End Sub
Private Sub AttachObstacles_Click(sender As Object, e As EventArgs) Handles ButtonsetAttachObstacles.Click
Dim quantity As Integer = Fix((attachObstaclesMaximum - attachObstaclesMinimum + 1) * Rnd() + attachObstaclesMinimum)
For o = 1 To quantity
pictureBox(Fix(81 * Rnd())).BackColor = Color.Black
Next
End Sub
Private Sub AttachSAndTIntoMaze_Click(sender As Object, e As EventArgs) Handles ButtonAttachSAndTIntoMaze.Click
Dim tag As Integer() = Nothing
Dim z As Integer
For o = 0 To 80
If pictureBox(o).BackColor = Color.White Then
tag(z) = o
z += 1
End If
Next
Dim S As Integer = Fix(z * Rnd() + 1)
Dim T As Integer = Fix(z * Rnd() + 1)
pictureBox(S).Text = "S"
pictureBox(T).Text = "T"
End Sub
End Class
原本預期ButtonSet_Click可以把pictureBox0~80全塗白
原本預期AttachObstacles_Click可以把pictureBox0~80隨機塗黑20~50個
原本預期AttachSAndTIntoMaze_Click可以挑出T和S
結果都沒動作
我沒測試過,
不過我猜,
你把
Me.Controls.Add(pictureBox(i))
pictureBox(i) = New PictureBox
pictureBox(i).Name = "pictureBox" & i
pictureBox(i).Text = i
pictureBox(i).Size = New Size(50, 50)
pictureBox(i).Location = New Point(50 * (x) + 12, 50 * (y) + 12)
改成
pictureBox(i) = New PictureBox
pictureBox(i).Name = "pictureBox" & i
pictureBox(i).Text = i
pictureBox(i).Size = New Size(50, 50)
pictureBox(i).Location = New Point(50 * (x) + 12, 50 * (y) + 12)
Me.Controls.Add(pictureBox(i))
試試看.
可以了,能否告訴我原因
Me.Controls.Add(pictureBox(i))--->關鍵...
我知道換了那個,但是不懂原因
你一開始的寫法是先把 pictureBox 加進去 Me.Controls 再去給pictureBox 物件 所以 你一開始加進去的pictureBox是空的
因為你還沒有設定好資料,
就把它加到控制項清單裡面,
結果後面的動作都是沒有作用的,
做完動作後就被系統回收了.
另外,
如果有幫助到你,
麻煩設定一下最佳解答.
要先給新物件屬性,再Add新物件
現在才注意到這個按鈕0.0