Event for Click in any button (C# windows forms)

前端 未结 4 1392
广开言路
广开言路 2020-12-21 03:35

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 t

4条回答
  •  情深已故
    2020-12-21 04:15

    Create a button click handler by double-clicking one of the buttons. But instead of doing the same with the other buttons, go to the properties window and switch to events view. Now select each one of the remaining buttons in turn and choose the just created click handler from the drop down list of the Click event of the other buttons in the properties Window. Now they all trigger the same method when they are clicked.

    enter image description here

    private void button1_Click(object sender, EventArgs e)
    {
        var btn = (Button)sender;
        switch (btn.Name) {
            case "button1":
                ...
                break;
            case "button2":
                ...
                break;
            case "button3":
                ...
                break;
            default:
                break;
        }
    }
    

    Or you can define a value for the Tag property of the buttons in the properties window and use it directly without having to use a switch- or if-statement.

    You can also test for specific buttons directly with sender == button1, but this does not work in a switch statement.


    It might be easier to create your own button deriving from Button and to add the required properties. Once compiled, your button appears in the Toolbox and your properties can be set in the properties window.

    public class MyButton : Button
    {
        public int A { get; set; }
        public int B { get; set; }
    }
    

    Usage:

    private void button1_Click(object sender, EventArgs e)
    {
        var btn = (MyButton)sender;
        DoSomething(btn.A, btn.B);
    }
    

提交回复
热议问题