So, this might be simple but I seem to be missing it.

I am trying to figure out how to use variables to define which object to update. I could of course use a case statement to pick the object based on a variable, but it seems to me like there should be a more direct way. Here is a smaller example of what I would like to do.

In my form I have 4 picture boxes (pbox1, pbox2, pbox3, and pbox4). I then want to change the image in one of the boxes, but the box I want to change will be determined by a variable (say maybe a randomly generated number). Is there some way to dynamically concatenate the "pbox" with the number that VB would understand it and use it as an object?

In this example I could easily build a case statement to handle the selection, but in my real program there will be many more than 4 options.

Any thoughts, advice or anything else would be great. Or am I crazy?

Edit: Ack!!! and I cant even spell Variables!

i hope i understood your problem right...

Put your imageBoxes into a Panel (in my example it will have the name "PicPanel"

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
		Dim rand As New Random
		CType(PicPanel.Controls.Find("pBox" & rand.Next(1, 5), False).First, PictureBox).Image = New Bitmap("path to image")

	End Sub

	Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
		Randomize()
	End Sub

That should be exactly what I needed. I'll give it a try and see what happens. Thanks!

Well, no luck. I am getting an "InvalidOperationException was Unhandled" error on the CType line. My research has told me that it could be a control that has not been loaded yet is being called, but my testing has disproved that case. Anyone have thoughts on what the cause might be?

I'll post the code later when I have it on hand.

You get that exception because it didnt find the picturebox.
Make sure you have all the pictureboxes in a Panel grouped. and also make sure that your random generated number is not higher than the number of the last picturebox.

Dim Rnd As New Random
Me.Control("pBox" & Rnd.next(Low,High)).Image = New Bitmap(Path)

This won't work out because if the pictureboxes are in another control it won't find it.

Dim Rnd As New Random
AnotherFormName.Control("pBox" & Rnd.next(Low,High)).Image = New Bitmap(Path)

Public The Control

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.