Reputation: 95
What should I write where I put the question mark below? Each time to change the color of a button.
I can keep the names from the list , but I can not button the background color.
buttonList[rndNumber].Name ??? Back.Color = Color.Red;
int satir, sutun, minute, tik;
List<Button> buttonList = new List<Button>();
Random rnd = new Random();
private void timerRandom_Tick(object sender, EventArgs e)
{
int rndNumber = rnd.Next(0, satir*sutun);
// buttonList[rndNumber].Name ??? Back.Color = Color.Red;
// should change the color of the buttons I created below
}
int i = 0, j = 0;
private void btnStart_Click(object sender, EventArgs e)
{
panel.Controls.Clear();
switch (comboBoxLevel.Text)
{
case "1.Seviye":
satir = 5; sutun = 5; minute = 60000; tik = 5000;
break;
case "2.Seviye":
satir = 7; sutun = 7; minute = 120000; tik = 5000;
break;
case "3.Seviye":
satir = 9; sutun = 9; minute = 1800000; tik = 500;
break;
default:
break;
}
for (i = 0; i < satir; i++)
{
for (j = 0; j < sutun; j++)
{
Button btn = new Button();
btn.Name = "btn" + i + j;
// btn.Text = "Button" + i + " , " + j;
btn.Size = new Size(80, 60);
btn.Location = new Point(i * 80, j * 60);
btn.Click += buttonClick;
panel.Controls.Add(btn);
buttonList.Add(btn);
}
}
timerRandom.Interval = tik;
timerRandom.Start();
}
Upvotes: 1
Views: 860
Reputation: 2341
To create the original background color:
for (i = 0; i < satir; i++)
{
for (j = 0; j < sutun; j++)
{
Button btn = new Button();
btn.Name = "btn" + i + j;
// btn.Text = "Button" + i + " , " + j;
btn.Size = new Size(80, 60);
btn.BackColor = System.Drawing.Color.AliceBlue;
btn.Location = new Point(i * 80, j * 60);
btn.Click += buttonClick;
panel.Controls.Add(btn);
buttonList.Add(btn);
}
}
To change the background color AFTER you've created the button, add the following to your buttonClick method:
private void buttonClick(object sender, EventArgs e)
{
Button b = (Button)sender;
b.BackColor = System.Drawing.Color.AliceBlue;
}
To change the background color of a button you name, use:
private void changeColor(string buttonName,System.Drawing.Color newColor)
{
Button b = (Button)Controls.Find(buttonName, true)[0];
b.BackColor = newColor;
}
Upvotes: 0
Reputation: 174545
You'll want to set the BackColor
property of the button, no need to care about the Name
:
buttonList[rndNumber].BackColor = Color.Red;
Upvotes: 1