Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))

Problem

You want the Click event handler for a button to run, but you want to initiate this action from code instead of waiting for the user to click the button.

Solution

Call the button's PerformClick() method:

Button1.PerformClick()

Discussion

While it's nice that the Button control has a PerformClick() method to run its Click event handler in an object-oriented manner, most controls and most control events have no such related method. If you wish to call an event handler immediately through code, you have to call it like any other method, passing the correct arguments:

' ---- Call the text box control's GotFocus handler. TextBox1_GotFocus(TextBox1, New System.EventArgs)

In this case, calling the TextBox1 control's GotFocus() event handler will run that handler's code, but it will not cause the focus to move to the text box. An even better solution would be to write a shared routine that the GotFocus() event handler and your other code both call.

Категории