Question:
VB.Net pictureboxes and loops.?
KScarlett
2011-01-24 08:11:11 UTC
I'm a newbi programmer (halfway through my 1st year of computing at AS)

i want to have a for loop the set the image inside a picture box to a set image from my hard-drive.

I don't want to have to do 42 of these

PictureBox43.Image = System.Drawing.Image.FromFile("")

Changing the number everytime. But when i use a for loop

For i = 1 to 42
Pictureboxi.image = System.Drawing.Image.FromFile("")
next

I know it's because the pictureboxi is considered a name for a picture box and the computer can't find my pictureboxi.

So what way is there for me to make this loop?

I'm using VB.net on visual studio 2010 on the college computers by the way.
Three answers:
cosimo
2011-01-24 08:20:27 UTC
If you look at the link below it sounds like it gives an answer to your question, however it is probably best to refactor your code as the author has done to use an array of pictureboxes. Hope this helps.
Pfo
2011-01-24 16:28:12 UTC
You could add them all to an array like this:



dim pictureBoxes(42) as PictureBox = {PictureBox1, PictureBox2, ...}



Or use reflection and get the fields:



for i as integer = 0 to 42



dim name as String = String.format("PictureBox{0}", i)

dim info as FieldInfo = Me.GetType().GetField(name)

dim pictureBox as PictureBox = DirectCast(info.GetValue(me), PictureBox)

dim file as String = String.format("FileName{0}", i)

pictureBox.Image = Image.FromFile(file)



next i
kevin
2014-02-25 09:41:29 UTC
dim myPictureBoxControl(41) as picturebox



for i=0 to 41



'INITIALISE CONTROL

myPictureBoxControl(i) = new picturebox



'SET PROPERTIES OF CONTROL

myPictureBoxControl(i),Name =

myPictureBoxControl(i). image = image.fromFile( )

myPictureBoxControl(i).location = new system.drawing.point( xposition , ypostion )



next



:) Something along those lines is what you need


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...