Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I just started programming, and I want to use WinForms to make multiple buttons that you can click on to change from white to lime-green and back to white. I have done this for one button:

private void button1_Click(object sender, EventArgs e)
    {
        if (button1.BackColor != Color.Lime)
        {
            button1.BackColor = Color.Lime;
        }
        else
        {
            button1.BackColor = Color.White;
        }
    }

Now I could copy and paste that for all of the buttons, but I know that is inefficient; and if I use winforms to reference button1 on button2, it will just change the color of button1 (obviously).

So, do I need to use a helper method, new class, or something else? What would that look like?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
227 views
Welcome To Ask or Share your Answers For Others

1 Answer

There are a couple of approaches. One might be to create a common function which the different buttons call:

private void button1_Click(object sender, EventArgs e)
{
    ChangeColor(button1);
}

private void ChangeColor(Button button)
{
    if (button.BackColor != Color.Lime)
        button.BackColor = Color.Lime;
    else
        button.BackColor = Color.White;
}

Then each button handler can use that same function call.

Or, if all of these buttons will always ever do exactly the same thing, then you can use one click handler function for all of them. In this case what you'd need to do is determine which button invoked the handler (whereas you're currently referencing button1 directly) so that you know which one to change. The sender object passed into the handler function is actually a reference to the form element which invoked the handler. All you need to do is cast it:

private void button_Click(object sender, EventArgs e)
{
    var button = (Button)sender;
    if (button.BackColor != Color.Lime)
        button.BackColor = Color.Lime;
    else
        button.BackColor = Color.White;
}

So first the handler grabs a reference to the button which invoked it, then runs the logic on that button. Note also how I made the name of the handler function slightly more generic. Now you'd go to the form designer and set button_Click as the click handler for all of the buttons which should invoke this.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...