这个程序的目的是遍历一系列的pictureboxes,并将它们的.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)