vb.net 如何在 Visual Basic 中制作一组图片框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23440025/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make an array of PictureBoxes in Visual Basic
提问by hhaslam11
How do I make an array of PictureBoxes in Visual Basic?
如何在 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_blkis an ImageList, and blk_Greenis a ImageBox I've already made on the form.
imgl_blk是一个 ImageList,而blk_Green是一个我已经在表单上制作的ImageBox。
When I run it, only one of the PictureBoxes will show up, instead of all 10 from the array.
当我运行它时,只会显示一个图片框,而不是数组中的所有 10 个。
This is what i'm trying to get (Or something like this):

这就是我想要得到的(或类似的东西):

This is what happens instead:

这是发生的事情:

How could I make this work? Thanks in advance!
我怎么能让这个工作?提前致谢!
回答by Guru Josh
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).
然后你可以用 blk(0) 引用 PictureBox1,用 blk(1) 引用 PictureBox2,用 blk(2) 引用 PictureBox3,用 blk(3) 引用 PictureBox4。
回答by dotNET
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 Imageproperty.
您正在Object为所有 10 个图片框分配相同的's 引用。您需要分别实例化每个图片框,然后分配每个图片框的Image属性。
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.
顺便说一句,你真的应该研究一下 GDI+ 的绘图方法,比如Graphics.DrawImage()来做这种事情。它会快得多,而且不会占用太多内存。
回答by ej8000
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

