Random out image for picture box c#

18,063

The first step would be to make a list of some sort to store all your images. You can either opt for a list of Images, or a list of their paths.

If you're using the Image route, you can create a list of images with List<Image> images = new List<Image>(); and add each image to it with images.Add(image); for each image.

If you're using the path route, you can create a list of paths with List<String> paths = new List<String>(); and add each image to it with paths.Add(path); for each path.

Then, when you're setting the picture box to a random image, you can generate a random number and pick one out of the list.

For Images:

Random random = new Random();
pictureBox1.Image = images[random.Next(0, images.Count - 1)];

For paths:

Random random = new Random();
pictureBox1.ImageLocation = paths[random.Next(0, images.Count - 1)];

As Tuukka says, using paths is a much better idea (memory usage-wise), unless you've created the images dynamically, or already have the images for some other reason.

Share:
18,063
Kevin
Author by

Kevin

A guy in his early twenties learning how to code. From Oslo, Norway.

Updated on June 04, 2022

Comments

  • Kevin
    Kevin almost 2 years

    I'm working on a Winform where I have this picture box. I have 52 different images and only 1 image is going to be shown in this particular picture box. I'm not really sure how I should do this without ending up with 52 if statements. Could anyone help me with this as I'm still kinda new in programming :)

    I'm programming in c#

    Thank you! :D