6.5. The Structure of a Visual Basic ProgramBroadly speaking, programs can be either procedure-driven or event-driven . In a procedure-driven program, program flow is predefined. A classic example is a console application: program flow begins at the program entry point (the Main routine) and proceeds along a predictable path until it reaches program termination. But in an event-driven program, program flow is not predetermined and is instead controlled by external eventsevents initiated by both the user and the systemand possibly by internal code-specified events. Both types of applications include a starting entry point (the Main routine), which can call other functions and subroutines according to the logic needed in the application. Procedure-driven applications are limited to this single entry point. But event-driven applications include many entry points throughout their lifetime (beyond the initial Main entry point). These entry points are event handlers, which are invoked automatically by the .NET Common Language Runtime in response to user, system, or internal application actions. The different procedures in your application can be grouped into three broad categories.
6.5.1. Events: The Starting PointEvents can be system generated (such as with Timer control events that trigger actions at a specific time or interval) or user generated (as through a mouse click on a command button). You can also include code that forces an event to fire as needed. For instance, a stock monitoring application might generate a Positive event when a stock's value goes up and a Negative event when its value decreases.
6.5.1.1. Windows Forms eventsWindows Forms classes include many special events that fire during the creation and destruction of a form instance. These events appear in the following order:
Other form-specific events occur while the form is active on the display. Individual controls also expose events. 6.5.1.2. ASP.NET eventsASP.NET exposes a more complex event model, in which events can be trapped at the application, session, and page level. Table 6-1 illustrates the sequence of application, session, and page events for an ASP.NET application.
Individual controls also expose events . 6.5.1.3. Event argumentsWhen an event is fired, the CLR passes two arguments to the event handler:
Example 6-2 shows an event handler for a command button's Click event in a Windows Forms application. Example 6-2. A command button's event handler
When the event is fired, the dialog box shown in Figure 6-2 appears. Figure 6-2. A dialog box displaying event informationThe EventArgs class itself has no useful members; all of its members are inherited from the System.Object class. Most event handlers are passed an instance of the EventArgs class, although events with additional useful information to convey will pass an object derived from EventArgs, with the extra informational members added. For example, the Button and ImageButton controls in the System.Web.UI.WebControls namespace raise a Command event that is fired when the control is clicked. Instead of an instance of the EventArgs class, the CLR passes the event handler an instance of the CommandEventArgs class. It has the following properties:
In some cases, an event's default action can be cancelled. For instance, the CancelEventArgs class (derived from EventArgs) has a Cancel property that, when set to true, cancels the pending action related to the event. 6.5.2. Calling Routines from Event HandlersOnce processing has been directed to one of your event handlers, it's time to do some work. Of course, you can write every bit of processing code right there in the event-handling routine, but for readability, a divide-and-conquer approach often works better. An event handler can call methods, functions , and procedures, and can set and retrieve property values, all from classes in your own application or from the .NET Framework Class Library. In Example 6-3, the SaveAllData command button's Click event demonstrates this approach to event handling by calling SaveDetails, a method in some other part of the code, to do most of the work. Example 6-3. Calling an external routine from an event handler
The SaveDetails method contains all the code to actually save the details, and it can be called from anywhere in the class (or from other classes, if it is public). Placing code in custom procedures not only improves readability of the code, it centralizes the work, making it possible to use the same collection of source code statements from multiple places in your application. 6.5.3. Writing Custom ProceduresCustom procedures can be added to any class, structure, or module in your application. Visual Basic includes three main types of custom procedures or routines: Functions, Sub procedures, and Properties. 6.5.3.1. FunctionsA function is a collection of related statements and expressions used to perform a particular task. When it completes execution, the function returns a value to the calling routine. If you don't specify an explicit return value for the function, the default value of the return data type is used. If you write a custom function in a class module and declare it as Public, it becomes a class method. Consider the following simple function, which returns a String data value. Public Function PrepareForSQL(ByVal origText As String) As String ' ----- Prepare a string for use in a SQL statement. Any ' single quotes must be doubled-up. If (Len(origText) = 0) Then Return "NULL" Else Return "'" & Replace(origText, "'", "''") & "'" End If End Function Because functions return values, you can use them as part of an expression in place of a variable or literal value. The following statement includes a custom function as an argument to the VB InStr function. If (InStr(GetCustomerStatusCodes(customerID), "P") > 0) Then This statement is equivalent to this more verbose variation: Dim statusCodes As String statusCodes = GetCustomerStatusCodes(customerID) If (InStr(statusCodes, "P") > 0) Then Functions include zero or more arguments, values or references that are passed to the function call for use in that function. For instance, the statement: statusCodes = GetCustomerStatusCodes(customerID) passes the variable customerID to the function. Each argument is of a certain data type, as defined in the parameter list of the function's definition. Public Function GetCustomerStatusCodes( _ ByVal customerID As Long) As String For full details on the syntax and use of functions, see the entry for the "Function Statement" in Chapter 12. 6.5.3.2. Sub proceduresA Sub procedure is used just like a function, except it does not return a value. Event handlers are, by definition, Sub procedures, since they do not return values. As with functions, if you write a custom Sub procedure in a class module and declare it as Public, it becomes a class method. For full details of the syntax and use of Sub procedures, see the entry for the "Sub Statement" in Chapter 12. 6.5.3.3. PropertiesProperties are specialized procedures used to assign and retrieve custom property values. When accessed through code, they look like public variables or constants of a class (fields), but they include logic in their data setting and retrieval code. Properties have two parts.
Properties can be defined as ReadOnly or WriteOnly; when defined with one of these restrictions, the applicable component (Get or Set) is left out of the property definition. Example 6-4 defines a simple class with a single property. Example 6-4. A property
While the Name member of the Person class could have just been a public variable for simplicity, using a property made it possible to check for invalid use (an empty name value, in this case). Internally, properties are implemented as methods. Visual Basic implements each property accessor as a get_propertyname method, while each mutator is implemented as a set_propertyname method. New in 2005. Normally, the Get and Set components of the Property statement share the same level of accessibility (that is, they both are Public, Friend, or Private). Visual Basic 2005 allows you to specify different access levels for the Get and Set components. For full details of the syntax and use of Properties, see the entry for the Property Statement in Chapter 12. |