简体   繁体   中英

Change last clicked button properties c#

In my form i have about 36 buttons and for each i have the following code

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

which means I will have this code x 36 times, I want to make a method that does this but I dont know how to change last clicked buttons properties, i want something like this :

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

How can i tell change_properties method that it should work with button3 in case it was clicked?

You can send the button as a parameter to the method -

change_properties(Button lastClickedButton)

And then use this parameter to do what you want.

If what you do with your 36 buttons are identical, then for each of your Button.Click events (likely declared in your designer.cs file), refers it to a single 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

And then in your event handler, convert the sender object to Button class by using as 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
}

If it is not, then just leave the declarations of the event handler but make the button as the input for your change_properties method

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM