Monday, February 25, 2008

Control Arrays
A control array is a list of controls with the same name. Therefore, instead of using four command buttons with four separate names, you can place a command button control array
on the form, and that control array holds four command buttons. The control array can have a single name, and you’ll distinguish the controls from each other with a subscript.

TIP: Use a control array if several controls on your form are to look and act similar to each other, such as multiple command buttons or two or more list boxes.

One of the best reasons to use a control array is that you can add the first control to your form and set all its properties. When you create a control array from that first control, all the
elements in the control array take on the same property values. You then can change those properties that need to be changed without having to set every property for every control individually.


Definition: A control array is an array of several controls that you reference with an Index property value that acts as the subscript. The controls in a control array must be the same
control type.


Control arrays have a lot in common with data arrays. A control array has one name, and you distinguish all the array’s controls from each other with the zero-based subscript. (The Index property holds the control’s subscript number.) All the control
array elements must be the same data type.


As soon as you place a control on a form that has the same name as an existing control, Visual Basic makes sure that you want to begin a control array by issuing the warning message: "you already have a control name "". Do you want to create a control array?"
The message box keeps you fromcaccidentally creating a control array when you actually want to add a different control. If you click the message box’s No button, Visual Basic uses a default control name for the placed control.

After you click 'Yes' , the name in the top of the Properties window becomes optColor(0) for the first control and optColor(1) for the second. The number inside the parenthesis is called an Index and is used to refer to the specific control within the array. All subsequent controls given the same name will automatically have an index attached.

Select Case Index
Case 0 'First button is selected
lblMessage. Forecolor=vbBlue
Case 1 'Second button is selected
lblMessage.Forecolor=vbBlack.
End select
End sub




Common Dialog Box
The common dialog box in visual basic is an insertable control that allows users to display a number of common dialog boxes in their program. These include Open and Save As file dialog boxes; the Find and Replace editing dialog boxes; the Print, Print Setup, Print Property Sheet, and Page Setup printing dialog boxes; and the Color and Font dialog boxes.


The Common Dialog Box Methods
To display a particular dialog box, your application must specify one of these methods:
ShowColor
ShowFont
ShowHelp
ShowOpen
ShowPrinter
ShowSave

Therefore, if your Common Dialog Box control is named cdbFile, your application can display the File Save dialog box with this statement:

cdbFile.ShowSave

Adding the File Dialog Boxes
To display a File Open dialog box, your application might contain the following statements:

cdbDialog.DialogTitle = "File Open"
cdbDialog.Filter = "*.txt" ` Show only text files
cdbDialog.FileName = "*.txt" ` Default filename
cdbDialog.ShowOpen ` Trigger the dialog box

All of the File Open dialog box buttons and list boxes have property names. Therefore, you can initialize the File Open dialog box to have any default value that best matches your application's needs. When the user selects from and closes the dialog box, your application will have to test the dialog box's FileName and IntDir properties to locate the file the user selected.

To display a File Save dialog box, your application might contain the following statements:

cdbDialog.DialogTitle = "File Save"
cdbDialog.Filter = "*.*" ` Show all files
cdbDialog.FileName = "test.txt" ` Default filename
cdbDialog.ShowSave ` Trigger the dialog box

Notice that the methods at the end of these last two code fragments have triggered the dialog box's display for the user.

The Color Dialog Box

To display a Color dialog box, you only need to change the DialogTitle property and issue the correct method, like this:

