Section 6.5. The Structure of a Visual Basic Program


6.5. The Structure of a Visual Basic Program

Broadly 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.


Entry Point Code

This procedure type includes the primary entry point (the Main routine), as well as all event handlers needed to support the various events for which your application needs to act.


Custom Procedures

In these procedures, you often create the main functionality of your application. These procedures are called methods within your classes and modules.


Property Procedures

These procedures are generally used to get and set the internal values managed by a class.

6.5.1. Events: The Starting Point

Events 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.

For a discussion of events and the way in which procedures can be defined to handle events, see Chapter 8.


6.5.1.1. Windows Forms events

Windows Forms classes include many special events that fire during the creation and destruction of a form instance. These events appear in the following order:

New Constructor
Load Event
Activated Event
Shown Event (New in 2005)
Closing Event
FormClosing Event (New in 2005)
Closed Event
FormClosed Event (New in 2005)
Deactivate Event

Other form-specific events occur while the form is active on the display. Individual controls also expose events.

6.5.1.2. ASP.NET events

ASP.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.

Table 6-1. ASP.NET events

Event

Type

Description

Start

Application

Fired when the application starts. The event handler must reside in global.asax.

Start

Session

Fired when a user session is created. The event handler must reside in global.asax.

Init

Page

Fired when the page is initialized.

Load

Page

Fired when the page is loaded.

PreRender

Page

Fired when the page is about to be rendered.

Unload

Page

Fired when the page is unloaded.

Disposed

Page

Fired when the page is released from memory.

End

Session

Fired when a user session ends or times out. The event handler must reside in global.asax.

End

Application

Fired when an application ends. The event handler must reside in global.asax.


Individual controls also expose events .

6.5.1.3. Event arguments

When an event is fired, the CLR passes two arguments to the event handler:


sender

An object of type System.Object (or some more specific type) that represents the instance of the class raising the event


e

An object of type System.EventArgs, or of a type derived from System.EventArgs, that contains information about the event

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

 Option Strict On Imports Microsoft.VisualBasic Imports System Imports System.Drawing Imports System.Windows.Forms Public Class JustAButton    Inherits System.Windows.Forms.Form    Friend WithEvents ActionButton As Button    Private Sub New(  )       ' ----- Form constructor; add the child controls.       Dim x As Integer       Dim y As Integer       ' ----- Configure the button control.       ActionButton = New Button       x = CInt(Me.Width/2 - ActionButton.Width / 2)       y = CInt(Me.Height/2 - ActionButton.Height / 2)       Me.ActionButton.Location = New System.Drawing.Point(x, y)       Me.ActionButton.Text = "Event Information"       Me.Controls.Add(ActionButton)    End Sub    Public Shared Sub Main       ' ----- The application starts here.       Application.Run(New JustAButton)    End Sub    Private Sub ActionButton_Click(sender As Object, e As EventArgs) _          Handles ActionButton.Click       ' ----- This is the button's Click event handler.       MsgBox(sender.GetType.ToString & vbCrLf & _          e.GetType.ToString)    End Sub End Class 

When the event is fired, the dialog box shown in Figure 6-2 appears.

Figure 6-2. A dialog box displaying event information


The 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:


CommandName Property

The name of the command to be executed. It corresponds to the Button or ImageButton control's CommandName property.


CommandArgument Property

Any optional arguments passed along with the command.

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 Handlers

Once 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

 Private Sub SaveAllData_Click(sender As Object, e As EventArgs) _       Handles SaveAllData.Click    If SaveDetails(  ) Then       MsgBox("Data recorded successfully.", vbInformation)    Else       MsgBox("Error occurred while saving data.", vbCritical)    End If End Sub 

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 Procedures

Custom 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. Functions

A 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 procedures

A 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. Properties

Properties 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.


Property Accessor

Retrieves the value of a property, returning it to the caller. The accessor is defined through the property's Get component.


Property Mutator

Assigns a value to or modifies a property's value. The mutator is defined through the property's Set component.

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

 Public Class Person    Private theName As String    Public Property Name(  ) As String       Get          ' ----- Property accessor.          Return theName       End Get       Set(ByVal value As String)          ' ----- Property mutator.          If (Trim(value) <> "") Then             theName = value          Else             Throw New System.ArgumentException( _                "Missing name value.", "Name")          End If       End Set    End Property End Class 

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.




Visual Basic 2005(c) In a Nutshell
Visual Basic 2005 in a Nutshell (In a Nutshell (OReilly))
ISBN: 059610152X
EAN: 2147483647
Year: 2004
Pages: 712

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net