Using the WithEvents Statement

Using the WithEvents Statement

If you declare a variable using the WithEvents statement, the handlers for the events associated with the type of the variable can be generated by selecting the object in the class name list and the events in the method name list. Here's an example in case you're not familiar with the WithEvents statement.

 Private WithEvents MyButton As Button 

When the variable has been declared, the name will show up in the class name list. Based on the preceding code statement, MyButton will be in the method name list, and when you select MyButton , the method name list will include all the events associated with the Button type. By picking the Click event, for instance, the Click event handler will be generated.

You will still need to construct an instance of MyButton , but the Click handler will be associated with the control when MyButton is created. The following fragment demonstrates how to dynamically create the Button control.

 MyButton = New Button() MyButton.Text = "Click Me!" Controls.Add(MyButton) 

These three statements construct an instance of the Button class, set the Text value for the button, and add the button to the form's Controls collection. The last step is imperative; if you forget this step, messages won't get sent from the form to the button.

You can use the WithEvents statement and the Handles clause to define and associate event handlers at design time ”when you are coding ”or you can use AddHandler and RemoveHandler statements to manage event handlers dynamically at runtime.


Use a WithEvents statement and a Handles clause together, or use the AddHandler statement ”but don't use both options at once.

Visual Basic. NET Power Coding
Visual Basic(R) .NET Power Coding
ISBN: 0672324075
EAN: 2147483647
Year: 2005
Pages: 215
Authors: Paul Kimmel © 2008-2017.
If you may any questions please contact us: