此程序的目的是运行一系列图片框并将其.image属性设置为特定图像。我不断收到错误“对象引用未设置为对象的实例”。来自显示“DirectCast(Me.Controls(pic(i)),PictureBox).Image = My.Resources.glass_buttonred”的行。奇怪的是,如果我将该代码移到for循环之外它只运行精细。
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim pic(2) As Object
For i = 0 To 2
pic(i) = "picturebox" + Convert.ToString(i)
DirectCast(Me.Controls(pic(i)), PictureBox).Image = My.Resources.glass_buttonred
Next
Label1.Text = pic(1)
End Sub
这是工作代码。谢谢!希望它能帮助其他人想要将字符串转换为控制对象
Dim pic(2) As Object
For i = 0 To 2
pic(i) = "picturebox" + Convert.ToString(i + 1)
DirectCast(Me.Controls(pic(i)), PictureBox).Image = My.Resources.glass_buttonred
Next
Label1.Text = pic(1)
答案 0 :(得分:3)
问题可能是Me.Controls
区分大小写。如果你使用设计师来构建这些,你可能需要:
' Note the upper case letters below
pic(i) = "PictureBox" + (i + 1).ToString()
DirectCast(Me.Controls(pic(i)), PictureBox).Image ' ...
默认情况下,设计师会将控件命名为“PictureBox1”(第一个),第二个命名为“PictureBox2”,案例相关。