Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

c# - How do I make buttons do the same thing?

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...