user2824324
user2824324

Reputation: 31

Object reference not set to an instance of an object

The purpose of this program is to run through a range of pictureboxes and set it's .image property to a particular image. I keep getting the error "Object reference not set to an instance of an object". Coming from the line that shows "DirectCast(Me.Controls(pic(i)), PictureBox).Image = My.Resources.glass_buttonred"....Whats weird is if i move that code outside of the for loop it runs just fine.

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

HERE IS THE WORKING CODE. THANKS! Hope it will help others wanting to convert string to control object

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)

Upvotes: 3

Views: 426

Answers (1)

Reed Copsey
Reed Copsey

Reputation: 564433

The problem may be that Me.Controls is case sensitive. If you're using the designer to build these, you likely need:

' Note the upper case letters below
pic(i) = "PictureBox" + (i + 1).ToString()
DirectCast(Me.Controls(pic(i)), PictureBox).Image ' ...

The designer, by default, will name the controls "PictureBox1" (for the first), and "PictureBox2" for the second, with the case being relevant.

Upvotes: 3

Related Questions