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

Categories

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

visual studio 2010 - Event for Click in any button (C# windows forms)

I'm developing a program that has many buttons that should do a similar action when clicked, but with a small difference based on which button was clicked. The problem is that the only straightforward path is to code this for each button, which would be a very repetitive task. Is there a way to program simply one block that would get the click on any button and which button was clicked?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Assign the same event handler to all buttons.

foreach (var button in Controls.OfType<Button>()) {
    button.Click += button_Click;
}

Or you can select the same event handler in the properties window switched to events (flash icon).


private static void button_Click(object sender, EventArgs eventArgs)
{
    switch (((Button)sender).Name)
    {
        // find a way to disambiguate.
    }
}

You can also add some useful information to the Tag property for the disambiguation. And last but not least, you can derive your own button from Button and add appropriate properties. They will even appear in the properties window.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...