在Visual Basic中访问多个PictureBox(或任何表单控件)?

问题描述 投票:-2回答:2

所以我在VB中制作游戏用于学习目的,现在我正在努力解决这个问题:

我正在尝试绘制水平贴图的For循环。但是,我似乎无法弄明白。这是我正在尝试做的一个例子:

For index as integer = 1 to 192
    PictureBox(index).Image = bg(map(x,y)) 'this is causing me problems
    x=x+1
    if x=16 then
        x=0
        y=y+1
    End If
Next

但由于PictureBox(索引).Image似乎不是正确的答案,它只是给我一个错误。

有没有办法做到这一点?

编辑:

不久,我需要像这样设置PictureBox.Image从1到192,而不需要192行代码:

PictureBox1.Image = bg(map(0,0))
PictureBox2.Image = bg(map(1,0))
PictureBox3.Image = bg(map(2,0))
PictureBox4.Image = bg(map(3,0))
'etc....

相反,我不想在For循环中设置它们。我不想要额外的代码行。

Aaditi:

PictureBoxes将添加到编辑器中。

vb.net picturebox
2个回答
0
投票

在设计者中将每个Tag的属性PictureBox设置为由传递给x函数所需的ymap组成的字符串值

例如:

  • PictureBox1应将Tag属性设置为“0,0”
  • PictureBox2将Tag属性设置为“1,0”,
  • ....
  • PictureBox17将Tag属性设置为“0,1”

依此类推,直到您使用正确的值映射所有图片框。

然后您的代码可以更改为

' Assuming the PictureBox are all childs of the Form
For Each pic in Me.Controls.OfType(Of PictureBox)()

    Dim tag = pic.Tag

    ' You could omit this check if you have only the pictureboxes
    ' set with a valid Tag property 
    if Not string.IsNullOrEmpty(tag) Then
       Dim xyCoords = tag.ToString().Split(","c)
       pic.Image = bg(map(Convert.ToInt32(xyCoords(0), 
                          Convert.ToInt32(xyCoords(1))))
    End if
Next

0
投票

我将在这里做出一个巨大的假设并假设您在到达此代码之前已经在表单上有PictureBox,并且他们有Id的PictureBox1到PictureBox192。代码如下所示。你需要: 1.按ID检索元素 2.将其从对象转换/转换为PictureBox 3.适当地设置它的Image属性。

Dim pBox As PictureBox ' To store each pic box in
For index as integer = 1 to 192
    pBox = Me.Controls.Find(PictureBox&&index) ' Try to find pic box by ID
    If Not pBox Is Nothing Then ' If able to find element by this ID
        DirectCast(pBox, PictureBox).Image = bg(map(x,y))
    End If
    x=x+1
    if x=16 then
        x=0
        y=y+1
    End If
Next
© www.soinside.com 2019 - 2024. All rights reserved.