To display specific pictures i've used the code below

PictureBox1.Image = Image.FromFile(FILEPATH")

but how can I code it so a random file of a photo is displayed instaed?

Recommended Answers

All 7 Replies

In psuedocode something like.

  1. Get the list of files in an array.
  2. Use a random number from 1 to the number of files.
  3. That line of code would be used and for the filename would be from the array with the index being the random number in psuedocode line 2.

Would it be possible if you could provide me with a code example because I'm new to programming .

To save you from the "gotcha" (thoughtfully provided by Microsoft), the Next method of the random number class can be called with parameters MinValue and MaxValue as in


The gotcha is that that some brain dead programmer at Microsoft decided that the MinValue is inclusive and MaxValue is exclusive so MaxValue is actually one greater than then largest value you want returned - rnd.Next(0,20) will return a random number from 0 to 19.

Thanks Microsoft.

commented: +1 for instructions unclear. +8

@Khw09, I'm going with no. If a new programmer learns how to get others to write code for them, then they won't learn how to research and code.

For example in step 1 of the psuedocode I could google "How to get a list of filenames into an array in Visual Basic?" Seems that folk have done that. You as an aspiring programmer must learn to research. That I will help with by providing what search phrases if you can't find the right words.

To find files use the DirectoryInfo.GetFiles method. It returns an array of FileInfo objects. Use the Random class to generate a number that can be used as an index for the FileInfo array. Becareful to specify an index that is within bounds.

Selecting pictures at random will mean that occasionally you'll see one appear multiple times in succession, which might not be quite what you're expecting. If that's the case you'll need to have a think about defining your algorithm to prevent this from happening - a trivial problem which I'll leave for you to figure out. Have fun.

Thanks i got it working now but i got another question.

I got an excel file with a list of names and i can generate a random name from the list with a use of a button but if I had more than 1 column e.g.first name and telephone number in my excel file,how can i seperate the 2 columns and only read from 1 column e.g.first name, so I can still generate a random name with out the phone number showing.

@Khw09. It's been generally accepted that if you have a new question you start a new discussion. I found no mention of Excel in your top post and question.

When you post your new question, show what you tried along with the version Excel and your code so far.

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.