我有一个非常简单的表格,带有 16 个标签的网格,我希望从我选择的 12 种颜色中随机设置每个标签的背景颜色。
这是我的代码:
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);
}
}
但是发生的事情是所有 16 个标签都被分配了相同的背景色,而不是每个标签都被单独随机分配。
我究竟做错了什么?