-1

How can I change a picture box's image when I only have a string that has the name of the picture box. (it probably doesn't really matter that it's a picture box or that I am changing it's image)

For example:

"picturebox1".image = myimage      'how would I get this to actually set an image for picturebox1?
4
  • You'd need to use reflection. Commented Jun 10, 2013 at 15:53
  • 3
    How did you come to this point? I'm guessing there's a problem with the design somewhere else which would be better fixed than to continue with this approach. Why do you have the name of the variable as a string? Commented Jun 10, 2013 at 15:54
  • I just realized that this is a duplicate. the answer is here: StackOverflow Thanks for the super fast replies Commented Jun 10, 2013 at 16:02
  • @user1727470: Controls.Find method suggested by @Douglas is better, because it allows you to traverse the tree of controls. Me.Controls in the answer you linked only takes top level (direct children) into account. Commented Jun 10, 2013 at 17:02

2 Answers 2

4

I always prefer using DirectCast instead of CType. This is also safer because it won't crash if it doesn't find a picturebox with that particular name.

Dim pb As PictureBox = DirectCast(Me.Controls.Find("picturebox1", True).FirstOrDefault(),  PictureBox)
If pb IsNot Nothing Then
    pb.Image = myimage
End If
Sign up to request clarification or add additional context in comments.

2 Comments

I like the OfType extension method: Dim pb = Me.Controls.OfType(Of PictureBox).FirstOrDefault()
That's a good suggestion. The DirectCast will throw an exception if it finds a control of that name but a different type.
0

Try this ..

Dim pic as PictureBox = CType(Me.Controls("PictureBox1", PictureBox))
pic.Image = myimage 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.