Export (0) Print
Expand All

How to: Call a Button's Click Event Programmatically

Visual Studio 2008

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

  1. On the File menu, click New Project.

  2. In the New Project dialog box, in the Templates pane, click Windows Forms Application, and then click OK.

    A new Windows Forms project opens.

  3. From the Toolbox, drag two Button controls onto the form.

  4. In the form, double-click the first button (button1) to create the Click event handler.

  5. In the button1_Click event handler, type the following line of code.

    MessageBox.Show("button1.Click was raised.");
    
  6. Right-click the code, and then click View Designer.

  7. Double-click the second button (button2) to create the Click event handler.

  8. In the button2_Click event handler, type the following line of code.

    // Call the Click event of button1.
    button1.PerformClick();
    
  9. Press F5 to run the program.

  10. The program starts and the form appears. When you click either button1 or button2, the click event handler of button1 displays a message.

Community Additions

ADD
Show:
© 2014 Microsoft