cdbDialog.DialogTitle = "Select a Color"
cdbDialog.ShowColor ` Display the dialog box

The dialog box's Color property will hold the selected color when the user closes the dialog box and your code regains control. You can assign this Color property to other Visual Basic properties that require color values.

The Font Dialog Box
To display a Font dialog box, you only need to change the DialogTitle property, select a default font name and style if you want, set the kind of font to display, and then use the ShowFont method, like this:

cdbDialog.DialogTitle = "Font"
cdbDialog.FontName = "Arial"
cdbDialog.Type = cdlCFBoth
cmdDialog.ShowFont

The Type property is required, or you will cause the error shown in Figure 12.10. cdlCFBoth is a named literal you can use with the Font dialog box. The type cdlCFBoth tells Visual Basic to display the user's TrueType fonts as well as any printer and screen fonts that appear on the system.

The Printer Dialog Box
To display a Printer dialog box, you only need to change the DialogTitle property and use the ShowPrinter method, like this:

cdbDialog.DialogTitle = "Select a Printer"
cdbDialog.ShowPrinter

Exception or Error Handling

Visual Basic supports structured exception (error) handling, which allows the program to detect and possibly recover from errors during execution. Visual Basic uses an enhanced version of the Try...Catch...Finally syntax already supported by other languages such as C++. Structured exception handling combines a modern control structure (similar to Select Case or While) with exceptions, protected blocks of code, and filters.

Structured exception handling, which is the recommended method of error handling in Visual Basic, makes it easy to create and maintain programs with robust, comprehensive error handlers. Unstructured exception handling using On Error can degrade application performance and result in code that is difficult to debug and maintain.

Introduction to Exception Handling
Visual Basic supports both structured and unstructured exception (error) handling. By placing exception handling code in your application, you can handle most of the errors users may encounter and enable the application to continue running. You can use structured and unstructured error handling to plan for potential errors, preventing them from interfering with the application.


Consider using exception handling in any method that uses operators that may generate an exception, or that calls into or accesses other procedures that may generate an exception.
If an exception occurs in a method that is not equipped to handle the exception, the exception is propagated back to the calling method, or the previous method. If the previous method also has no exception handler, the exception is propagated back to that method's caller, and so on. The search for a handler continues up the call stack, which is the series of procedures called within the application. If it fails to find a handler for the exception, an error message is displayed and the application is terminated.

A single method can contain either structured or unstructured exception handling, but not both.

Structured Exception Handling
In structured exception handling, blocks of code are encapsulated, with each block having one or more associated handlers. Each handler specifies some form of filter condition on the type of exception it handles. When an exception is raised by code in a protected block, the set of corresponding handlers is searched in order, and the first one with a matching filter condition is executed. A single method can have multiple structured exception handling blocks, and the blocks can also be nested within each other.
The Try...Catch...Finally statement is used specifically for structured exception handling.

Try' Starts a structured exception handler.

' Place executable statements that may generate

' an exception in this block.

Catch [optional filters]' This code runs if the statements listed in

' the Try block fail and the filter on the Catch statement is true.

[Additional Catch blocks]

Finally' This code always runs immediately before' the Try statement exits.

End Try' Ends a structured exception handler.

Unstructured Exception Handling
The On Error statement is used specifically for unstructured exception handling. In unstructured exception handling, On Error is placed at the beginning of a block of code. It then has "scope" over that block; it handles any errors occurring within the block. If the program encounters another On Error statement, that statement becomes valid and the first statement becomes invalid.

On Error GoTo Line
The On Error GoTo Line statement assumes that error-handling code starts at the line specified in the required line argument. If a run-time error occurs, control branches to the line label or line number specified in the argument, activating the error handler. The specified line must be in the same procedure as the On Error GoTo Line statement; otherwise, Visual Basic generates a compiler error. The following example illustrates the use of an error handler with a line label:

Sub TestSub
On Error GoTo ErrorHandler
' Code that may or may not contain errors.
Exit Sub

ErrorHandler:
' Code that handles errors.
Resume
End Sub

When to use Structured / Unstructured?
Structured exception handling is significantly more versatile, robust, and flexible than unstructured. If possible, use structured exception handling. However, you might use unstructured exception handling under these circumstances:


1. You are upgrading an application written in an earlier version of Visual Basic.

2. You are developing a preliminary or draft version of an application and you don't mind if the program fails to shut down gracefully.

3. You know in advance exactly what will cause the exception.

4. A deadline is pressing, you need to take shortcuts, and are willing to sacrifice flexibility for speed.

5. Code is trivial or so short that you only need to test the branch of code generating the exception.

6. You need to use the Resume Next statement, which is not supported in structured exception handling.


Types of Errors
In Visual Basic, errors (also called exceptions) fall into one of three categories: syntax errors, run-time errors, and logic errors.

Syntax Errors
Syntax errors are those that appear while you write code. Visual Basic checks your code as you type it in the Code Editor window and alerts you if you make a mistake, such as misspelling a word or using a language element improperly. Syntax errors are the most common type of errors. You can fix them easily in the coding environment as soon as they occur.

The Option Explicit statement is one means of avoiding syntax errors. It forces you to declare, in advance, all the variables to be used in the application. Therefore, when those variables are used in the code, any typographic errors are caught immediately and can be fixed.

Run-Time Errors
Run-time errors are those that appear only after you compile and run your code. These involve code that may appear to be correct in that it has no syntax errors, but that will not execute. For example, you might correctly write a line of code to open a file. But if the file is corrupted, the application cannot carry out the Open function, and it stops running. You can fix most run-time errors by rewriting the faulty code, and then recompiling and rerunning it.

Logic Errors
Logic errors are those that appear once the application is in use. They are most often unwanted or unexpected results in response to user actions. For example, a mistyped key or other outside influence might cause your application to stop working within expected parameters, or altogether. Logic errors are generally the hardest type to fix, since it is not always clear where they originate.


Using the MAPI Controls

The messaging application program interface (MAPI) controls allow you to create mail-enabled Visual Basic applications. MAPI is a set of core system components that seamlessly connect any mail-enabled or workgroup application to MAPI-compliant information services. For example, the Microsoft Exchange messaging system can be connected to most private or public e-mail systems through the use of MAPI drivers.


In Visual Basic, the MAPI controls are used to interact with the underlying message subsystem. To use these controls, you must first install a MAPI-compliant e-mail system like Microsoft Exchange. The underlying messaging services are provided by the workgroup environment — the Microsoft Exchange Server running under Windows 95 (or later) or Windows NT, for instance.


Using the MAPI controls involves two steps: establishing a MAPI session and then using various properties and methods to access and manage an individual Inbox. For example, create and send a message, include a file attachment, verify the recipient's address against the e-mail system's address book, etc.


The MAPISession control signs on and establishes a MAPI session. It is also used to sign off from a MAPI session. The MAPIMessages control contains all the properties and methods needed to perform the messaging system functions described above.


The MAPI controls are invisible at run time. In addition, there are no events for the controls. To use them you must set the appropriate properties or specify the appropriate methods.

Possible Uses
- To add messaging functionality to your application.
- To create a full-featured electronic mail application.


What Are Subroutines?

Subroutines can be thought of as miniature programs. A subroutine has a name attributed with it, much like a variable does. Unlike a variable, a subroutine doesn't hold data. Instead, it holds code. When the code in a subroutine is executed, the subroutine is said to be "called". Therefore, one subroutine can "call" another subroutine. Some subroutines are called automatically when certain actions are performed.

Why Use Subroutines?

Subroutines are useful because they eliminate redundancy. Consider a complicated program like a word processor. When certain actions are performed, such as closing the program, opening a file, or closing an individual file, the word processor would probably check to see if you had modified your document. If the user had modified the document since they opened it, the user would be prompted to save the file before performing the action. You could imagine that checking if the document was modified, prompting the user, and acting on the input would require many lines of code. If the programmer had literally typed this code into all of the places in the program where this check was to be made, it would still work fine. However, what would happen if the way the program handles documents changed, and therefore this code needed to be changed? The programmer would have to change the code in every place where this check was made. Even worse, what if the programmer changed the code in a few places but not in another? This would lead to bugs that are difficult to track down. Instead, if this code was put in a subroutine, the subroutine would simply be called from all of these places. If the code then needed to be changed, the programmer would only have to change it in one place; inside the subroutine. By doing this, subroutines eliminate redundant code, making the entire program easier to manage.

Creating A Subroutine

A subroutine begins with the word "Sub", followed by a space, then a name identifying the subroutine. Two parentheses follow, which are used for a parameter list.

Sub TestSub()

End Sub

After you enter the first line and press Enter, the second line will automatically be added for you. These lines represent the start and end of the subroutine. Any code inserted between these lines will be executed when the subroutine is called. A subroutine can be called in one of two ways: using the Call keyword, or by simply stating its name.

Sub TestSub()
MsgBox "Code in TestSub()"
End Sub

Private Sub Form_Load()
MsgBox "Code in Form_Load()"
TestSub / Call TestSub
MsgBox "Back in Form_Load()"
End Sub

Subroutine Scope
The declaration of a subroutine has an optional keyword that can be used before "Sub". You may enter a keyword representing scope here. "Private" and "Public" are examples of scopes. You may have noticed that the Form_Load subroutine has the word "Private" before "Sub". This declares that this subroutine has a Private scope. If you don't specify the scope of a subroutine, Visual Basic will use a default scope. You should never rely on default scope, however. Get in the habit of always explicitly declaring the scope of your subroutines.


What Is Scope?
In the context of subroutines, scope represents where in your program the subroutine can be called from. Subroutines with a Private scope can only be called from the source file from where they were defined. Subroutines with a Public scope can be called from anywhere in your program. For example, a subroutine with a Private scope in a form can not be called from another form, whereas it can if it has a Public scope.


Why Use Scope?
Why would you ever limit where you can call a subroutine from? Why wouldn't you make all subroutines Public so that there are no limitations on your program? Subroutine Scope is one of many tools that programmers can use to find bugs. If you know that your subroutine should never be called from a different source file, you should declare the subroutine to be Private. This will prevent you from making a silly mistake and calling this subroutine where it shouldn't be called. This will prevent mistakes that could be extremely damaging and hard to detect. Instead, your program will crash with an error rather than executing the subroutine with unpredictable results.

Parameters/ Arguments

Parameters, also called Arguments, are variables that can be "passed into" a subroutine. A subroutine with parameters looks like this:

Private Sub DisplayAdd(x As Integer, y As Integer)
MsgBox x + y
End Sub

Private Sub Form_Load()
DisplayAdd 5, 2
End Sub

A new subroutine has been declared called DisplayAdd. This declaration is different than the declarations that you have seen so far, however, as code has been added between the parenthesis. From your knowledge of variables, this syntax should look somewhat similar to you. x As Integer and y As Integer appear to be variable declarations without the "Dim" keyword. These declarations are separated by a comma. These variables are the Parameters for the DisplayAdd subroutine. Code within the subroutine can access x and y as usual, as if they were normal variables. However, when the subroutine is called, the calling subroutine will also provide values for these parameters. Therefore, the subroutine has now become dynamic. The code can act on input without caring where the input came from. When the Form_Load subroutine calls DisplayAdd with the parameters 5 and 2, the code within DisplayAdd is executed. The first line adds x and y together and displays the result. x and y have already been filled with the values 5 and 2 from the Form_Load subroutine. The calling subroutine doesn't have to use numeric constants, however. It can use variables as well:

Private Sub DisplayAdd(x As Integer, y As Integer)
MsgBox x + y
End Sub

Private Sub Form_Load()
Dim a As Integer
Dim b As Integer
a = 5
b = 2
DisplayAdd a, b
End Sub

ByRef and ByVal

Parameters can be sent to a subroutine By Reference (ByRef) or By Value (ByVal). ByRef is the default, and means that changes to the variable in the subroutine will result in changes to the source variable outside of the subroutine. ByVal literally copies the values of the variables from the calling subroutine into the called subroutine. By doing this, the variables can be changed, but their values will not change outside of the called subroutine. ByVal can also be a lot slower with large variable types, however, since memory has to be copied from one location to another. If you don't have any reason to do so, there is no need to pass variables ByVal. You can explicitly state the way that a variable is passed to a subroutine by using these keywords before the variable name. Using the ByRef keyword, one could write a Swap function, which switches the values of 2 variables.

Private Sub Swap(ByRef x As Integer, ByRef y As Integer)
Dim temp As Integer
temp = x
x = y
y = temp
End Sub

Private Sub DisplayVals(ByRef a As Integer, ByVal b As Integer)
'Don't worry about understanding the next line yet, it will be explained later
MsgBox "a = " & CStr(a) & vbCrLf & "b = " & CStr(b)
End Sub

Private Sub Form_Load()
Dim a As Integer
Dim b As Integer
a = 10
b = 12
'Display values, swap, and display again
DisplayVals a, b
'The next line is functionally identical to "Swap a, b"
Call Swap(a, b)
DisplayVals a, b
End Sub
Notice that Call was used instead of simply stating the subroutine name. When using the Call method however, you must use parenthesis when calling the subroutine. Note that this program would also have worked without typing "ByRef" anywhere, since it is the default. The ByRef and ByVal keywords are rarely used in simple programs, however, but it's a nice trick for your toolkit.

Functions

Subroutines have a close cousin called Functions. Functions are basically the exact same as subroutines, except that they return a value. That means that the function itself has a type, and the function will return a value to the calling subroutine based on the code that it contains. An example of this would be a function that adds two numbers, shown below. A function is declared the exact same way as a subroutine, except using the "Function" keyword instead of "Sub". To return a value, assign a value of the proper type to the function's name, as if it were a variable.

Private Function Add(ByVal x As Integer, ByVal y As Integer) As Integer
Dim Res as integer
Res = x + y
Add = Res
End Function

Private Sub Form_Load()
Dim a As Integer
Dim b As Integer
Dim c As Integer
a = 32
b = 64
c = Add(a, b)
MsgBox ("Sum is : " & c)
End Sub

No comments: