在vb.net中以编程方式添加多个图片框 [英] Adding multiple pictureboxes to a form programmatically in vb.net
问题描述
所以我写了一小段代码来添加6个图片框到随机位置的表单。它将每个图片框添加到集合,然后循环遍历集合,并将它们添加到表单控件。奇怪的问题是,代码只有当我在调试模式下一行一行的时候工作。如果我只是编译和运行代码,然后只有1 picturebox被添加到窗体,但如果我逐行通过代码行,那么所有6个图片框被成功添加到随机位置的形式。任何人都可以告诉我为什么地狱这发生?它驱动我很坚果。代码如下:
For i As Integer = 0至5
Dim pic As New PictureBox
Dim rnd As new Random
pic.Location = New Point(rnd.Next(200,300),rnd.Next(200,300))
pic.Size = New Size(5,5)
pic.BackColor = Color.White
pic.Visible = True
pic.BringToFront()
_picCollection.Add(pic)
下一页
每个项目作为PictureBox在_picCollection
Controls.Add(item)
下一页
ShowDialog()
没有声明RND对象在循环外。谢谢tinstaafl!
So I have written a short section of code to add 6 pictureboxes to a form in random locations. It adds each picturebox to a collection, then loops through the collection and adds them to the form control. The bizarre issue is that the code only works when I step through it line by line in debug mode. If I just compile and run the code then only 1 picturebox is added to the form, but if I step through the code line by line then all 6 pictureboxes are successfully added to the form in random locations. Can anyone tell me why the hell this happening? It's driving me pretty nuts. Code below:
For i As Integer = 0 To 5
Dim pic As New PictureBox
Dim rnd As New Random
pic.Location = New Point(rnd.Next(200, 300), rnd.Next(200, 300))
pic.Size = New Size(5, 5)
pic.BackColor = Color.White
pic.Visible = True
pic.BringToFront()
_picCollection.Add(pic)
Next
For Each item As PictureBox In _picCollection
Controls.Add(item)
Next
ShowDialog()
Open to suggestions of how to do this better / in a way that actually works properly.
Had to declare RND object outside of loop. Thanks tinstaafl!
这篇关于在vb.net中以编程方式添加多个图片框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!