按钮数组:更改属性

loo*_*kie 2 c# winforms

我有一系列按钮,如下所示:

int x = 0, y = 0;
butt2 = new Button[100];

for (int i = 0; i < 100; i++)
{
    butt2[i] = new Button();
    int names = i;
    butt2[i].Name = "b2" + names.ToString();
    butt2[i].Location = new Point(525 + (x * 31), 70 + (y * 21));
    butt2[i].Visible = true;
    butt2[i].Size = new Size(30, 20);
    butt2[i].Click += new EventHandler(butt2_2_Click); //problem lies here (1)
    this.Controls.Add(butt2[i]);
}

private void butt2_2_Click(object sender, EventArgs e)
{
    // want code here
}
Run Code Online (Sandbox Code Playgroud)

我想在点击时更改按钮的背面颜色.我想通过i能够做到这一点:

butt2[i].BackColor = Color.Green;
Run Code Online (Sandbox Code Playgroud)

nes*_*oop 8

这应该做的伎俩:

private void butt2_2_Click(object sender, EventArgs e) 
{
  Button pushedBtn = sender as Button;
  if(pushedBtn != null)
  {
     pushedBtn.BackColor = Color.Green;
  }  
}
Run Code Online (Sandbox Code Playgroud)

这适用于大多数UI事件,"对象发送者"参数指的是"发送"/"触发"事件的控件.

要了解有关C#事件处理的更多信息,我将从这里开始.

此外,这是关于GUI事件处理的SO问题,由Juliet很好地回答(接受的答案).

希望这可以帮助.

  • @lookie我用一些你可能觉得有用的链接编辑了我的答案.祝学习交易顺利:D. (2认同)