Section 2.2. The Structure of a VB Program

   

2.2 The Structure of a VB 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 (in the case of a .NET console application, it begins with the Main routine) and proceeds along a predictable path until it reaches program termination. In an event-driven program, on the other hand, program flow is not predetermined and is instead controlled by external events (i.e., by the program's interaction with the user and the system), and possibly by internal events as well.

From the perspective of program structure, the difference between procedure-driven and event-driven programs is less sharp than is usually thought. Both rely on a procedure as an entry point, which in turn can call other functions and subroutines that are visible to it. The major difference is that a procedure-driven program has a single entry point, whereas an event-driven program has multiple entry points. For event-driven programs, these entry points (in addition to the required Main procedure) are event handlers , which are invoked automatically by the .NET Common Language Runtime in response to an event within the code itself or in its environment.

Therefore, regardless of whether an application is procedure driven or event driven, Visual Basic code can be divided into three main categories:

Entry point code

For procedural applications, this code is a routine named Main . For an event-driven application, it is a routine named Main , supplemented by code that you write to handle events such as a button being clicked by the user. These latter procedures are called event handlers.

Custom procedures

In these procedures, you create the main functionality of your application. When these custom procedures are located within a class, they are termed methods and are typically used to perform an operation.

Property procedures

These procedures are used in form and class modules, typically to retrieve or set the value of a class attribute.

For the rest of this section, we'll discuss program structure by focusing on applications that fire events, which ultimately control program flow.

2.2.1 Events: The Starting Point

Aside from the obligatory Sub Main , which serves as the initial entry point for an application, an event provides an entry point into your code for any event-driven program. In other words, once the application is launched and the code in the application entry point has executed, an application can have numerous entry points that are invoked by the Common Language Runtime in response to particular events. An event can be system generated, such as the Load event of a form or a Timer control event, or it can be a user-generated event, such as the Click event on a command button. In can also be a custom event that you define in your code. For example, a stock monitoring application might generate a Positive event when a stock's value changes from negative to positive, and a Negative event when its value changes from positive to negative.

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

2.2.1.1 Windows Forms events

For a Windows Form application in which a form serves as the startup object, the order of execution of code is as follows :

The Main procedure
The New constructor
The Load event
The Activated event
The Closing event
The Closed event
The Dispose event

Individual controls also expose events.

2.2.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 2-1 illustrates the sequence of application, session, and page events for an ASP.NET application.

Table 2-1. ASP.NET events

Event

Type

Description

Start

Application

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

Start

Session

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

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.

End

Application

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

Individual controls also expose events.

For a full discussion of the events that fire when an object reference becomes null or when an application ends, see Section 4.3.8 in Chapter 4.

2.2.1.3 Event arguments

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

sender

An object of type Object that represents the instance of the class raising the event

e

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

For example, Example 2-6 shows an event handler for a Button object's Click event in a Windows application.

Example 2-6. A Button object's event handler
 Option Strict On Imports Microsoft.VisualBasic Imports System Imports System.Drawing Imports System.Windows.Forms Public Class CEvent    Inherits System.Windows.Forms.Form Friend WithEvents oBtn As Button Private Sub New(  )    oBtn = New Button    Dim x As Integer = CInt(Me.Width/2 - oBtn.Width / 2)    Dim y As Integer = CInt(Me.Height/2 - oBtn.Height / 2)    Me.oBtn.Location = New System.Drawing.Point(x, y)    Me.oBtn.Text = "Event Information"    Me.Controls.Add(oBtn) End Sub Public Shared Sub Main    Application.Run(New CEvent)    End Sub  Private Sub oBtn_Click(sender As Object, e As EventArgs) _                        Handles oBtn.Click    MsgBox(sender.GetType.ToString & vbCrLf & _           e.GetType.ToString) End Sub  End Class 

When the event is fired, the dialog shown in Figure 2-4 is displayed.

Figure 2-4. A dialog box displaying event information
figs/vnl2_0204.gif

The EventArgs class itself has no useful members; all of its members are inherited from the Object class. Most event handlers are passed an instance of the EventArgs class. Sometimes, however, the event handler is passed useful information about the event. In this case, the event handler's second parameter is an instance of a class derived from EventArgs; its added members provide information about the event. 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 by modifying the member of the class instance derived from EventArgs. For instance, the CancelEventArgs class is derived from EventArgs and is the base class of InputLanguageChangingEventArgs, TreeViewCancelEventArgs, and PrintEventArgs. By setting its Cancel property to True , you can cancel a pending application print job programmatically, cancel a change of language, or cancel the checking, expansion, collapse, or selection of a TreeView item.

2.2.2 Calling Routines from Event Handlers

An event handler, in turn, can call methods, functions, or procedures and can set and retrieve property values. These values can reside in the .NET Framework Class Library, or they can be custom functions in code modules or methods in custom classes that you wrote. For example, in Example 2-7, the Click event from a Button control named btnSave demonstrates this approach to event handling.

Example 2-7. Calling an external routine from an event handler
 Private Sub btnSave_Click(sender As Object, e As EventArgs) _                           Handles btnSave.Click Try    If SaveDetails(strFileName) Then       MsgBox("Details Saved OK", vbInformation)    Else       MsgBox("Details have not been saved", vbCritical)    End If Catch ex As Exception         MsgBox(ex.Message) End Try      End Sub 

Because the SaveDetails method contains all the code to actually save the details, the function can be called from anywhere in the class.

2.2.3 Writing Custom Procedures

Placing all code in event handlers is often inconvenient. Particularly when more than one event handler needs to execute the same code, it is preferable to write that code only once and call it from each event handler or any other routine that needs to access it. For this purpose, Visual Basic supports custom procedures. To create a new procedure, move to the bottom of the code window and type the Function or Sub definition before the End Module or End Class statement.

The three main types of custom procedures in Visual Basic include:

  • Functions

  • Sub procedures

  • Properties

2.2.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 statement. If you don't specify an explicit return value for the function, the default value of the return data type is returned. If you write a custom function in a class module and declare it as Public , it will become a class method.

Here's a quick example of a function used to provide a minimum number:

 Private Function MinNumber(ByVal iNumber As Integer) As Integer     If iNumber >= 500 Then         MinNumber = iNumber     Else         MinNumber = 500     End If      End Function 

Because functions return a value, you can use them as part of an expression in place of a value. In the following snippet, the string passed to the VB Instr function is a custom function that returns the customer name corresponding to a customer code:

 If InStr(1, GetCustomerName(sCustCode), "P") > 0 Then 

For full details on the syntax and use of functions, see the entry for the Function statement in Chapter 10.

2.2.3.2 Sub procedures

A Sub procedure is used just like a function, except it does not return a value and therefore cannot be used as part of an argument. Visual Basic uses Sub procedures to provide event handling.

Generally, you should use functions rather than Subs to create custom procedures. Functions allow you to return a value, which, minimally , could be a Boolean True or False , to inform the caller that the function has succeeded or failed. Tests indicate that there is no performance hit for coding a routine as a function instead of a procedure.

Like a function, if you write a custom Sub in a class module and declare it as Public , it will become a class method.

For full details of the syntax and use of Sub procedures, see the entry for the Sub statement in Chapter 10.

2.2.3.3 Property procedures

Property procedures are specialized procedures used to assign and retrieve custom property values. They can only be included in class definitions marked by the Class...End Class statement. Property procedures are defined within a Property ... End Property statement and can take either of two forms:

Property accessors

Retrieve the value of a property, returning it to the caller

Property mutators

Assign a value to or modify a property's value

Example 2-8, which defines a simple class with only one property, illustrates the syntax for property procedures.

Example 2-8. A property
 Public Class CPerson Dim sName As String Public Property Name As String    Get            ' Property accessor       Return sName    End Get    Set            ' Property mutator       sName = Value    End Set End Property End Class 

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. This implementation is evident in Figure 2-5, in which ILDASM displays two additional methods for the CPerson class that we created in Example 2-8, and Figure 2-6, in which ILDASM displays the IL for the Name property and shows that property references are resolved as separate calls to the get_Name and set_Name methods.

Figure 2-5. CPerson class members
figs/vnl2_0205.gif
Figure 2-6. IL for the Name property
figs/vnl2_0206.gif

2.2.4 Controlling Execution Flow

Now you've got your event handlers. These handlers will spring into life when the user clicks a button or a form loads. You've also written some useful functions that do all the work behind the scenes. How do you link the two together?

2.2.4.1 Calling sub and function procedures

Methods and functions or procedures can be called in one of two ways. In the case of a procedure, or in the case of a method or function whose return value is to be discarded, the Call statement can be used. Its syntax is:

 Call   routine   ([   argumentlist   ]) 

where routine is the name of the function, procedure, or a class or class instance along with the name of its method, and argumentlist is a comma-delimited list of arguments expected by the routine. The argument list must always be enclosed in parentheses. For example:

 Call Console.WriteLine("The Save operation completed successfully.") 

or

 Call SaveDetails(sFileName) 

The Call statement can also be omitted. If it is omitted, the syntax for a method or function whose return value is being stored to a variable is:

   retval   =   routine   ([   argumentlist   [) 

where retval is the function or method's return value, routine is the name of the function, procedure, or a class (or class instance along with its method), and argumentlist is a comma-delimited list of arguments expected by the routine. The argument list must always be enclosed in parentheses. The syntax for a method or procedure that does not return a value is:

   routine   ([   argumentlist   ]) 

Note again that the argument list must be enclosed in parentheses. This requirement contrasts with VB 6, which allows only a single parameter to be enclosed in parentheses in this instance.

2.2.4.2 Setting and retrieving property values

Property values can be set using a simple assignment statement with the property on the left side of the equals sign. The syntax is:

   object   .   property   =   value   

where object is the name of a shared class or an object instance, property is the property name, and value is the value to be assigned to the property. When dealing with property arrays (an array or collection of property values), an index into the property array is also required. The syntax is:

   object   .   property   (   index   ) =   value   

where index is the zero-based ordinal position of the property array element whose value is to be changed, or the key value if the property array supports access by keys.

Property values can also be retrieved by using a simple assignment statement with the property on the right side of the equals sign. The syntax is:

   value   =   object   .   property   

where value is the value of the property, object is the name of a shared class or an object instance, and property is the property name. When dealing with property arrays (an array or collection of property values), an index into the property array is also required. The syntax is:

   value   =   object   .   property   (   index   ) 

where index is the zero-based ordinal position of the property array element whose value is to be changed, or the key value if the property array supports access by keys.

   


VB.Net Language in a Nutshell
VB.NET Language in a Nutshell
ISBN: B00006L54Q
EAN: N/A
Year: 2002
Pages: 503

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