Visual Basic Concepts

Understanding Properties, Methods and Events

Visual Basic forms and controls are objects which expose their own properties, methods and events. Properties can be thought of as an object's attributes, methods as its actions, and events as its responses.

An everyday object like a child's helium balloon also has properties, methods and events. A balloon's properties include visible attributes such as its height, diameter and color. Other properties describe its state (inflated or not inflated), or attributes that aren't visible such as its age. By definition, all balloons have these properties; the settings of these properties may differ from one balloon to another.

A balloon also has inherent methods or actions that it might perform. It has an inflate method (the action of filling it with helium), a deflate method (expelling its contents) and a rise method (if you were to let go of it). Again, all balloons are capable of these methods.

Balloons also have predefined responses to certain external events. For instance, a balloon would respond to the event of being punctured by deflating itself, or to the event of being released by rising into the air.

Figure 3.1   Objects have properties, respond to events, and perform methods

If you were able to program a balloon, the Visual Basic code might look like the following. To set the balloon's properties:

Balloon.Color = Red
Balloon.Diameter = 10
Balloon.Inflated = True

Note the syntax of the code — the object (Balloon) followed by the property (.Color) followed by the assignment of the value (Red). You could change the color of the balloon from code by repeating this statement and substituting a different value. Properties can also be set in the Properties window while you are designing your application.

A balloon's methods are invoked like this:

Balloon.Inflate
Balloon.Deflate
Balloon.Rise 5

The syntax is similar to the property — the object (a noun) followed by the method (a verb). In the third example, there is an additional item, called an argument, which denotes the distance to rise. Some methods will have one or more arguments to further describe the action to be performed.

The balloon might respond to an event as follows:

Sub Balloon_Puncture()
   Balloon.Deflate
   Balloon.MakeNoise "Bang"
   Balloon.Inflated = False
   Balloon.Diameter = 1
End Sub

In this case, the code describes the balloon's behavior when a puncture event occurs: invoke the Deflate method, then invoke the MakeNoise method with an argument of "Bang" (the type of noise to make). Since the balloon is no longer inflated, the Inflated property is set to False and the Diameter property is set to a new value.

While you can't actually program a balloon, you can program a Visual Basic form or control. As the programmer, you are in control. You decide which properties should be changed, methods invoked or events responded to in order to achieve the desired appearance and behavior.