Assign Event to Multiple Controls, Windows forms and C#

Lets say that you want the same event to be triggered by multiple controls. You don’t want to have to rewrite the code for all the controls.

Here we’re going to use four buttons with one shared event that shows the name of the button that’s been clicked.

Firstly create a form (in this case Form1) and add four buttons (button1, button2, button3, button4)

Next we want the Event code that will display the name of the button clicked.

In the code behind Form1 add:

private void button_Click(object sender, EventArgs e)
{
    Button btn = (Button)sender;
    MessageBox.Show(btn.Name);
}

This code simply takes the sender object, allocates it to a Button variable btn, and then displays the button’s name.

Now all we need to do is allocate this code to the button click event of each button. To do this you need to edit the Form1.Designer.cs code. You will see code similar to below for each button:

// 
// button1
// 
this.button1.Location = new System.Drawing.Point(13, 13);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;

To this we need to add the definition for the button click event:

this.button1.Click += new System.EventHandler(this.button_Click);

This adds the this.button_Click event handler to the button1.Click event.

If you add this code to all four buttons (place each with the code section for the appropriate button):

this.button2.Click += new System.EventHandler(this.button_Click);
this.button3.Click += new System.EventHandler(this.button_Click);
this.button4.Click += new System.EventHandler(this.button_Click);

The button_Click event will be triggered no matter which button you click, passing the clicked button as the sender object. Therefore, each button, when clicked should display its own name.

Advertisements
This entry was posted in Programming and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s