更改上次单击的按钮属性c#

本文关键字:按钮 属性 单击 | 更新日期: 2023-09-27 18:27:25

在我的表单中,我有大约36个按钮,每个按钮都有以下代码

        button3.BackColor = Color.DarkGreen;
        button_click("A1");
        button3.Enabled = false;
        nr_l++;
        textBox4.Text = Convert.ToString(nr_l);

这意味着我将有这个代码x 36次,我想做一个这样做的方法,但我不知道如何更改上次点击按钮的属性,我想要这样的东西:

    private void change_properties()
    {
    last_clicked_button.backcolor = color.darkgreen;
    button_click("A3"); //this is a method for adding A3 to a string,   
    last_clicked_button.enabled = false;
    nr_l++;
    textbox4.text = convert.tostring(nr_l);
    }
    private void button3_Click(object sender, EventArgs e)
    {
    change_properties();
    }

我如何告诉change_properties方法,如果它被点击了,它应该与按钮3一起工作?

更改上次单击的按钮属性c#

您可以将按钮作为参数发送到方法-

change_properties(Button lastClickedButton)

然后使用这个参数来执行您想要的操作。

如果您对36个按钮所做的操作相同,那么对于每个Button.Click events(可能在designer.cs文件中声明),将其引用到单个event handler

this.button1.Click += new System.EventHandler(this.button_Click); //notice the event name is the same
....
this.button2.Click += new System.EventHandler(this.button_Click); //notice the event name is the same
....
this.button36.Click += new System.EventHandler(this.button_Click); //notice the event name is the same

然后在事件处理程序中,使用as Buttonsender对象转换为Button

private void button_Click(object sender, EventArgs e)
{
    Button button = sender as Button; //button is your last clicked button
    //do whatever you want with your button. This is necessarily the last clicked
}

如果不是,那么只保留事件处理程序的声明,而将button作为change_properties方法的输入

private void change_properties(Button button)
{
    button.backcolor = color.darkgreen;
    button_click("A3"); //this is a method for adding A3 to a string,   
    button.enabled = false;
    nr_l++;
    textbox4.text = convert.tostring(nr_l);
}
private void button1_Click(object sender, EventArgs e) //the name of the event handler is unique per `Button` Control
{
    change_properties(sender as Button);
    //do something else specific for button1
}
....
private void button36_Click(object sender, EventArgs e)
{
    change_properties(sender as Button);
    //do something else specific for button36
}