【问题标题】:C# Windows Form Coloring Random ButtonC# Windows 窗体着色随机按钮
【发布时间】:2016-08-27 15:02:45
【问题描述】:

下面问号的地方应该写什么?每次改变一个按钮的颜色。

我可以保留列表中的名称,但我不能按背景颜色。

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();                 
}

【问题讨论】:

  • 你为什么在意这个名字?您拥有控制权,只需为其分配背景颜色。这是一个简单的属性分配。

标签: c# windows forms


【解决方案1】:

你需要设置按钮的BackColor property,不需要关心Name

buttonList[rndNumber].BackColor = Color.Red;

【讨论】:

    【解决方案2】:

    创建原始背景颜色:

     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);
            }
        }
    

    要在创建按钮后更改背景颜色,请将以下内容添加到 buttonClick 方法中:

    private void buttonClick(object sender, EventArgs e)
        {
            Button b = (Button)sender;
            b.BackColor = System.Drawing.Color.AliceBlue;
        }
    

    要更改您命名的按钮的背景颜色,请使用:

    private void changeColor(string buttonName,System.Drawing.Color newColor)
        {
            Button b = (Button)Controls.Find(buttonName, true)[0];
            b.BackColor = newColor;
        }
    

    【讨论】:

      猜你喜欢
      • 2012-03-02
      • 1970-01-01
      • 2013-06-05
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 2020-09-21
      • 1970-01-01
      相关资源
      最近更新 更多