-2

I'm using visual studio community 2015 to make a form-based program that rolls two dice. I need to change out the picture depending on the Random number that I get.

The way I can do this is:

Random num = new Random();
int dice = num.Next(1,7);

if (dice == 1)     {
  pictureBox.Image = proj08.Properties.Resources._1;
} else if (dice == 2)    {
  pictureBox.Image = proj08.Properties.Resources._2;
} else if (dice == 3)    {
  pictureBox.Image = proj08.Properties.Resources._3;
} else if (dice == 4)    {
  pictureBox.Image = proj08.Properties.Resources._4;
} else if (dice == 5)    {
  pictureBox.Image = proj08.Properties.Resources._5;
} else if (dice == 6)    {
  pictureBox.Image = proj08.Properties.Resources._6;    }

This works perfectly and does just what I want, but it is very messy code. I would like to clean it up by doing something like:

Random num = new Random();
int dice = num.Next(1,7);
pictureBox.Image = proj08.Properties.Resources._dice;

but that doesn't work. I would also like to use the same code, even if the pictureBox is pictureBox1 or pictureBox2, so that I can use it for either of the dice.

leppie
  • 115,091
  • 17
  • 196
  • 297
Dawn
  • 19
  • 5
  • This question is about referencing resources more than it is about dice. At least mark it duplicate of something more appropriate like: http://stackoverflow.com/questions/1190729/vb-net-dynamically-select-image-from-my-resources – Crowcoder Jul 19 '16 at 18:39

1 Answers1

0

You can have a list of the images:

List<Image> images = new List<Image>()
{
   proj08.Properties.Resources._1,
   proj08.Properties.Resources._2,
   proj08.Properties.Resources._3,
   proj08.Properties.Resources._4,
   proj08.Properties.Resources._5,
   proj08.Properties.Resources._6
};

Random num = new Random();
int dice = num.Next(1, images.Count + 1);
pictureBox.Image = images[dice - 1]; // list starts from 0

This is the most straight-forward elegant way i can think of.

For multiple picture boxes, you can create a method passing the picture box as an argument and set its image property inside of it.

Zein Makki
  • 29,485
  • 6
  • 52
  • 63