MOCKSTACKS
EN
Questions And Answers

More Tutorials




Setting multiple buttons to one event handler in C#

To let multiple buttons have the same event handler, we can set the Click property of of every button as a new EventHandler() and pass the method to call for all events as a parameter, in below example we create 1 method called b1_Click(), and we created a new event handlers using that method new EventHandler(b1_Click);

Example

public partial class Form1 : Form
    {
        TextBox t = new TextBox();
        Button b1 = new Button();
        Button b2 = new Button();
        public Form1()
        {
            InitializeComponent();
            t.Location = new Point(0, 0);
            this.Controls.Add(t);

            b1.Location = new Point(12, 50);
            b2.Location = new Point(12, 100);
            b1.Name = "b1";
            b2.Name = "b2";
            b1.Click += new EventHandler(b1_Click);
            b2.Click += new EventHandler(b1_Click);

            this.Controls.Add(b1);
            this.Controls.Add(b2);
        }

        void b1_Click(object sender, EventArgs e)
        {
            Button b = (Button)sender;
            t.Text = b.Name;
        }
    }

Conclusion

In this page (written and validated by ) you learned about Setting multiple buttons to one event handler in C# . What's Next? If you are interested in completing C# tutorial, we encourage you simply to start here: C# Tutorial.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.