I’ve got a vey simple form with a grid of 16 labels, each of which I wish to set the Background color at random from 12 colors I have chosen.
Here is my code:
private void btnRandom_Click(object sender, EventArgs e)
{
txtA1.BackColor = RandomColor();
txtA2.BackColor = RandomColor();
txtA3.BackColor = RandomColor();
txtA4.BackColor = RandomColor();
txtB1.BackColor = RandomColor();
txtB2.BackColor = RandomColor();
txtB3.BackColor = RandomColor();
txtB4.BackColor = RandomColor();
txtC1.BackColor = RandomColor();
txtC2.BackColor = RandomColor();
txtC3.BackColor = RandomColor();
txtC4.BackColor = RandomColor();
txtD1.BackColor = RandomColor();
txtD2.BackColor = RandomColor();
txtD3.BackColor = RandomColor();
txtD4.BackColor = RandomColor();
}
private Color RandomColor()
{
Random rand = new Random();
int r = rand.Next(1, 12);
switch (r)
{
case 1:
return Color.FromKnownColor(KnownColor.DodgerBlue);
case 2:
return Color.FromKnownColor(KnownColor.MediumAquamarine);
case 3:
return Color.FromKnownColor(KnownColor.Teal);
case 4:
return Color.FromKnownColor(KnownColor.OrangeRed);
case 5:
return Color.FromKnownColor(KnownColor.LightCoral);
case 6:
return Color.FromKnownColor(KnownColor.Red);
case 7:
return Color.FromKnownColor(KnownColor.MediumOrchid);
case 8:
return Color.FromKnownColor(KnownColor.MediumPurple);
case 9:
return Color.FromKnownColor(KnownColor.DarkOrchid);
case 10:
return Color.FromKnownColor(KnownColor.Lime);
case 11:
return Color.FromKnownColor(KnownColor.PaleGreen);
case 12:
return Color.FromKnownColor(KnownColor.SeaGreen);
default:
return Color.FromKnownColor(KnownColor.White);
}
}
But what is happening is that ALL 16 labels are assigned the same backcolor, rather than each being randomized individually.
What am I doing wrong?
Probable cause of the issue
It because you are creating
Randomobject each time theRandomColor()method is called and call it few times almost at the same time.Explanation
When you write
new Random();the pseudorandom function is initiated with a seed based on a current time. Seed is a value that determines the values returned by theRandomobject (values of pseudorandom function). This means that when you create twoRandomobjects with the same seed, they return the same values in the subsequentNext()method.In your case you are calling the method few times, so the seed may be the same and that’s why it returns the same value for all the labels.
Suggested solution
In order to fix it, move
Random rand = new Random();outside the method, to be created only once for a class instance.