How to: Call a Button's Click Event Programmatically
Even if a user does not click a button, you can raise the button's Click event programmatically by using the PerformClick method. The following example demonstrates how to call the click event of a button within a program. When button2 is clicked, the click event for button1 is also triggered.
To use buttons in a program
On the File menu, click New Project.
In the New Project dialog box, in the Templates pane, click Windows Forms Application, and then click OK.
A new Windows Forms project opens.
From the Toolbox, drag two Button controls onto the form.
In the form, double-click the first button (button1) to create the Click event handler.
In the button1_Click event handler, type the following line of code.
Right-click the code, and then click View Designer.
Double-click the second button (button2) to create the Click event handler.
In the button2_Click event handler, type the following line of code.
Press F5 to run the program.
The program starts and the form appears. When you click either button1 or button2, the click event handler of button1 displays a message.
Even if a user does not click a button, you can raise the button's Click event programmatically by using the PerformClick method. The following example demonstrates how to call the click event of a button within a program. When button2 is clicked, the click event for button1 is also triggered.
To use buttons in a program
On the File menu, click New Project.
In the New Project dialog box, in the Templates pane, click Windows Forms Application, and then click OK.
A new Windows Forms project opens.
From the Toolbox, drag two Button controls onto the form.
In the form, double-click the first button (button1) to create the Click event handler.
In the button1_Click event handler, type the following line of code.
- Code:
MessageBox.Show("button1.Click was raised.");
Right-click the code, and then click View Designer.
Double-click the second button (button2) to create the Click event handler.
In the button2_Click event handler, type the following line of code.
- Code:
button1.PerformClick();
Press F5 to run the program.
The program starts and the form appears. When you click either button1 or button2, the click event handler of button1 displays a message.