0

I want to randomly change the background colour of a picture box control. What I have is

Random Rand = new Random();
int randNum = Rand.Next(1,3);
string boxName = "pic" + randNum.ToString();
PictureBox picBox = new PictureBox();
picBox.Name = boxName;

picBox.BackColor = Color.White;

And it doesn't work. I know that picBox.Name = boxName doesn't actually set picBox to that picture box, but it's the only code that wouldn't give some intellisense error.

I have 3 picture boxes, pic1, pic2, and pic3. This is done on a button click, hence random num between 1 and 3.

I tried to apply Choosing random places in C#, but I couldn't get it to work, could anyone help?

Community
  • 1
  • 1
Daevin
  • 778
  • 3
  • 14
  • 31
  • 1
    You need to keep (or put) all of your `PictureBox`es in a list or array, then get a random number to select one from that list/array. – Jonathon Reinhart Oct 23 '13 at 00:31
  • if you want to load real images then you need to create a BitMap object from the file (there is a constructor that takes a file name) and then assign that image to the .BackgroundImage of the PictureBox object – pm100 Oct 23 '13 at 00:42

2 Answers2

4

Create an array of PictureBox:

var boxes = new [] { pic1, pic2, pic3 };

and use it when selecting random one:

var picBox = boxes[Rand.Next(0, 3)];

Note: You have to draw from 0 (included) to 3 (excluded), because arrays are indexed from 0.

Than you'll have a random PictureBox assigned to your picBox variable, so you can change the background:

picBox.BackColor = Color.White;
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
4

Why not simply store the colours in an array and change the background colour at random? No need to recreate a picture box.

Color[] colours = new Color[] { Color.White, Color.Black, Color.Blue, Color.Red }; //etc
Random Rand = new Random();
int randNum = Rand.Next(0, colours.Length);

And then to assign the colour:

picBox.BackColor = colours[randNum];
codemonkeh
  • 2,054
  • 1
  • 20
  • 36
  • 1
    This actually answers the question! – Razor Oct 23 '13 at 00:36
  • I was confused for a minute, then realized I wasn't clear in my question... I want the colour predefined, and the randomization being on the picture boxes, i.e. out of the 3 picboxes, a random one has the colour change. – Daevin Oct 23 '13 at 00:41
  • @Edper as per MSDN "A 32-bit signed integer greater than or equal to zero, and less than maxValue" Where maxValue in this case is the Length. – codemonkeh Oct 23 '13 at 00:44
  • @Daevin Ah in that case MarcinJuraszek's answer should be more accurate – codemonkeh Oct 23 '13 at 00:45
  • @codemonkeh you're right (and my bad) I normally get confused the length/size as max value for random numbers. – Edper Oct 23 '13 at 00:53
  • @Edper Easy to do, I had to check the spec to be sure! – codemonkeh Oct 23 '13 at 01:37