Introduction
In the previous chapter, we studied how to develop a system using some system analysis and design methods without necessarily referring to any particular programming language. Therefore, we have been looking at what a system analyst ought to do rather than how a particular task should be done. In this chapter, we shall learn how to develop programs using Visual Basic programming language. Note that any other programming language can be used to develop programs. Therefore, as a leaner, you are at liberty to select any other programming language and learn how to use it to construct systems.
Definition of Visual Basic
Visual Basic (VB) is a graphical user interface programming language for creating software systems that run under Microsoft Windows environment. It is modeled in line with BASIC language which was originally created to help students learn how to program. Visual Basic has the following features:
- It is an event driven programming language. An event is a response generated by the program when the user performs an action e.g. a mouse click. The response depends on the code held in an event procedure. An event procedure is a group of self contained statements that are executed by the computer when a trigger action is performed. For example, a mouse click may cause a menu to be displayed on the screen.
- It has a collection of tools that are used by programmers. These tools are called The controls can be accessed easily by clicking their icons on the toolbox to select them.
- It has special objects called forms that have a title bar at the top. The programmer can then add controls such as a menu bar, status bar, toolbars, buttons, and slide bars to the form when creating an application.
Starting Microsoft Visual Basic
You can start Visual Basic from the Programs menu by pointing to Microsoft Visual Studio and then selecting Microsoft Visual Basic. Depending on the way the application has been setup, you may see the New Project dialog box
This dialog box allows you to set up a new project. You can set up several types of projects as shown by the different icons in this dialog box. However, for the purposes of learning, let us select the Standard.EXE project found on the New tab. Click the Open button. The application window will appear. This is the Visual Basic Integrated Development Environment (IDE).
Features of Visual Basic Integrated Development Environment (IDE) window
The Visual Basic application window (Figure 5.2) has many similarities to common windows based applications.
The following is a summary of the various features identified in the window:
The standard toolbar
Like in many other applications, the standard toolbar has the standard icons that are shortcut commands to the menu bar commands. Simply point to an icon and a text tip will appear telling you the name of the icon. Of great interest to us this time are the three commands of Start, Break and End.
To execute a Visual Basic project, simply click the Start button or select Start1from the Run menu. Execution of the program can be temporarily suspended by clicking the Break button. Resume the run by selecting Continue from the Run menu. Finally, the execution can be stopped by clicking the End button.
Forms and controls
Forms and controls are generally called objects. An object is usually associated with an event hence most objects have their own properties and methods. The properties define the appearance of the object while the method is a predefined action that can be set to occur or affect the object. For example show method makes a form visible on the screen.
The form design window is the place where the programmer does the actual design of the user interface for the program. This is accomplished by selecting the relevant control icons from the toolbox then placing them on the form design window. The control can then be moved and resized as desired by the programmer.
The entire form can be moved around on the screen by holding the title bar of the project container window then dragging it to the required position.
Project window
The project window displays a hierarchical list of files associated with a particular project. The files represent forms and program modules in the project. For example, Figure 5.2 shows a form whose title is Form 1.
Properties window
The properties window displays a set of various characteristics unique to each active object in the project. Some examples of properties include name, caption, colour, height etc.
When a new project starts, it is most likely that the form design window is active. In this case, the properties for the form will be displayed and can be changed by the programmer as appropriate. For example, we can change the caption of the form by clicking on the Alphabetic tab in the properties window then changing the value associated to Caption property from Form.l to say “Book Data Form”. Notice that the caption in the title bar of the active form changes simultaneously as you type the new name in the properties window.
Code editor window
Figure 5.2 shows that the project window has three icons at the top left hand comer. One of them is called the code view icon. Point to the icon with the mouse pointer and a tool tip will appear showing its name. If you click it, the code editor window opens displaying the code of the object that is currently selected. Alternatively, double click the object on the form for which you want to edit its code. The code editor window will open (Figure 5.4). In this case, we double clicked the form.
Form layout window
The form layout window allows you to specify the screen location of the form when the project is Executed. This can be done by dragging the form in this window to the desired location.
The Visual Basic toolbox
Visual Basic tool box has controls that enable a person to design and customise forms. Figure 5.5 depicts the toolbox.
Pointer: This is not actually a control but a tool used to select an object or objects to be worked on.
Picture box: A picture box is used to display graphical objects or text and to initiate event actions. It is similar to an image box but has more properties, redraws slower and cannot be stretched.
Label: A label displays text on a form. The text cannot be reassigned during program execution though its appearance can be altered.
Text box: A text box provides a means of entering or displaying text. The text may be already available or can be entered during the program execution.
Frame: A frame is a tool rather than a control used as a container for a group of controls. Command button: A control used to activate an event driven procedure.
Check box: As opposed to the option buttons a check box is used if more than one selection are to be made.
Option button: Option buttons are used when one selection must be made before an action is carried out. For example, if you want to turn off a computer running on Microsoft Window 9x, check the shut down option button then click Yes/OK.
Combo box: A combo box is a special type of list box that combines the capabilities of a text box and a list box. It provides a list of text items for selection by the user during program execution. Items can also be added during program execution.
List box: The list box control provides a list of text items for selection by the user.
Horizontal scroll bar: A horizontal scroll bar is used for drawing horizontal scroll bars on a form.
Vertical scroll bar: A vertical scroll bar is used for drawing vertical scroll bar on a form.
Timer: Timer control allows timed events to occur repeatedly at a specific time intervals.
Drive list box: A drive list box provides a means of selecting a drive from a list of existing drives.
Directory list box: A directory list box provides a way of selecting a directory from a list. File list box: A file list box provides a way of selecting files within a group of files.
Shape tool: A shape tool is used to draw circles, ellipses, squares and rectangles within forms.
Line tool: A line tool is used when drawing straight lines within forms. Image box: An image box control is used to display graphical objects.
Data control: A data control when placed on a form provides a means of displaying information from an existing database.
NB The number of tools available on the tool box depends on the edition and release of Visual Basic you are using
Saving a Visual Basic project
Saving a project in Visual Basic is a bit different compared to other applications. This is because Visual Basic operation involves saving multiple files.
1. To save a new Visual Basic project for the first time, select the Save project As command from the File menu. The Save File As dialog box of Figure 5.6 (a) appears. You will first have to enter a form name e.g. bookdata and then click the Save button. The form is saved as a file with extension .frm.
2. After this, the Save Project As dialog appears. Type the name of the project and it will be saved as a file with extension. vbp (Visual Basic project
Opening an existing project
You can open a project when Visual Basic starts or from the file menu. To open a project during startup, from the New Project dialog box that appears when Visual Basic is starting, click the Existing tab. A list of existing projects will be displayed as shown in Figure 5.7
1. Alternatively, if Visual Basic is already running, close all other projects then click the Open Project command on the File menu. The Open Project dialog box appears from which you can select the Existing tab. (Figure 5.7 (b)). Type the name of/or select the project to open.
Visual Basic fundamental concepts
Before going further into detailed discussion on how to develop programs in. Visual Basic, it is important to highlight some of the fundamental concepts used in Visual Basic.
Data types
Table 5.1 shows the data types supported by Visual Basic:
Constants
In programming, a constant is a value that remains the same. It does not change during the execution of the program. There are three types of constants: string, numeric and named constants.
String constants
A string constant can be defined as a sequence of characters enclosed in quotation marks. They are used to write non-numeric values like telephone numbers, addresses and names. The following are examples of string constants: “Holiday season”, “345678”, “Why don’t you call”, “$72.10”
Numeric constants
Numbers are usually referred to as constants in Visual Basic. In most cases, the numeric constants are either whole numbers (integer) or double or single. Some examples of numeric constants are:
0, 3, 6000 +70, 1.4E+2, 1.674, -.00456,
Named constants
A named constant is identified by name rather than its actual value. In Visual Basic, the reserved word Canst is used to declare this type of constants e.g. Canst Price As Integer = 20, means that an integer value 20 is identified using the name price.
Variables
A variable is a memory location referred to by name used to hold a value that is subject to change during program execution. When a variable is declared in a program, the computer sets aside memory space to hold a value in the variable. The variable may be a numeric constant, a character, a string or any other data item.
In Visual Basic, the following rules should be followed when declaring variables:
- The variable name must not have more than 255 characters.
- The variable name must start with a letter.
- The letter case is not important when declaring variables.
- A variable name must not be a reserved A reserved word is a special word that Visual Basic understands as a command, internal function name or simply set aside for use by the program. Examples of reserved words are Case, Else, Dim, etc.
- Variable names should not have spaces.
A variable is declared using the reserved word Dim. Dim is the short form of the word dimension (size). It is used to associate a variable with a specific data type. For example to declare a variable that will store the first name of a student in a program, the following declaration can be used:
Dim FirstName As String
This means that the variable FirstName is of the type string.
Variants
A variant is a variable whose data type has not been explicitly declared by the programmer. In this case, the variable type will be determined by the value held by the variant. These types of variables are called variant type because their data type keeps on changing with the values they hold. Although this may sound okay, it is not a good programming practice. All variables should be explicitly declared.
Scope
The word scope refers to the level of the program that a variable, a constant or a procedure is recognised. The scope of a variable constant is said to be global or local. The scope of a procedure variables or constants is set by declaring it as either private or public. The following terms are used in this regard:
- Private subprocedure.
- Public subprocedure.
- Global variables/constants.
- Local variables/constants.
A public procedure can be accessed from any module or form in the program. However, a private procedure is accessed in the module or form within which it is declared.
A variable or constant that is declared within a procedure is said to be local. This means that it can only be accessed within that procedure. However, a variable or constant that is declared outside the standard module but within the same project is said to be global. Such variables can be accessed by all procedures within the project.
If a public procedure is to be accessed from a module or a form other than the one it is contained in, the form or module name must be preceeded by the module containing the definitions i.e.
Global Module Name. Active Form Name (Arguments).
In Visual Basic, to declare variables as either private or public use the syntax:
- Private X As Integer
- Public Y As String
In the first declaration, the private variable X can only be accessed in the module within which it is declared. In the second example, it can be accessed by other subroutines in the same project.
User defined data types
Sometimes, a programmer may want to have a single variable that can store several data types as a unit. Such a data type whose individual components are standard data items are referred to as user defined data types. Some examples of user defined data types are records, arrays, enumerated types, lists etc. They are user defined because it is the programmer who creates them in the program. Each element or member can be accessed individually by using a period between the user defined variable and the member name e.g. if a record known as schoolrecord has a name field, then to access the name field, a programmer will type schoolrecord.name in the code.
Using suffixes to declare variables and constants
Suffixes are special symbols appended to the end of a variable or constant name in order to associate them with a particular data type. It makes programming easier and faster. Table 5.2 summarises some common suffixes.
Mathematical operators
In order to write correct mathematical expressions, you need to understand some of the operators used in Visual Basic. These include arithmetic, relational and logical operators.
Arithmetic operators
Arithmetic operators are special symbols that are used to write arithmetic expressions like addition, subtraction, division and multiplication. However, it is also possible to carry out other mathematical operations using other operators. Table 5.3 shows a summary of symbols used in arithmetic operations:
NB: The last two rows in the table can be explained as follows:
- In an integer division, each of the numbers being divided is first rounded to become an integer then the quotient is truncated to an integer. For example, 2.4/3.5 will result in 2/4 being evaluated.
- The MOD operator returns the remainder of an integer division. For example, 4 MOD 3 returns 1 and 5MOD3 returns 2.
Operator precedence/hierarchy
Arithmetic operators in Visual Basic have the following order of precedence when used in a program. Notice that the order may not be the same as that of algebra in mathematics. Table 5.4 illustrates how to carry out operations.
Relational operators
A relational operator is used in an expression that returns a true or false value when evaluated. The operators can compare numeric variables, constants or expressions. Table 5.5 shows a summary of relational operators used in Visual Basic. Table 5.5
A decision construct in a program based on a relational expression would make a decision depending on the outcome of the evaluation.
Logical operators
Logical operators are used to combine expressions to form compound expressions. Table 5.6 summarises some common logical operators used in Visual Basic.
The assignment statement
An assignment statement is an executable statement that assigns whatever is on the right of the assignment operator to the variable on the left. In Visual Basic, the assignment operator is the equal sign (=). A variable can be assigned a value as follows: Variable = Expression
Examples of assignment statements are:
- P = 0.25 2. E = M*C”2 3. Area = 1/2 * base* height 4. X = X + I
NB: The last statement on the right (X = X + I) does not make mathematical sense. Yet, this is the beauty of the assignment statement in programming. The statement can be interpreted as follows:
Add 1 to the original value of X and assign the sum to X.
The Print statement
The Print statement displays data on the active form of your Visual Basic project. It can be used to display processing results of a program. If you run the project, you will notice that the result of the Print statement starts being displayed in the top left comer of the form. The structure of the Print statement is:
Print VariableName (this prints out the value held in a variable). or
Print “String”
(this prints out the string between the two quotation marks. If there is nothing between the two quotation marks, a blank line will be the output)
The skeletal code listing below shows a sample code that displays the values stored in the variables StudentName, TotalMarks and AverageMark on a form.
Private sub Form_Load ( )
Dim StudentName As String, TotalMarks As Single, AverageMark As Single
…………
StudentName = “Edward”
TotalMarks = 1000 AverageMark = 200
……………
Print, StudentName, TotaIMc;zrks,AverageMark
End sub
The following output will be displayed on the form: Edward 1000 200
NB: The use of a comma to separate the various elements to be output by the Print statement makes them to be widely spaced on the screen. To have a compact display with the various outputs close to each other, then use a semicolon to separate the various elements e.g. Print
StudentName; TotalMarks AverageMark would display
Edward 1000 200
Library functions
Library functions are modules that have been pre-written and included in the Visual Basic language. A function performs a single task like calculating a mathematical expression then returns a value. A function will usually have a name and can be called when needed to perform a particular task. Visual Basic has many library functions. A library function is accessed by stating its name followed by the information that must be supplied to the function enclosed in parenthesis. This process is called calling a/unction. The values held in the parenthesis are called arguments. When the function is called, it uses the supplied arguments to perform an operation and return a value. Table 5.7 shows a summary of some the library functions used in Visual Basic.
Using the format function
The format function helps the programmer to display data in many different formats. Table 5.8 below shows how data can be formatted.
NB: The dollar sign may be used with the format function depending on the type of output required. In the last row of the table, the formatted output is displayed on a label control.
Program comments
Comments are English statements included in the code to document a program. The comments are not executed when the program is running. In Visual Basic, a comment starts with a single apostrophe (‘) followed by the comment statement. For example:
X = Sin(p) ‘find the sine of p and store it in X
Print X ‘display the value ofX on the screen
Converting a numeric string to a value
If you enter a number in a text box, the best way to convert it into a value is to use the Val function This is because the computer treats anything typed in the textbox as a string. The Val function operates on the string and returns a numerical value.
Hence, if the name property of a text box is set to txtLength, then the number typed in it can be read as a value into a variable x as follows: x = Val(txtLength.Text)
Converting a value to a string
Assuming a particular variable has a numeric value and you wish to display the value in a text box, then you have to convert the value to a string first. Suppose that the name of the text box is txtArea and the integer variable is x then: txtArea.Text = Str(x) ‘ display the value in x as a string in txtArea.
Project 5.1
Create a program that can be used to calculate the area of a rectangle. The program should prompt the user to enter the length and width of the rectangle. Figure 5.8 shows an overview of such a program.
To create the project, proceed as follows:
- Open Visual Basic and select the Standard.EXE from the New Project dialog box. A blank form will be displayed as shown in Figure 5.9.
- Place the necessary controls on the form. We need three text boxes and two command buttons. Double click the text box tool on the toolbox then the command button. The controls are automatically placed on the form and are given default names like Text! and Commandl. Add another command button. Use the shape tool to place a rectangle on the form. Drag the controls to the desired location on the form and repeat the process until you have the interface as shown in Figure 5.10.
- The next step is to define the set of properties for each control. To do this, right click the control then click properties. Set each control properties in the properties window as shown in the Table 5.9 below:
NB: The conventional way of setting the name property of any object in Visual Basic is to use object prefixes such as txt for text or boxes, lbl for labels, cmd for command buttons etc.
- After setting the properties, we can now write the event procedures that calculate the area of the rectangle once values are entered in the txtLength and txtBreadth text boxes. To write the code, double click calculate button and add the code listing between Private sub cmdCalculate click and the End sub.
Dim L As Single, W As Single, A As Single
L= Val(txtLength. Text)
W= Val(txt Width. Text)
A=L*W
txtArea= Str( A)
For the cmdExit button, just write End between Private sub cmdExit click and the End sub.
Figure 5.11 shows how your code should look like in the code window.
- Run the project. Enter a value in the txtLength and another in the txtWidth text boxes then click the Calculate button. Notice that the area of the rectangle is displayed as shown in Figure 5.12.
Explanation
- The first line declares the variables needed for the program to run and store values.
- The second and third lines assign the values in the text boxes called txtLength and txtWidth variables Land W respectively.
- The second last statement calculates the area of the rectangle while the last uses a function Str to display the result as a string value in the textbox named txtArea.
Adding more forms to a project
Sometimes a Visual Basic project may require the use of more than one form. To add a form to a project, the following procedure is followed:
- Click the Project menu then select Add Form command.
- In the dialog that appears, select the type of form you want to add from the New tab then click Open button.
Control structures
In Chapter 3, we introduced the three control structures that determine the execution of statements in a program. In this topic we shall discuss how these controls are implemented in Visual Basic.
Selection
The most common selection controls used in Visual Basic are:
- IF …… THEN.
- IF … THEN …… ELSE.
3.Nested IF.
4.CASE selection.
The IF…THEN selection
The IF. . . THEN selection is used to execute a single statement or a group of statements that represent only one alternative or option. This means that some circumstances have only one option for selection depending on whether a condition evaluates to true or false. For example IF y = 80 THEN Print (“……..”)
END IF
The statements in the If…Then…End If will be executed if the value of y is equal to 80 otherwise the whole block will be bypassed and the statements after END IF will be executed.
IF…THEN…ELSE selection
The IF… THEN.. . ELSE allows the execution of two alternatives or options depending on whether the test returns a true or false. Consider the following example:
IF average> 80 THEN
Print(“Excellent work! Congratulations”)
ELSE
Print(“Work harder next time”)
END IF
In this case, the statements starting with ‘Excellent Work! ……. ‘ will be displayed on the screen if the average is greater than 80. Otherwise, if average is less than 80, the statement “Work harder next time” will be displayed on the screen.
Nested IF selection
Nested IF selection is used if there are more than two available options to choose from. The general format of Nested IF is
IF <condition> THEN
Statements
ELSE IF <condition> THEN
Statement
ELSE IF <condition> THEN
Statement
ELSE <condition> THEN
Statement
Project 5.2
Write a program that can be used to find the roots of a quadratic expression. ax2 + bx + C = 0
The formulas to solve the values of x in this expression are:
Xl = -b -sqr(b2 – 4ac)
2a
X2 = -b -sqr(b2 – 4ac)
2a
X=-b
2a
i.e.b2 – 4ac = 0 or b2 = 4ac
To create the project, proceed as follows:
- Test whether b2 is larger than or equal to 4*a*c. If it is true, then:
- Create a new project that would be used to calculate the values of x, Xl and X2 also called roots of the quadratic equation.
- In the appropriate event procedure e.g. the calculate button, add the code listed below: ‘Calculating roots of a Quadratic Equation
Dim a,b,c As Integer Dim z,X,X1,X2 As Double z=(b^2-4*a*c)
IF z> 0 THEN
X1=(-b+Sqr(d)) / (2*a)
x2 –x1=(-b-Sqr(d)) / (2*a) ELSE IF z= 0 THEN x = -b / (2*a) ELSE IF z= 0 THEN
Print (“This quadratic equation is not soluble”) END IF ENDIF
ENDIF
Explanation
- The expression b/\2-4*a*c is first assigned to a variable z.
- z is then tested if it is greater than zero. If greater, the program calculates the values of Xl, X2 and x. Otherwise a message “This quadratic equation is not soluble” is displayed.
The Case construct
As discussed earlier in control structures of chapter 3, the Case construct is used to reduce the tedious work of coding associated with the nested IF… construct. Let us look at a case statement that can display the name of a weekday when its number is provided. ‘Display weekday
Dim D As Integer
SELECT CASE D
CASE 0
Print(“Sunday”)
CASE 1
Print(“Monday”)
CASE 2
Print(“Tuesday”)
CASE 3
Print(” Wednesday”)
CASE 4
Print(“Thursday”)
CASE 5
Print(“Friday”)
CASE 6
Print(“Saturday”)
CASE ELSE
MsgBox(“Error -That is not a day in the week”)
End SELECT
Looping construct
In Visual Basic looping instructs the computer to execute the same block of code many times before a particular condition is met. Common looping constructs used in Visual Basic are:
- DO loop.
- ..Wendloop.
- FOR loop. DO loop
There are four ways of writing the Do loop. Two of the constructs require the condition to be tested first while the other two require that the condition be tested after the statement within the construct is executed at least once. The general formats of the four Do constructs are:
- DO WHILE <condition>
Statements
Loop
2.DO Until <condition>
Statements
Loop
- DO
Statement,
Loop UNTIL <condition>
- DO
Statements
Loop WHILE <condition>
Explanation
The Do While. ..Loop in 1 continues to execute as long as the condition is true. The Do Until. ..Loop in 2 continues to execute as long as the condition remains false. The loop in 3 executes the statements at least once as long as the condition is not true. Lastly, the loop in 4 executes the statements within the construct at least once as long as the condition remains true. for the first two DO statements, the test of the condition is done at the beginning of the loop hence avoiding execution of any statements in the loop as long as the condition required is not met. On the other hand, the last two loops allow a pass through the loop at least once before the condition is tested. example 5.1
Write a program using the DO loop that will write numbers between 1 and 20 on the screen then stop. Save the project as Example 5.1.
Solution
- Double click the form to display its code window
- Add the following code listing between the Private sub form-load and End sub. x=O Counter=O
DO WHILE counter<=20 x=x+1
Counter=counter+ 1
Print x
Loop
NB: All the other DO loops can be easily implemented with little effort following the general format provided.
Looping with While-Wend
The While..Wend construct can be used in place of a Do While loop. The general format of this construct is: While <condition> Statements
Wend
As with the Do While loop, this loop executes the statements within the construct as long as the condition is true.
Practical activity 5.1
Open the project for Example 5.1 and replace its code with the code below. Dim x As Integer, Counter As Integer
x=O
Counter = 0 While counter<=20 x=x+1
counter=counter+1 Print x
Wend
Save the project as Example 53.
The FOR – NEXT loop
The FOR – NEXT Loop executes the statements within the construct a predetermined number of times. The general format of the FOR – NEXT Loop is:
For index = lower limit To upper limit ‘sets upper and lower limits statements
Next index ‘increments index by 1.
You can set the STEP value of the index as follows:
For index = lower limit To upper limit STEP 2 statements
Next index ‘STEP increments index by 2.
The FOR construct is very suitable for accessing values in a list or array because of their sequential nature.
Practical activity 5.2
Open the project for Example5.3 and replace the code with the listing below:
Dim Number As Integer, Counter As Integer
Number= 0
For counter= 1 TO 20 STEP 2 Number= Number + counter
Print Number
Next counter
Working with graphical objects
To add a picture or object on to a form, simply click the picture box or the image tool on the toolbox and then drag to define the area where you want the picture to be placed. Right click the object and then click properties. Set the Name and Path properties. The Path property tells the control where the picture is located.
Notice that after setting the properties, the picture is displayed on the form. If it is lying on top of other controls and you want it to be the background, right click it then select Send to Back.
Modules and procedures
Large projects must be made modular in nature to enhance maintenance and independence of the various blocks of code. The three main modules used in Visual Basic are explained in Table 5.10.
Declaring general subroutines
So far, we have mainly discussed event driven procedures. Visual Basic also lets the programmer create general procedures that can be called within another procedure (subroutine). The general format of a general purpose subroutine is:
Sub SubroutineName( ) statements
End Sub
Example 5.2
Write a general subroutine that would solve y = xn , given that the values of n are integers.
Solution
Sub Power of Number ( )
Dim x As Single, y As Single, n As Integer y = x^n
Print y
End Sub
Explanation
The above general subroutine is given the name PowerofNumber. To call the subroutine in another procedure such as an event procedure, simply use the call statement. For example, to call the subroutine in the cmdCalculate _Click event procedure, type:
Call PowerofNumber () or Power Of Number ()
The code is executed once the command button for the cmdCalculate click event procedure is clicked. Project 5.3
Consider a subroutine that will determine the largest of two numbers. Use the code listing below to create a proj ect that can be used to determine the lagest value once the user clicks a command button. Sub Largest ( )
Dim Larger As Integer, x As Integer, y As Integer
If (x>y) Then Larger = x
Print (“The larger number is: “,x)
Else If (x<y) Then
Larger = y
Print (‘The larger number is “,y) Else
Print(“Both numbers are equal”)
End If
End If
End Sub
To create the project, proceed as follows:
- Open a new project and save it as LargerNumber.vbp. Save the form as LargerofTwo.frm. Set the objects properties for the three labels (Tabe 5.11) and design the interface as shown in Figure 5.13.
Double click the Calculate and Exit buttons and add the codes as shown:
Option Explicit
Dim x As Single, y As Single
Private sub cmdCompareXY- Click () X = Val (txtX Text)
Y = Val (txt Y. Text)
call Largest ‘calls a procedure named Largest that
End Sub passes the values of x and ythe procedure.
- Create a general subroutine called Largest and write the code listing below: Sub Largest ( )
Dim Larger As Single
If (x > y) Then
Larger = x txtLarger = x ElseIf (x < y) Then
Larger = y txtLarger. Text = y
Else txtLarger. Text = “The numbers are equal” End If
End Sub
Private Sub cmdExit – Click()
End ‘code for the exit button
End Sub
This code will appear as shown in Figure 5.14. The call statement in the cmdCalculate makes the Largest Sub procedure to be executed once the End sub is encountered, the control is returned back to the next statement often the procedure call.
- Click the run button and enter a value in the text box labelled X and the other in Y. Figure
5.15 shows that the value of Y i.e. 50 is larger than that of X.
Creating menus, message and dialog boxes Menus enable the users to quickly select commands while dialog boxes enable the user to enter values and make selections when working with the computer.
Drop down menus
Drop down menus are the most common menus found in applications. When a menu is selected, a drop down list of commands is displayed.
For example to create a menu bar with the menu items File, Edit and Format with commands for each menu item as shown in the Table 5.12 below.
Proceed as follows:
- Click the Menu editor command on the toolbar. Alternatively, from Tools click the Menu Editor command. The menu editor window opens.
- Under caption, type the word File. This is the screen name of the menu item.
- In the Name box enter mnuFile. This is the name that will be used to refer to the File item when coding.
- Under Shortcut, select a shortcut key combination. This is optional.
- Click Insert button and notice that the cursor moves to the next line.
- Type Open in the Caption box and mnuFileOpen in the Name box.
- Click the flush right button to insert four dots to the left of Open i.e. File
……….. Open
This means that Open is an item of the File menu. Repeat steps 1 to 4 for all the items then click the OK button. Your complete set up should appear as shown in Figure 5.16 below.
- Click OK to close the menu Editor window and go to form design. You will notice that your form now has a menu bar at the top as shown in Figure 5.17 below. Clicking the File menu displays a list of the options that you defined.
It is now possible to activate the menu commands by adding code in their event procedures. To do this, simply click a menu option while in design view and the code window opens in which you can add its code.
Message boxes
A message box is a special type of dialog box used to display a message to the user. To display a message box, use the syntax:
MsgBox “Message string”, Button/icon, “Title bar Caption”.
For Example: MsgBox(“Drive not Ready. Retry?”, vbRetryCancel + vbQuestion, “Drive Error”) Displays a message box (Figure 5.18) that tells user that the drive is not ready. Note the Retry and Cancel buttons, the Question mark in the dialog box and “Drive Error” on the Title bar.
Table 5.13 outlines some of the buttons/icons used in Visual Basic Table
Dialog boxes
A dialog box enables the user to have a “dialog” with the computer i.e. to exchange information with the computer. You have seen these many times when you try to open or save a file; a dialog will always pop up asking you to fill or select some options. A dialog box is a special purpose form. It is usually accessed when a menu item is selected. Most dialog boxes have common controls like option buttons, list boxes and command buttons.
Simple dialog boxes
Visual Basic enables the user to create forms that can be used as dialog boxes. However, they are secondary to the primary form that is used to access them. Such a form is referred to as a modal form. This means that the form remains on top of the active form until the user clicks the OK or cancel button. To add a modal form to your project, use the Load form command. For example, if the name of the form is Form3 then the Load Form3 command will display the form into the current project. To stop the form from executing, use the unload command i.e. Unload Form3.
In most cases, a form that is loaded may not even be visible in the project window. To make it visible, simply use the Show method. Remember that a method carries out actions on objects. For example to display Form 3, use the syntax Form3.Show. To show the form as modal, use Fonn3.Show l or Form3.Show vbModal.
Project 5.4
Open a project on which you created the menu bar and do the following:
- From the project menu click Addform then click New from the Add Form dialog box.
- Select dialog A form with two command buttons ie Ok and Cancel is added to your project. Notice in the Project Explorer window that a new form called Form2 is placed hierarchically below the first form.
Change the form caption and name appropriately.
- From your main form file menu click the Open command.
- In the menuFileOpen code window that opens add the code as shown in Figure 5.19.
- Close the code editor window and run project. Notice that when you click File then Open the dialog box you created is displayed on top of Form 1 (Figure 5.20). Because of the Show 1 method, you cannot access the main form until you click ok or cancel button on the dialog box.
Directory list box
You can also add a directory list box on a form. To do this, proceed as follows:
- In the Project Explorer window, double click Form2 to open it in design view.
- Double click the DirListBox on the toolbar to place it on the form.
- Run the project and select the Open command from the File menu, you will be able to browse all the directories on your computer using the dialog box that you just created.(Figure 5.21).
Common dialog box control
Microsoft common dialog control is a component used to add dialog’ boxes such as Save As and Open onto a form. The common dialog control I is not available on the toolbox unless it is added. To add it, click Project then Components. The components dialog box as shown in Figure 5.22 will appear. Select the option Microsoft common dialog control as shown, then click the Apply button. Close the components dialog and check your toolbox for the new icon called common dialog. Project 5.5
Using the common dialog box control, create a project that can be used to display the open and save As dialog boxes. To create the project, proceed as follows:
- On the form, create a menu bar with menu items File, Edit and Format and two command buttons with captions open and save as shown in Figure 5.23.
- Right click the common dialog control on your form to display its properties window. Set the name property e.g. commonDiagl.
- Double click Open from the File menu or the Open Command button on the design form then add the statement below between the Private sub and End sub. ShowOpen
- Double click the mnuSaveAs or the Save Command and type the code CommonDiag I. Show Save
Save the project and run the form. Notice that if you click the Open command or button when the form is running, the Open dialog box opens as shown in Figure 5.24.
In the same way a Print dialog box can be called by adding the following to a menu or button event: CommonDiag 1.ShowPrint
Other dialog boxes supported by common dialog box are Show Color and Show Font.
List boxes and combo boxes
List boxes and combo boxes are used to display a list of items the user can select from.
List boxes
A list box enables the user to select an item from a list of entries. Selecting an item on a list during runtime causes the value of the selected item to be assigned to the ListIndex property. The ListIndex is an integer with a range of 0 to n-I where the second item corresponds to index 1. Items can be added to a list using the AddItem method or using the list function.
Project 5.6
Create a project that leads a list of items into a list box when the form is loaded.
To create the project, proceed as follows:
- Place the list box on the form and then drag it to the expected size.
- Double click the Form and add the following code window in the Form_Load() event procedure:
Alternatively you can add the items in the list property of the list box. To do this, display the list properties window, in the list property, enter the items. To move to the next line, during item entry, press Ctrl + Enter. Figure 5.25 shows the item list assigned to a list box using the properties window.
- Run the project. You will notice that the list builds dynamically as you click in the box when the form is running.
NB: The ListIndex and ListCount properties are very important. ListIndex can be used in CASE selection construct to point to the most recently selected list entry. For example, Select Case Listlndex
Case 0 ‘first entry in list corresponds to 0, not 1 “Nairobi”
Case 1 “Kisumu ”
Case 2
“Mombasa”
Case 3
………… ” ..
End Select
On the contrary, the ListCount property shows the number of entries in a list and it starts from 1, not O.
Combo boxes
As opposed to a list box, a combo box allows the user not only to select but also make a new entry into the list of items. Project 5.7
Create a project that loads a list items into a combo box when the form is loaded.
To create the project, proceed as follows:
- Place the combo box control on the form.
- Open its properties window and in the List property add the following items:
“Red”
“Yellow”
“Green”
“White” “Black”
- Run the project to load the form. Click the down arrow on the combo box to view the list of item as shown in Figure 5.26 below.
Visual Basic data structures
Apart from using simple data structures such as Integer, Single, Double etc., Visual Basic comes with features that allow the programmer to create complex data structures. These include arrays, records and files. Arrays
An array is a data structure that stores several data items of the same type hence it is called a homogeneous data structure. Table 5.14 shows how data of type Integer is stored in an array. The array has cells. The numbers 0 to 5 are called array indices or subscripts. In Visual Basic, an array starts from cell 0 as shown in the table.
Declaring an array
To declare an array, use the statement Dim ArrayName (n), where n stands for the number of elements in the array. For example:
Dim Scores (4) is an array that holds five elements. An element is an item in an array that can be accessed using the array variable name and a subscript. For example, consider an array of 5 elements called Scores. To display the 4th element use:
Score4 = scores(3)
Print Score4
The value stored in the variable score4 is printed on the form. To store a value in an array variable, use the statement ArrayVariable (index). For example, to assign a numeric constant 90
to the fifth cell use scores( 4) = 90
This statement will assign a value 90 in the cell 4th of the array.
NB: If the array was very large and you wish to read or enter values in it, it would be very tedious entering a value cell by cell i.e. Score(O) = 10
Score( 1) = 20
Score(3) =30
Score(n) = x
To avoid this, the For.. loop can be used. Remember that this loop is used where the number of iterations are pre-determined hence its suitability for use with arrays.
For example, if you wish to request the user to enter six values in array named A, the following FOR loop can be used:
Dim A(5) As Integer
Dim index As Integer
Private Sub EnterArrayValues()
For index= 0 To 5
A(ifldex) = Val(Textl.Text)
Next index End Sub
Notice that the array is declared this time outside the Subroutine in order to make it a general procedure that can be accessed by other subroutines. To Display values of the array on the form the following statement can be used:
Private Sub Display Array Values ()
For index = 0 To 5
Text2. Text= Str(A(index))
Next index
End Sub
Two dimensional arrays
A two dimensional array is a data structure in which elements are arranged in rows and columns. Two subscripts are used to identify an item. For example Dim Score(2,4) means that the element is in the 3rd row, 5th column. This is because the array was declared to start from row 0 column
0 same as Dim Score (0 to 2, 0 to 4). To manipulate elements stored in a two dimensional array, we use the nested For.. Next or For Each … Next loop as shown below: Dim iRow As Integer
Dim jColumn As Integer
For iRow = 1 T03
For jColumn = 1 to 5
Score(iRow, jColumn)
Next jColumn Next iRow
Records
A record comprises of a series of related data items (fields). They differ from arrays in that whereas all elements in an array are of the same data type, data items in a record may differ in type. For example, when you want to store a students record with the fields Name, Registration number and date of birth in a file as a unit, then you can define a record that would hold all this data items in one structure. For example the following declaration will create StudentDetails record:
Type StudentDetai/s Name As String 15
RegistrationNumber As String 10
DateofBirth As Date
………… .
End Type
The first line in the type declaration gives the name of the data structure i.e. StudentDetails. The other three lines define fields in the data type. Notice that each field has its own data type and that the string data types are of fixed length. The last line i.e. End type marks the end of the record definition. A record is defined in a standard code module or the General Declaration section of a form module.
It is not possible to access the elements of a data structure directly. This is why after defining data structure, you must declare a variable that will be used to hold the records. This is done by declaring a variable whose type is the data structure. The general format of such a declaration is: Dim RecordVariablelVame As RecordName
For example, the StudentDetails record can be declared as a variable using the statement:
Dim Student As StudentDetails
This means that the variable Student is of type StudentDetails. To access an element in the structure, the following syntax have to be used:
RecordVariable.FieldName e.g. Student.Name
Array of records
An set of user-defined data types can be stored and accessed in arrays too. Consider the record declared below:
Type Student
RegistrationNumber As Integer Name As String * 20
End Type
An array of the student record can then be declared as follows: Dim StudentArray(39) As Student This means that the array can store fourty student records. To access a field in the array of records use the statement: Arrayname(index).FieldName e.g. StudentArray(20).Name will return the name of the student whose record is in the 20th cell.
Data files
A file can be defined as a storage location of related information or records. Visual Basic recognises three types of files namely: text (sequential) files, random access files and binary files. Sequential files consist of data made of text strings. A random access file contains data records each of equal length with each record having a unique identifier. Remember that a record is a data structure that has several related data items about a particular entity. In random files, a record can be accessed directly by specifying its corresponding record number or location. A binary file contains information expressed as a stream of bytes. Such files store graphics, sound files or compiled code. Sequential files
A sequential file stores data items one after another in sequence. The keywords used in manipulating a sequential file include Output, Input, Write, Read and Close. Table 5.15 gives a summary of the keywords used in manipulating sequential files.
The following statements are very important when working with this type of files:
Open filename For Output As #n
- Open filename For Input As #n
- Close #n where n refers to the file number (n is usually an integer value).
Manipulating data in a sequential file
To manipulate a text file you can use the tools that corne with Visual Basic such as the common dialog box. For example, to open a file for input, use the showOpen method of the common dialog box. The skeletal code below shows that when the user enters the name of the file in the open dialog box, it is assigned to a string variable TargetFile ready for input.
Private Sub mnuOpen _Click
Dim TargetFile As String, x As Integer, item As string
CommonDialogl.ShowOpen
TargetFile= CommonDialog I.FileName Open TargetFile For Input As #1 x= 0
Do Until EOF(I) input # 1, item
‘Write a code that reads each data
‘Item from the TargetFile until the end-of file-condition is true x=x+l
Loop
Close #1
End Sub
Likewise, you can write data to a new file by operating it in Output mode as shown in the skeletal code listing below. Note that the file number used is #2 to avoid overwriting the first file.
Private Sub mnuSaveAs Click
Dim NewFile As String, x As Integer, item As string
CommonDialog 1.ShowSave
NewFile= CommonDialogl.FileName Open NewFile For Output As #2 n= 30 For x = 1 TO n
‘Write a code that writes each data item into the NewFile Next x
Close #2
End Sub
When you write to a file, all the original data in the file is lost. To avoid losing the content of a file open it in Append mode as shown in the skeletal code below.
Private Sub mnuSaveAs Click
Dim TargetFile As String, x As Integer, n As Integer
CommonDialog 1.ShowSave
TargetFile= CommonDialog.FileName Open TargetFile For Append As #1 n= 20 For x = 1 TO n
‘write each data item at the end of an existing file Next x
Close #1
End Sub
Project 5.8
Using Visual Basic programming, develop a simple sequential file processing program that would read data from a file called ReaderFile.txt and write the contents to another file called Receive. txt . The system should be menu driven. The project should use the Open and Save as dialog boxes to access the two files on the disk.
To create the project, proceed as follows:
- Create a new project and save the default fonn as Save the project as
SequentialFiles. vbp
- Create a File menu having menu commands as shown in Figure 5.27 below: i.e. Click the tools then menu editor command.
- Place the Common dialog control, a combo box and a label on the form.
- Double click the form then add the code listing below.
Private Sub Form_Load()
Form I. Caption = “Text File I”
Labell. Caption = “Learning to work with text files”
mnuSave As. Enabled = False
Combo 1. Text = ” ”
End Sub
- Double click the Open command and type the code below:
Private Sub mnuOpen – Click()
Dim TargetFile As String, Item As String
Dim x As Integer
CommonDialog I.Filter = “Text files (*. txt)/*. txt” ‘open only text files
CommonDialog1.ShowOpen
TargetFile = CommonDialog1.FileName Open TargetFile For Input As #1 x= 0
Do Until EOF(1)
Input #1, Item
ComboI.List(x) = Item ‘Assign items to the list property of combo box
ComboI.Tag = x ‘Assign the index x to the tag property that represent the number of items read from the file.
x= x+ 1
Loop
Combo 1. Text = “Contents” Combo I.Locked = True
mnuSave As.Enabled = True ‘enable command after file open
Close #1
End Sub
Private Sub mnuSave _As – Click()
Dim NewTargetFile As String
Dim x As Integer, m As Integer
CommonDialogI.Filter = “Textfiles (*.txt)/*.txt”
CommonDialog I.ShowSave
NewTargetFile = CommonDialogI.FileName Open NewTargetFile For Output As #2
n = Val (Combo 1. Tag) ‘Assign the value of the tag to n
For x = 0 To n
Print #2, ComboI.List(x)
Next x
Close #2
End Sub
Explanations
- on running the program, a form is displayed on which is a combo box and a file menu.
- On clicking the open command in the File menu, the open dialog box is displayed from which the user can select or type the file name.The file is assigned to a variable TargetFile.
- Minimise the Visual Basic IDE Window and start a text editor program such as Notepad. In the window, write the text: we are the world.
- After saving the text file, close the program and now return to your project. Click File then Open on your running project. In the Open dialog box, locate your text file and open it. Notice now that the words “We are the World” are displayed in the Combo box as shown in Figure 5.28.
You can now use the Save_As command to save the file elsewhere with another name.
NB: If we alter the text and separate the words in the sentence with commas or quotes each word will be read into the computer separately. In such a case the words will be displayed in a drop down list in the combo box.
- The reason why the text is displayed in the combo box is because we used the Print statement for output and directed the output to the combo box. However, to write the content into the file, use the Write #n statement instead of Print #n.
Project 5.9
Laura, a proprietor of Laura Refreshment Cafe has requested you to create a program that stores her products in a sequential file. The data entry form should display beverages in a combo box while juice flavours should be displayed in a list box. These two controls are populated with data stored in a sequential file. Using a command button, the user should be able to add more beverages in the combo box.
To create the project, proceed as follows:
- Create a new project with one form and add appropriate controls on the form as shown in Figure 5.29.
- Display each control properties window and set the properties of each control such as:
- Name and caption of add beverages command button.
- A combo box with items such as Tea, Coffee, Cocoa, Beans etc.
3. A List box with items such as Orange, Passim)., Mango etc.
4. A menu bar with File and Edit Menus. The commands in the
File menu include Save and Exit while those in the Edit menu includes Delete an item, Clear the list and add an item
3, Write a code for each event procedure as shown by the listing below.
Double click the Add Beverages command button and type the code below:
Option Explicit
Dim mbUnsaved As Boolean
Private Sub cmdAddBevarage – Click()
‘Add new Beverage If cboBeverages.Text <> “” Then
With cboBeverages
.Add/tem cboBeverages
.Text= “”
End With mbUnsaved = True
Else
MsgBox “Enter the name of Beverage”, vbExclamation, “Missing Data”
End If cboBeverages.SetFocus
End Sub
Double click the form to open the code editor window and enter the code listing below:
Private Sub Form_Load() .
‘Load the list
Dim stBeverages As String
On Error GoTo HandleErrors ‘Turn on the error handling routine
Open “a:BevFile.Dat” For Input As #1
Do Until EOF(1)
Input #1, stBeverages cboBeverages.AddItem stBeverages
Loop
Close #1
Form Load exit:
Exit Sub
HandleErrors:
‘The code below raises any type of error encountered during the file open operation
Dim iResponse As Integer
Select Case Err.Number
Case 53, 76 ‘ Invalid path or file name iResponse = MsgBox(“Create a new file?”, vbYesNo + vb Question, “File Not Found”) Display a message box
If iResponse = vb Yes Then
Resume form_Load _exit ‘Exit the Procedure Else mnuFileExit – Click ‘Exit the program
End If Case 71 iResponse = MsgBox(”Drive not Ready. Retry?”, . vbRetryCancel + vbQuestion, “Drive Error”) display a message box
If iResponse = vbRetry Then
Resume
Else
mnuFileExit – Click ‘Exit the program
End If
Case Else
.
Err.Raise Err display a message for any other type of error End Select
End Sub
Private Sub mnuEditAdd – Click()
‘Add a new beverage list cmdAddBevarage _Click
End Sub
- Double click the Add command from Edit menu and type the code below:
Private Sub mnuEditdelete – Click()
‘Delete a selected item If cboBeverages.ListIndex <> -1 Then cboBeverages.RemoveItem cboBeverages.ListIndex
mbUnsaved = True
Else
MsgBox “Select an item you want to delete”, vbInformation, – I
“Select an Item”
End If
End Sub
- Double click the Exit command in the file menu and type the code listing below:
Private Sub mnuFileExit – Click()
‘Exit from the program and save changes
Dim iResponse As Integer
If mbUnsaved = True Then iResponse = MsgBox(“Save changes?”,vb YesNo + vbQuestion, “Save Changes”)
If iResponse = vb Yes Then mnuFileSave Click
End If
End If
End
End Sub
(e) Double click the save command in the file menu and type the code listing below:
Private Sub mnuFileSave – Click()
‘Save the combo box content into a sequential file
Dim iIndex As Integer
Dim iMax As Integer
Open “a:BevFile.Dat” For Output As #1 iMax = cboBeverages.ListCount – 1
For iIndex = 0 To iMax
Write #1, cboBeverages.List(iIndex)
Next iIndex Close #1 mbUnsaved = False
End Sub Explanation
- On running the program, the form is loaded and you can add a beverage item in the combo box as shown in Figure 5.30.
- When the user clicks the save command on the File menu, the Beverages list is saved on the floppy disk. You can view the items using Microsoft Windows NotePad or any Text Editor. Below is a list of items saved in the file Dat. “Chocolate”
“Tea”
“Coffee”
”Milo”
“Plain Coffee”
“Soya” I
“Cocoa”
3. On error statement have been used in the Form Load procedure. This code ensures that the program does not halt in case the user forgets to insert a floppy disk. On error statement and
the err objects are therefore used to trap run-time errors. The correct syntax of the On Error
statement is: I
On Error GoTo LineLabel e.g. On Error GoTo ErrorHandler I
The lineLabel refers to the error handling code that begins with a line label such as HandleErrors:
The resume statement tells the program to resume back to the statement that caused the error. Resume Next option can also be used I to tells the program to execute the statement immediately following the line that caused the error.
The Err object holds information about an error that has occurred. The name of the application that caused the error is stored in the source property. The Number property contains error numbers ranging from 0 to 65,535. Examples of Err.Number are shown in Table 5.16.
Table 5.16
You can use the raise method to set the error code, effectively turning on an error. This is necessary if the error that has occurred is not the one of the anticipated. The statement Err.Raise Err in the form load procedure therefore tells the program to display an error message for any other unhandled error.
Random access files
Random access files consists of fixed length records each assigned a unique identification number. The keywords use in random file manipulation are summarised in Table 5.17 below:
To open a random file for input or output use the syntax: The following statement:
Open filename For Random As #n Len = record length
Reading records from a random file
Records are read one at a time using the following procedure
Get #n,record number, data item
Sometimes, you may ignore the record number but instead put two commas I.e.
Get #n”data item
The computer in this case will look for the record following the last’Get operation.
Writing to a random file
The statement below can be used to write records to a file.
Put #n,record number, data item or put #n”data item
The latter statement would write a record next to the last Put operation. NB: Random files will accept data records only.
Project 5.10
You have been requested to develop a program that can store employees contact details. Create a project that has two forms namely the main form and a data form that can be used to manipulate employees records and store them in a random file. The forms should have the following controls:
Main form
- A List box where the names of the employees are displayed.
- Command buttons for Adding, Deleting, Updating and browsing employee’s records.
- Menu bar with File and View menus.
Data form
- Labels and Text boxes for LastName, FirstName, Address and City/Town
- Navigation buttons i.e. First, Next, Previous and Last.
- OK and Cancel buttons.
To create the project, proceed as follows:
- Create a project that has two forms namely the main form and a data form and add controls as shown in Figure 5.31 (a) and (b).
- Open the properties window and set the properties of each control such as:
- Name and caption of each form controls
- Command buttons for both forms.
- A combo box with items such as Tea, Coffee, Cocoa Soya etc.
- Create a menu bar with File and View The File menu should include at least one command e.g. Exit while the View menu should have at least View Records command.
- Write codes for each event procedure and standard procedure as shown by the listing below. Standard(Global) Procedure
Enter this code in a standard module code editor window. Option Explicit
Type employeesRecord ‘Define a record with five fields.
stLastName As String * 15 stFirstName As String * 15 stAddress As String * 10 stCity As String * 12
stDeleted As String * 1
End Type ‘End of record defination
Public gEmployee As employeesRecord
Public gstFileAction As String
Main form Procedures
Private Sub cmdAddNew – Click()
‘Display a blank record in order to add a new employee gstFileAction = “A”
frmFile.Show vbModal End Sub
Private Sub cmdBrowse – Click()
‘Browse the File gstFileAction = “B” frmFile.Show vbModal End Sub Private Sub cmddelete – Click() ‘Delete an employee from the list iflstEmployee.ListIndex <> -1 Then gstFileAction = “D” frmFile.Show vbModal
Else
MsgBox “Select a record to be deleted!”, vbOKOnly + vbInformation, “Delete!” End if
End Sub
Private Sub cmdUpdate – ClickO ‘Update an employee record iflstEmployee.ListIndex <> -1 Then gstFileAction = “u” frmFile.Show vbModal
Else
MsgBox “Select a record to update”, vbOKOnly + vbInformation, “Update” End if
End Sub
Private Sub Form_Load()
‘Store the details of the list box in a random file
Dim iIndex As Integer
Dim iResponse As Integer
On Error GoTo HandleErrors
Open “a:Employee.Dat” For Random As #1 Len = Len(gEmployee) IfLOF(l) / Len (gEmployee) > 0 Then ‘Iffile not empty
For ilndex = 1 To LOF(1) / Len (gEmployee)
Get #1, ilndex, gEmployee
If gEmployee.stDeleted <> “Y” Then
AddtoList (iIndex)
End If
Next iIndex Else
iResponse = MsgBox(“Create a new file?”, vb YesNo + vb Question, “File Not Found”) If iResponse = vbNo Then
mnuFileExit _Click ‘Exit the program
End If End If form_Load – exit: Exit Sub
HandleErrors: If Err.Number = 71 Then
iResponse = MsgBox(“Drive not Ready. Retry?”, vbRetryCancel + vb Question, “Drive
Error”)
If iResponse = vbReiry Then
Resume Else
mnuFileExit _Click ‘Exit the program
End If
Else
On Error GoTo 0 ‘Turn error trap off
End If
End Sub
Private Sub mnuFileExit – Click()
‘End the program
Close #1 End
End Sub
Public Sub AddtoList(iIndex As Integer)
‘Add an employee in the list box Dim stName As String
stName = Trim(gEmployee.stLastName) & “, “& gEmployee.stFirstName
IstEmployee.AddItem stName
IstEmployee.ItemData(lstEmployee.NewIndex) = iIndex
End Sub
Private Sub mnu ViewEmployee – Click()
‘Display the employees file gstFileAction = “B” ‘Browse
frmFile.Show vbModal End Sub
Data form Procedures Option Explicit
Dim miIndex As Integer
Private Sub cmdCancel- Click()
‘Switch to the main form frmFile.Hide
End Sub
Private Sub DisplayRecords()
‘Display record fields in the form text controls txtLastName. Text = gEmployee.stLastName
txtFirstName. Text = gEmployee.stFirstName
txtAddress. Text = gEmployee.stAddress txtCity. Text = gEmployee.stCity
End Sub
Private Sub SaveRecords() gEmployee.stLastName = txtLastName. Text gEmployee.stFirstName = txtFirstName. Text gEmployee.stAddress = txtAddress. Text gEmployee.stCity = txtCity. Text
End Sub
Private Sub cmdFirst – Click() ‘Display the first record frmMain!lstEmployee.ListIndex = 0
Readrecords
End Sub
Private Sub cmdNext_Click()
‘Display the next record If frmMain! IstEmployee.ListIndex < frmMain!lstEmployee.ListCount -1 Then
jrmMain!lstEmployee.Listlndex = jrmMain!lstEmployee.Listlndex + 1
Readrecords Else cmdFirst Click
End If
End Sub
Private Sub cmdLast – Click() ‘Display the last record frmMainflstEmployee.Listlndex = frmMain!lstEmployee.ListCount -1
Readrecords
End sub
Private Sub cmdOK Click()
‘Select the action to perform then click OK
Dim stName As String
Select Case gstFileAction
Case “A” milndex = LOF(1) / Len (gEmployee) + 1 gEmployee.stDeleted = “N”
SaveRecords WriteRecords frmMain.AddtoList (milndex)
frmMain!lstEmployee.ListIndex = frmMain!lstEmployee.Newlndex Case “D” miIndex =frmMain!lstEmplayee.ItemData(frmMain!lstEmployeeListIndex) gEmployee.stDeleted = “Y” WriteRecords
frmMain!lstEmployee.RemoveltemfrmMain! IstEmployee.Listlndex
Case “U”
SaveRecords
milndex= frmMain!lstEmployee.ItemData(frmMain!lstEmplayeeListIndex)
WriteRecords frmMain!lstEmployee.Removeltem frmMain! IstEmployee.Listlndex
frmMain.AddtoList (miIndex)
Case “B”
End Select frmFile.Hide ‘Return to the main form
End Sub
Private Sub ClearTextBoxes() txtLastName.Text = “” txtFirstName. Text = “” txtAddress. Text = “”
txtCity. Text = “”
End Sub
Private Sub NavigationEnabled() cmdFirst.Enabled = True cmdNext.Enabled = True cmdPrevious.Enabled = True cmdLast.Enabled = True End Sub
Private Sub NavigationDisabled() cmdFirst.Enabled = False cmdNext.Enabled = False cmdPrevious.Enabled = False
cmdLast.Enabled = False
End Sub
Private Sub cmdPrevious – Click()
If frmMain!lstEmployee.Listlndex < 1 Then cmdLast Click Else
frmMain!lstEmployee.ListIndex = .frmMain!lstEmployee.ListIndex – 1
Readrecords
End If
End Sub
Private Sub Readrecords() ‘Read data from a random file
miIndex= frmMain!lstEmployee.itemData(frmMain!lstEmployee.ListIndex}
Get #1, miIndex, gEmployee
DisplayRecords
End Sub
Private Sub WriteRecords()
‘Save data to a disk
Put #1, miIndex, gEmployee
End Sub
Private Sub Form_Activate()
‘Activate the data form and set focus to the LastName field
Select Case gstFileAction
Case ”A”
ClearTextBoxes NavigationDisabled txtLastName.SetFocus
Case “D”
Readrecords
NavigationDisabled
Case “U”
Readrecords
NavigationEnabled
Case “B”
NavigationEnabled cmdFirst Click
End Select
End Sub
Explanation
- On running the program, the main form is loaded that shows a list of employees as shown in Figure 5.32.
- When the user clicks the Add New button, a blank data form is displayed with focus set on the LastName text box. (See Figure 5.33). If you add a new employee record and then click the OK button, the employee’s name is added into the list box and saved into random file.
- On clicking the Delete, Update or Browse buttons, the records are displayed on the form for the user to perform the appropriate action. Figure 5.34 (a) shows a record that is just about to be deleted while Figure 5.34 (b) shows the main form display after deleting the selected record.
Binary files
A binary file is used to store graphics, sound or compiled files. Applications that make use of binary files are complicated and beyond the scope of this book. However, to manipulate a binary file the keywords Put, Get, EOF, Len, LOF, Seek, Loc (pointer location) are used.
To open a binary file we use the statement; OpenfileName for Binary As #n. Below is a skeletal listing of a Visual Basic program that read and writes the same data into a binary file.
Private Sub mnuCopy – Click()
Dim FileLength As Integer, Index As Integer
Dim FileName As String
Dim FileByteO As Byte
FileName = ……… ‘find out the file name
Open FileName For Binary As #1
FileLength = LOF(1)
ReDim FileByte(Filelength)
For index = 1 To FileLength ‘read the file
Get # 1 “FileByte(Index) ‘the second field has no value Next index
For Index = 1 To FileLength
Put #1, Index, FileByte(Index) ‘the second field has a value Next Index
Close #1
End Sub
Explanation
The Get #n statement start reading the first byte in the file and then reads each successive byte until the end of the file. The Put #n statement has a value hence it will overwrite the contents of the file it is writing to. To avoid this, leave index empty so that the write operation simply appends the records to the end of the file.
- What is an array subscript?
- Differentiate between a record and’ an array.
- Differentiate between a sequential file and a random access file.
- State the function of each of the following file manipulation commands.
Input #1 (b) Get#n (c) Put #n (d) Qpen
- Differentiate between (a) EOF and LOF
- An employee file has the following fields: First name, Second name, Employment number, Date of employment and Date of birth. Using the type declaration, create a user defined data type that will store ail this data for one employee.
- Declare a variable that can store the user defined data type in question 6 above. 8. Assuming the user wants to access the DateofEmployment field in a record variable’employeeDetails, write a statement that can do this.