Visual Basic Manual
Visual Basic Manual
Preface
Microsoft Visual Basic or simply VB is an incarnation of the old BASIC
language. It gives you a complete and powerful Windows application
development system in one package. VB give you a wide array of
software tools to create diverse applications like database systems,
games, and mathematical programs.
This manual is for programmers and would-be programmers who want to
learn Visual Basic. It contains a brief summary of the basic and more
important VB topics. It provides explained concepts and actual application
code that you can copy and run. It presents both the background and the
theory that a new Visual Basic programmer needs. The author though
assumes that the student already knows about basic programming
concepts such as flowcharting and algorithm formulation.
This manual was designed as a supplement to the Visual Basic classes of
Xavier University. Beginners might find this insufficient for a
comprehensive programmer's reference book. Teacher's guidance is
expected as students go through the lessons.
Acknowledgements
The author would like to thank the Commission on Higher Education
(CHEd) for funding this project.
Contact Me
I welcome any comment, suggestion, question, as well as corrections on the manual. You may contact me through:
Email jaeyf@xu.edu.ph
Phone (63-78) 858-3116 local 1006
(63-8722) 72-3116 local 1006
2
Introduction Basics of Visual Basic
Objectives
To recognize and understand the function of the main components of
the VB environment (Tool Bar, Toolbox, Project Window, Properties window,
Form, Code Window)
To understand Events, Methods, and Properties
It is a little known fact that you can write a VB program from scratch using nothing
more than a simple text editor, such as the Edit or Notepad applications that come
with Windows. In fact, the Visual Basic project files are exactly that - text files.
However, writing a project from scratch would involve a lot of tedious, detailed
manual entries. To simplify the task, Microsoft has built in to VB a software program
to help you write your VB projects. That software, known as the Integrated
Development Environment (IDE for short) is what comes to the screen when you
start VB and is the topic of this section.
Toolbox Form Title Bar Menu Bar Tool Bar
3
You use the Menu Bar to invoke IDE functionalities such as adding Forms to your
project. It also contains items that let you create and run your VB applications and
customize how the IDE would appear (like what windows and tools to display).
The Toolbox
The toolbox is simply a library of controls, both standard and custom. Controls are
objects that you place within Form objects such as a Label or a CommandButton.
Each type of control has its own set of properties, methods and events.
Pointer* PictureBox
Label TextBox
Frame CommandButton
Checkbox OptionButton
ComboBox ListBox
Horizontal Scrollbar Vertical Scrollbar
Timer DriveListBox
DirectoryListBox FileListBox
Shape Line
ImageBox Data
This is the window you use to manage the files for any given project. The window
is usually displayed in the upper-right corner of the main working area, and it
displays all the Forms, modules, user controls, and property pages that are currently
included in the project.
The three icons in the upper-left corner of the Project Explorer window are the
View Code icon, the View Object icon, and the Toggle Folders icon. Clicking
the View Code icon displays the code in the code window for the highlighted object.
Clicking the View Object icon displays the Form associated with the object in the
4
Form window. The View Object icon is available only to those objects that have
Forms associated with them. Clicking the Toggle Folders icon changes the view of
the window. It toggles the view from a folder view to a list of all the objects in
alphabetical order regardless of their type. The following diagram shows the
different parts of the Project Explorer.
Form Name
Form Filename
Note: Within Visual Basic, you refer to a Form through its name. The filename
(with .frm extension) is the name you give to the file storing the Form’s
information.
The Properties
Window
VB Controls such as
CommandButtons, Labels,
PicturesBoxes and other features
of most VB applications
allow you to enter parameters
that define how these controls
work. In VB, these parameters are
called Properties.
Some properties can be entered
at design time within the IDE,
while others must be entered
with code while the program is
running.
5
The Code Window
Like what its name implies, this is where you type in the code that VB executes.
Notice that the heading of the window indicates with which event the code is
associated.
The Code Window is easily displayed by double-clicking any control on the Form or
by clicking the View Code icon.
6
A VB Session
The first step to creating an application with Visual Basic is to create the graphical
user interface. The interface is the visual part of the application with which the user
will interact. You use Forms and controls to create the interface. They are the
objects that you will work with to build your applications.
7
It is important to understand that a project (the whole application) may contain
several Forms. Information about each Form (its own properties as well as those of
the controls that are on the Form) are stored in separate files with extension .frm.
Hence, a project with multiple Forms has multiple .frm files. The project also has a
.vbp file. This file contains data about the Forms the project has, which among
these is the startup Form, etc. An .frx file may be added if your project contains
graphics that are associated to the Forms.
An electric fan is an object. It has properties such as its height, color, and shape.
Its primary function is to blow air at varying strength depending on a specified
speed. The fan only functions when the user turns it on and presses any of its
speed buttons.
The Visual Basic program is analogous to the fan. The parts of the fan e.g. its fan
blades, power button, speed controls represent VB controls. The color, height, and
shape of the fan correspond to the properties of the controls. The fan’s functions are
analogous to methods. The action of turning on the fan and pressing the speed
buttons relate to what we call events.
If we are to program the fan, we would need to create the fan first and set its
properties (you might want to have a blue 5-foot fan with 5 speeds). We will design
it to function depending on what buttons are pressed: Rotate the blade at speed 2-
rotations per second for button 1, at speed 3-rotations per second for button 2, and
so on. In this case, the fan's behavior changes from idle to working when a power-
button-press and a speed-button-press events occur. We stop rotating the blades
when the user presses the power button.
In the next lessons, we will learn more about VB’s common controls, their properties
and events.
8
Lesson I. Forms, Labels, and Shapes
Objectives
To be able to create, execute, and save a VB project
To interactively design a simple interface by selecting, placing and
sizing screen objects from the toolbox
To be able to use the Pointer to select controls
To be able to customize the Form using properties
To use and be familiar with the Label control and its properties
To use and be familiar with Shapes and their common properties
To be familiar with VB events
Notes
IN FOCUS: FORMS
Forms are the windows that you see at runtime. They serve as containers of
controls such as Labels and CommandButtons. The following table lists the Form’s
properties.
Property Description
BackColor Specifies the Form’s background color. Programmer selects a color
from the Color Palette or specifies a color in Hex format.
BorderStyle Determines how the Form window appears. It also specifies whether
the user can resize the Form and determines what kind of Form you
wish to display (0: None, 1: Fixed Single, 2: Sizable, 3: Fixed Dialog,
4: Fixed ToolWindow, 5: Sizable ToolWindow)
Caption Specifies the text on the Form’s Title Bar at runtime.
Enabled Boolean. Determines whether the Form is active. A disabled Form
does not trigger an event. All controls on the Form are also
disabled.
Height Specifies the height of the Form in twips. A twip is 1,440th of an
inch)
Icon Specifies the filename of the icon graphic image that appears in the
Form’s Title Bar
Left Specifies the number of twips from the Label’s left edge to the Form
window’s left edge.
MaxButton Boolean. Specifies whether a maximize button appears on the Form.
MinButton Boolean. Specifies whether a minimize button appears on the Form.
MousePointer Determines the image of the mouse cursor when the user moves the
mouse pointer over the Form.
Moveable Boolean. Specifies whether the user can move the Form at runtime.
Picture Determines the graphic image that appears on the Form’s
background.
9
StartUpPosition Determines the state (centered or default) of the Form at application
startup.
Top Specifies the number of twips from the Label’s top edge to the Form
window’s top edge.
Visible Boolean. Determines whether the Form appears (True) or is hidden
from the user (False) at runtime.
Width Holds the width of the Form in twips.
WindowState Determines the initial state of the Form (0: Normal, 1: Minimized, 2:
Maximized)
Form’s Events
Form events are events that the Form can accept. The following are common ones:
Event Description
Load Occurs when a Form is loaded.
Unload Occurs when a Form is about to be removed from the screen.
Resize Occurs whenever a Form is resized, either by user interaction or
through code.
Activate Occurs when an object becomes the active Form. An active Form
appears in the foreground with a highlighted Title Bar.
Deactivate Occurs when a Form is no longer active.
IN FOCUS: LABELS
Labels hold text that appears on the Form. Labels cannot be edited directly – an
explicit code assigning a new caption to the Label should be carried out. You use a
Label, as its name obviously implies, to label a control, to provide instructions, etc.
The following table lists most common Label control properties.
Property Description
Alignment Determines whether the text appears 0: left-justified, 1: right-justified, or
2: centered within the Label’s boundaries.
AutoSize Boolean. Enlarges the Label’s size properties, when True, if you assign a
caption that is too large to fit in the current Label’s boundaries at
runtime. If False, the Label truncates the caption.
BackColor Specifies the Label’s background color. Programmer selects a color from
the Color Palette or specifies a color in Hex format.
BackStyle Determines whether the background shows through the label of if the
Label covers up it background text, graphics, and color.
BorderStyle 0: None, 1: Fixed Single. Determines whether a single-line border
appears around the Label.
10
Caption Holds the text that appears on the Label.
Enabled Boolean. Determines whether the Label is active. A disabled Label does
not trigger an even procedure.
Font Specifies the font of the text. Clicking this property will invoke a font
dialog box in which you can set the font name, style, and size.
ForeColor Specifies the color of the text. Programmer selects a color from the Color
Palette or specifies a color in Hex format.
Height Specifies the height of the Label in twips.
Left Specifies the number of twips from the Label’s left edge to the Form
window’s left edge.
MousePointe Determines the image of the mouse cursor when the user moves the
r mouse pointer over the Label.
TabIndex Specifies the order of the Label in the focus order.
TabStop Boolean. Determines whether the Label can receive the focus.
ToolTipText Holds the text that appears as a tooltip at runtime. A tooltip is a pop-up
description box that appears when the user rests the mouse pointer over
a control.
Top Specifies the number of twips from the Label’s top edge to the Form
window’s top edge.
Visible Boolean. Determines whether the Label appears (True) or is hidden from
the user (False) at runtime. Invisible Labels are only invisible at runtime.
Width Holds the width of the Label in twips.
WordWrap Determines whether the Label expands to fit its caption.
You can run, pause, and stop VB applications by pressing the control buttons on the
Tool Bar or by clicking the Run menu and selecting the appropriate menu item.
Click this to terminate the application. You can also click the
Close button on the Title Bar of the application.
11
The Pointer is one indispensable tool. When we move and resize control or when
we modify the properties of a control, we use the Pointer tool. How do we use the
Pointer in selecting controls?
If you want to select a control, simply click the Pointer on the Toolbox
and click the control you would like to select.
If you want to select multiple controls, hold down the Ctrl key and click
each control. You may also just lasso multiple controls by dragging a square
around the controls using the mouse.
The Shape control provides you with basic shape objects such as Rectangles,
Squares, Ovals, and Circles. The following Form shows each of these shapes:
When you drag a Shape control to the Form, a rectangle is displayed. To change
the shape, simply change the Shape property to:
0: Rectangle
1: Square
2: Oval
3: Circle
4: Rounded Rectangle
5: Rounded Square
By default, Shapes are transparent – all you see is the outline of a white shape. If
you want the color of the Form to appear through the Shape, (the Shape shows
whatever it covers), set the BackStyle to 0: Transparent.
12
You can fill Shapes with a color by setting the FillStyle property to 0: Solid and
setting a color to the FillColor property. You may also fill the Shapes with one of
the pre-defined patterns: 2: Horizontal, 3: Vertical Line, 4: Upward Diagonal, 5:
Downward Diagonal, 6: Cross, and 7: Diagonal Cross.
You can also modify the border (or outline) of the Shapes. The BorderStyle
property determines how the Shape’s borders would look like. When set to 0:
Transparent, you do not see any border. The border can also be 1: Solid Line (the
default), 2: Dashes, 3: Dots, 4: Dash Dots, 5: Dash Dot Dots, 6: Inside Solid . The
BorderWidth determines the width of the Shape’s border. Default value is 1. The
bigger this value, the thicker the border. The Visible property determines whether
the Shape should be displayed (True) or not (False) at runtime.
Lesson in Action
13
Create a new project. When you fire up VB, a New Project dialog box appears.
Select Standard Exe, and click the Open button.
1. Customize the Form.
Name frmMain
Caption My First Visual Basic Application
MinButton False
MaxButton False
StartUpPosition Center Screen
Height 3135
Width 4620
BackColor White
2. Place a Label control on the form.
3. Customize the Label.
Name lblBanner
Caption Welcome to Visual Basic
Font Arial, Regular
Size 24
BackColor Yellow
ForeColor Blue
Width 3735
Height 1215
Top 720
Left 360
4
4. Run your application by clicking the button.
5. Save your work as Lesson1.vbp. Do this by clicking the File menu, then
Save Project.
6. If you want to load your project again, simply click the File menu, then
Open Project. A dialog box appears. Just select the Drive and Directory
where your project is saved.
On your Own
14
1. Create an Application displaying your name. Consider the following
specifications:
Display the Maximize and Minimize buttons.
Your name should be displayed in Arial font, Size 18, Bold, color Blue.
Display a rectangle Shape control (BorderWidth=3, BorderStyle=Dots)
around the Label.
Label should be transparent.
Form should have a white Background color.
Display an icon on the Title Bar (icon file will be provided by the
instructor).
Objectives
To explore Forms and the code behind an application in design mode
To create a simple interactive application
To use and be familiar with the TextBox & CommandButton controls
and their properties
To use the concatenation operator (&)
To be able to familiar with VB events and write a event-handler
subroutine
To use the End statement
To understand and use Remarks
Notes
IN FOCUS: TEXTBOX CONTROL
TextBoxes accepts text input such as the user’s name or address. The following
are the common TextBox properties.
Property Description
Alignment Determines whether the text appears 0: left-justified, 1: right-
justified, or 2: centered within the TextBox’s boundaries.
BackColor Specifies the TextBox’s background color. Programmer selects a
color from the Color Palette or specifies a color in Hex format.
BorderStyle 0: None, 2: Fixed Single. Determines whether a single-line border
appears around the TextBox.
Enabled Boolean. Determines whether the TextBox is active. A disabled
TextBox does not accept input.
Font Specifies the font of the text. Clicking this property will invoke a font
dialog box in which you can set the font name, style, and size.
ForeColor Specifies the color of the text. Programmer selects a color from the
15
Color Palette or specifies a color in Hex format.
Height Specifies the height of the TextBox in twips.
Left Specifies the number of twips from the TextBox’s left edge to the
Form window’s left edge.
Locked Boolean. Determines whether the user can edit the text inside the
TextBox.
MaxLength Specifies the maximum length of text that the TextBox can accept.
MousePointer Determines the image of the mouse cursor when the user moves the
mouse pointer over the TextBox.
MultiLine Boolean. Determines whether the TextBox can hold multiple lines of
text (True) or just a single line of text (False).
PasswordChar Determines the character that appears in the TextBox when the user
enters a password.
ScrollBars 0: None, 1: Horizontal, 2: Vertical, 3: Both. Determines whether
scrollbars appear on the edges of a Multiline TextBox.
TabIndex Specifies the order of the TextBox in the focus order.
TabStop Boolean. Determines whether the TextBox can receive the focus.
Text Holds the text entered in the TextBox. Specified text in this property
becomes the default value that appears in the TextBox at runtime.
ToolTipText Holds the text that appears as a tooltip at runtume.
Top Specifies the number of twips from the TextBox’s top edge to the
Form window’s top edge.
Visible Boolean. Determines whether the TextBox appears (True) or is
hidden from the user (False) at runtime. Invisible TextBoxes are only
invisible at runtime.
Width Holds the width of the TextBox in twips.
Property Description
BackColor Specifies the CommandButton’s background color. Programmer
selects a color from the Color Palette or specifies a color in Hex
format. Applicable only when Style property is set to 1: Graphical.
Cancel Determines whether the CommandButton gets a click event if the
user presses Esc.
Caption Holds the text that appears on the CommandButton.
Default Determines if the CommandButton responds to an Enter keypress
16
even if another has the focus.
Enabled Boolean. Determines whether the CommandButton is active. A
disabled CommandButton is grayed out and cannot be pressed.
Font Specifies the font of the CommandButton caption. Clicking this
property will invoke a font dialog box in which you can set the font
name, style, and size.
Height Specifies the height of the CommandButton in twips.
Left Specifies the number of twips from the CommandButtons’s left
edge to the Form window’s left edge.
MousePointer Determines the image of the mouse cursor when the user moves
the mouse pointer over the CommandButton.
Picture Holds the name of an icon graphic image that appears on the
CommandButton as long as the Style property is set to 1-
Graphical.
Style Determines whether the CommandButton appears as a standard
Windows button (0: Standard) or a CommandButton with a color
and possible picture (1: Graphical)
TabIndex Specifies the order of the CommandButton in the focus order.
TabStop Boolean. Determines whether the CommandButton can receive
the focus.
ToolTipText Holds the text that appears as a tooltip at runtime.
Top Specifies the number of twips from the CommandButton’s top edge
to the Form window’s top edge.
Visible Boolean. Determines whether the CommandButton appears (True)
or is hidden from the user (False) at runtime. Invisible
CommandButtons are only invisible at runtime.
Width Holds the width of the CommandButton in twips.
IN FOCUS: EVENTS
Events, as discussed in the introduction, are the primary elements of a user and VB
interaction. Your application opens a dialog box when the user selects the Open
menu or outputs the square of two numbers when the user clicks on a button.
Selecting the menu and clicking the button are examples of events.
Events can be keyboard- or mouse-triggered. With the mouse, you can use the
MouseDown, MouseUp, and MouseMove events to enable your applications to
respond to both the location and the state of the mouse.
Event Description
17
MouseUp Occurs when the user releases any mouse button.
Click Occurs when the user clicks the selection mouse button
(may be the right or left button).
DblCLick Occurs when the user double clicks the selection mouse
button (may be the right or left button).
Keyboard clicks and key presses also provide means of data input and basic window and menu navigation. The
following are the events you can trigger using the keyboard:
Event Description
KeyDown Occurs when a key is in its down state (when the user
presses the any key).
How do a KeyPress and KeyDown or a MouseDown and a Click differ from each
other? KeyPress and MouseDown are keyboard/mouse state related. They occur at
that instant when the mouse button is clicked down and a key is pressed down.
This means the events occur before the mouse button or key is released back to its
normal state. Click and KeyPress occur after the user has clicked the mouse or
pressed a key.
18
Visual Basic automatically creates an Event Procedure for you in the format:
End Sub
The End statement ends an application immediately. No code after the End
statement is executed. The program will also not respond to further events. To end
the program, simply execute the statement End as in the following example:
IN FOCUS: REMARKS
Remarks are notes that you write in your code. These notes are commonly used to
help clarify some code, explain codes to readers, state the programmer’s name and
the date the program was written, and describe the purpose of the program. Since
remarks are intended for people, they are completely ignored by VB.
19
VB supports two kinds of remarks:
Remarks that begin with the Rem statement
e.g.
Rem Programmer: Jay R.C. Fernandez
Rem Computer Center
Rem 17 May 2001
Rem This program computes for the average of 3 numbers.
Lesson in Action
The application that will ask for the user’s first and last name and outputs “Hello
<firstname> <lastname>!” in a label. The visual representation of the program is
as follows:
20
Width 6195
BackColor White
21
Text None. Erase Default Value
Width 3495
Height 495
Top 1080
Left 2160
7. Run the application and see how your new application works.
8. Save your work as Lesson2.vbp.
On your Own
22
CommandButton, a caption should appear on the Label that reads “Left
Button Clicked!”. When the user clicks the second CommandButton, a
caption should appear on the Label that reads “Right Button Clicked!”.
2. Create an application with five CommandButtons
aligned vertically. Reverse the focus order so that when you run the
application and press the Tab key several times, the focus order flows
upward through the CommandButtons.
Objectives
To determine what data types VB supports; how to declare variables, and
how to assign data to variables
To able to use Arithmetic Operators
To use and understand the Val( ), Str( ), and isNumeric Functions
To apply the rule of arithmetic operator precedence
To able to write subroutines that solve mathematical problems
Notes
Programming involves data and ways of manipulating these data. Thus, you should
learn how to represent data in the computer.
You often need to store values temporarily when performing calculations with Visual
Basic. In VB, you can store values in containers called variables. Generally,
variables have a name (a string you use to refer to the variable when you want to
fetch or store value in the variable) and a data type (which determines the range of
values the variable can store and the operations defined for that type).
Data types control the internal storage of data in Visual Basic. How do we
associate a type to a variable? VB does this automatically. By default, Visual Basic
uses the Variant data type. But programmers can always associate variables to a
type explicitly.
23
Byte Positive numeric values without decimals that range from 0 to
255
Double Numeric values that range from
–1.79769313486232E+308 to 1.79769313486232E+308*
Integer Numeric values with no decimal point or fraction that range
from –32,768 to 32,767
Long Integer values with a range beyond that of Integer data
values. It ranges from
–2,147,483,648 to –2,147,483,647
String Data that consists of 0 to 65,400 characters of alphanumeric
(letters and numbers) and special characters (punctuations,
etc.).
Variant Data of any data type and used for control and other values
for which the data type is unknown.
*The value of 1.2E+6 is computed by multiplying 1.2 by 6 raise to 10. This
is equal to 1.2 times 1,000,000 = 1,200,000.
Variable Declaration
Data have different sizes, thus a variable that would contain a String value should
have enough space to accommodate strings. Variable declaration specifies how
much space VB should allocate for a variable.
How do we declare variables? You use the Dim statement through the following
syntax:
Scoping Variables
A variable is scoped as either a procedure-level (local) or module-level variable.
This depends on how it is declared.
24
Declaration: Declare variables variables within a
within a procedure. For Example: procedure.
Private Sub cmdSum_Click( )
Private x As Integer
…
End Sub
Note: You can declare 2 different variables with the same name but these variables
must be declared in different scopes. For example, you could have a public variable
named Temp and then, within a procedure, declare a local variable named Temp. If
we refer to variable Temp within the procedure, we would access the local variable.
References to Temp outside the procedure would access the public variable.
<var_name> = <expression>
<var_name> is a variable name (which you might have declared using the Dim
statement). <expression> can be a literal, another variable, a mathematical
expression, or a function call. Take the following examples:
25
‘Assigning the value of a variable to another variable
grade = score
Always bear in mind that the left and right hand side values of the assignment
operator should be of the same data type or at least of compatible type. You
cannot assign a String value to a Double variable.
You use math operators when you want to manipulate data. If you want to get the
average of 2 numbers, you will probably use the formula (x + y)/2. The following
table describes VB’s primary math operators.
26
Another matter that you should take note of is operator precedence. Precedence is
the order of computation. ^ is evaluated first, then * and /, then + and -. If there
are * and / in an expression, execution is done from left to right. This holds true to
+ and -. Let us demonstrate this in the following examples:
4 * (2 + 3)
This is equal to 20, computed by adding 2 and 3 and multiplying the sum by 4.
Without the parentheses, the value of the entire expression is 11 (multiplying 4 with
2 and adding 3 to the product).
The Val(), Str(), IsNumeric Functions are useful for data conversion: from
numbers to Strings and from Strings to numbers. Val() converts Strings to numbers.
Str() complements Val() – it converts numbers to Strings. IsNumeric() returns True
if a String argument can represent a number.
Val() is useful when you want to convert e.g. the Text property of a TextBox to a
number. This is applicable in cases when you require the user to enter a number in
the TextBox (e.g. the user’s age). The Text property of TextBoxes and the Caption
property of Labels are Strings in type, thus conversion must be done if you need
their number value. You use IsNumeric() in cases when you need to verify if
whether a particular value can be represented as a number. For example, if you
require the user’s age, and the user enters letters, you might want to notify the user
of wrong input.
strNumber = “122”
intNumber = Val(strNumber) ‘intNumber is assigned the numeric value 122
strNum = Str(intNumber) ‘strNum is assigned the string “122”
27
intAge = Val(txtAge.Text) ‘intAge is assigned the numeric value of
txtAge.Text
y = IsNumeric(intNumber) ‘y receives True
Lesson in Action
The application asks for the 2 numbers and outputs “The average of the 2 numbers
is <average>”.
28
Font Arial, Size 14, Regular
Top 960
Left 240
Width 2175
Height 495
Set the following properties for the third Label:
Name lblResult
BackColor Light Blue
Caption None. Erase Default Value
Font Arial, Size 14, Italic
Width 4815
Height 975
Top 1560
Left 240
29
Height 495
Top 2760
Left 3360
6. Write the following procedures:
On your Own
1. Write a code that declares these variables: your first name, your last name,
your age, your course, and whether you are old or new student.
_______________________________________________________________
_______________________________________________________________
_______________________________________________________________
2. Write an application that accepts your age in a TextBox and then displays,
when you click a CommandButton, your age in 10 years time.
3. Make an application that asks for an item price, the discount (if any), and the
cash given by the customer. Compute and output the selling price and the
change (cash – selling price). Refer to the Form below.
30
Lesson IV. Logical Structures
Objectives
To able to write simple decision-making statements
To be able to use the If-Then and If-Then-Else selection structures to
choose between alternative actions
To use Logical Operators
To use the Format() function
Notes
Logical structures allow nesting in the program flow. You might want to do a
particular routine if a certain condition is true, and do another routine if it isn’t. For
example, if you want to check if a student has passed a subject, what do you do?
You check if his grade is greater than or equal to the passing grade. You say
“Passed” if this is true. Otherwise, you say “Failed”.
There are a couple of logical structures in VB. What we will discuss in this lesson
are: If, If-Else, and the Select-Case statements. But before going into these, let
us discuss Comparison and Logical Operators first.
Comparison operators compare data values against each other and produce True or
False results. Put simply, we evaluate a comparison expression as True or False.
The expression 1>2 is false because 1 is not greater than 2. The following table
describes the comparison operators provided for by Visual Basic.
31
the value on the right hand side.
<= Total <= Quota Returns true of if the value on the left
hand side is less than or equal to the
value on the right hand side.
<> Course <> “CS” Returns true of if the values on the left
and right hand sides are unequal.
Note that expressions on both sides of a comparison operator should conform to the
same data type or at least compatible types. You cannot compare String and
numeric values, as this will cause a type mismatch error.
VB also supports three additional operators – And, Or, and Not. These are called
Logical Operators. Logical operators allow you to combine two or more
comparison tests into a single compound comparison expression.
The next table describes the logical operators.
IN FOCUS: IF STATEMENT
32
The If statement has the following syntax:
If <comparisonExpression> Then
One or more VB statements
End If
T
Comp VB Statement/s
Exp
F
If (Grade>90) Then
allowance = allowance + 50
End If
If <comparisonExpression> Then
One or more VB statements
T
Else CompE VB Statement/s
One or more VB statements xp
F
End If
VB Statement/s
If (grade>=60) Then
lblOutput.Caption = “You passed!”
33
Else
lblOutput.Caption = “Sorry but you failed.”
End If
The above code works but the coding is extremely difficult to follow.
Visual Basic supports another logical statement called Select Case. The syntax is
as follows:
34
CompExp N
F 1
2 T
Flowchart of Select-Case
VB Statement/s
structure VB Statement/s
to each <value>. If it finds a match, it executes the statements that immediately
follow it. It then ignores the rest of the Case statements. In the event when no
matches have been found, then the statements following the Case Else are
executed.
The Case clause has several variations. Case <value> works when you are
comparing <expression> to several specific values (e.g. Case 6, Case “Computer”).
If you want to compare it to a range of values, you use either:
The following code is the translation of the If-Else code to Select-Case. It is now
shorter and more readable.
Select Case grade
Case 50 To 70: lblOutput.Caption = “Good”
Case 71 To 85: lblOutput.Caption = “Outstanding”
Case 86 To 100: lblOutput.Caption = “Excellent”
35
Case Else: lblOutput.Caption = “Failed”
End Select
The Format() function enables you to format how data are displayed. If variable
total_cost contains the total amount of a product, you might want to display the
value of this variable in currency format (in 2 decimal places with a currency sign).
Format() does not change a value, it only changes the way a value looks. This
function returns a variant. The following is Format()’s syntax:
Format(<expression>, <strFormat>)
strFormat Description
“Fixed” Displays at least one digit before and two digits following
the decimal point, with no thousands separator.
You can also create your own strFormat. You’ll just need a combination of pound
sign and zeros to format values. Each pound sign indicates where a significant digit
goes. The zero indicates that you want either leading or trailing zeros, whether the
zero or significant or not.
Examples:
A = 123.3232
B = 23.0002
C = 12233
D = .34
36
Format Expression Result
Format(A, ”Currency”) $ 123.32
Format(D, ”Percent”) 34%
Format(B, “Fixed”) 23.00
Format(D, “###”) Nothing
Format(D, “##.###”) .34
Format(D,”0.000”) 0.340
Format(C,”#,###.00”) 12,233.00
Format(C,”#,###.##”) 12,233.
Format(C, “P #,##0.00”) P 12, 233.00
Lesson in Action
We will create an application that asks for two grades and outputs their average. It
will then display “Passed” if the average is greater than or equal to 60 or “Failed” if
the average grade is less than 60.
37
Height 5145
Width 5325
BackColor White
38
Height 1575
Top 1920
Left 240
39
Name cmdCompute
Caption COMPUTE
Width 1455
Height 495
Top 3960
Left 1800
9. Double Click on the Command Button. Enter the following code to your
cmdCompute_Click procedure.
10. Run the application and see how your new application works.
11. Save your work as Lesson4.vbp.
On your Own
4. What happens if every Case fails and there is no Case Else option?
5. Rewrite the following If statement to eliminate the Not. The logic should
still be the same.
If Not(A < 4) Or Not(college = ”Engineering”) Then
40
6. Write a program that contains a TextBox and a CommandButton. Put a
Label above the TextBox that tells the user to type a number from 1 to 10
inside the TextBox. Display a default value of 0. When the user clicks the
CommandButton, check the TextBox for a valid number. Display “Valid
Number” in another Label if the number is within the range. Display “Invalid
Number. Please enter a number from 1 to 10” when the entered value is out of
range.
Objectives
To be able to use the Do-While-Loop, Do-Until-Loop, and For-Next
repetition structures
To understand and implement counter-controlled repetition and
sentinel-controlled repetition
To understand the concept of nested control structures
Notes
Loop Structures are statements that execute instructions repeatedly. A common
practical application is when you need to compute 3^6. This expression is
evaluated by multiplying itself 6 times.
Syntax:
Do While (<comparison_test>)
One or more VB Statements
Loop
T
CompE Loop Body
xp
F
41
Flowchart of Do-While loop structure
The statements enclosed by Do-While and Loop, called the loop body, are executed
repeatedly while <comparison_test>, a boolean expression, is True.
<comparison_test> is evaluated the first time the loop begins. Thus, if
<comparison_test> is initially False, the loop body will never execute. One of the
statements in the loop body should somehow set the <comparison test> to False to
terminate the loop. If it remains True, VB will perpetually execute the statements.
This is called infinite loop and often causes the computer to appear to have hung.
Syntax:
Do Until (<comparison_test>)
One or more VB Statements
Loop
F
CompE Loop Body
xp
Do-Until loop works exactly like the Do-While loop except that the Do-Until loop
continues executing the loop body until the comparison is True. Just like Do-While,
Do-Until evaluates <comparison_test> first to determine if the loop body should be
executed.
Syntax:
Do
One or more VB Statements
Loop Until (<comparison_test>)
42
Loop Body
F
CompE
xp
This structure works exactly like the preceding two loop structures. Unlike the first
two, the loop body is executed first before evaluating <comparison_test>. If
<comparison_test> is true, VB repeats the loop body. Otherwise, VB exits the loop
and executes the statement following the loop code. Do-Loop-Until executes the
loop body at least once.
IN FOCUS: FOR LOOP STRUCTURE
Syntax:
For <counter_var> = <start_val> To <end_val> Step <increment_val>
One or more VB statements
Next <counter_var>
T
CounterVar<
Loop Body
= EndVal
43
F
Flowchart of For loop structure
The For-Loop also iterates a block of statements. Unlike the other loop structures
that we have discussed, For-Loop iterates for a specified number of times. The
number of iterations is determined by <start_val> and <end_val>, both Integers.
Initially, <counter_var>, an Integer variable, receives the value of <start_val>.
<counter_var> is incremented by the value of <increment_val> every iteration. By
default, <increment_val> is equal to 1. In this case, the loop terminates when
<counter_var> is greater than <end_val>. Thus, if <start_val> is equal to 1 and
<end_val> is equal to 5, then there would be 5 iterations. <counter_var> will have
the value 1 in the first iteration, 2 in the second iteration, and 5 in the last iteration.
The Step clause is optional (Step 1 by default). If you assign a negative value to
<increment_val>, Visual Basic counts down. The Next clause tells the For-Loop to
add <increment_val> to <counter_var> and checks if it has not gone beyond
<end_val>. The <counter_var>s after For and Next should be the same variable.
The loop body is iterated 6 times. Value of x is incremented by one every iteration
(x=2 in the first iteration, x=3 in the second iteration, .. , x=7 in the last iteration).
For x = 2 To 7 Step 2
Loop Body
Next x
The loop body is iterated 3 times. Value of x is incremented by two every iteration
(x=2 in the first iteration, x=4 in the second iteration, and x=6 in the last iteration).
At the end of the third iteration, Next x assigns the value 8 to x. Since it is greater
than 7, the <end_val>, the loop terminates.
For x = 9 To 1 Step -3
Loop Body
Next x
44
The loop body is iterated 3 times. Value of x is decremented by three every
iteration (x=9 in the first iteration, x=6 in the second iteration, and x=3 in the last
iteration). At the end of the third iteration, Next x assigns the value 0 to x. Since it
is less than 1, the <end_val>, the loop terminates.
For x = 1 To 8 Step 2 x= 1
Loop Body Do While (x<=9)
Next x Loop Body
x=x+2
Loop
Lesson in Action
Let’s create an application that asks for an integer and outputs the summation of
that number. E.g. the summation of 5 is 15 (1+2+3+4+5).
45
End Sub
The If statement makes sure that before we compute for the summation, the
number entered should be a positive number (otherwise, our program will bear an
incorrect result). intSum = intSum + x is done Val(txtNum.Text) times. If the user
entered 3, then we will be executing this statement thrice. On the first iteration,
intSum is assigned the value 1. On the second iteration, the value of x (which is 2
at the moment) is added to intSum, eventually assigning the value 3 to intSum.
Finally, the next value of x (which is 3) is added to intSum giving it the value 6.
Since Next x increments x to 4, and 4 is greater than 3 (our <end_val>), we
terminate the loop and display the value of intSum, the summation of 3.
On your Own
1. Modify the summation procedure in Lesson in Action and use Do-Until loop
instead.
3. Create a program that asks for a number and computes for its Factorial. The
Factorial of 3 is 6 (1 x 2 x 3). Factorial of 5 is 120 (1 x 2 x 3 x 4 x 5). You
may use the same Form and change the caption of the button from
“Summation” to “Factorial”. Also, make sure that the user enters a number
using the IsNumeric() Function. Display appropriate messages in the Label if
the user enters non-numeric values.
Objectives
To be able to use the MsgBox Function
To be able to use the InputBox Function
46
Notes
You use Message and Input Boxes when you need to ask the user questions or
display error messages and advise the user.
Input Box
Message Box Input Box
<intVariable> is an Integer variable that receives the return value of the function.
If you do not need to determine which button the user clicked (for example, when
there is only one button), you may use the function by executing:
47
vbYesNoCancel 3 Displays the Yes, No, and Cancel
buttons.
vbYesNo 4 Displays the Yes and No buttons.
vbRetryCancel 5 Displays the Retry and Cancel
buttons.
The Buttons displayed in a Message Box
If your Message Box has more than 1 button, you determine which button is
pressed by checking the value of <intVariable>. The return values are enumerated
in the following table.
The sample Message Box on the previous page was created through:
MsgBox "You must enter A, B, or C.", vbCritical, "Error"
Input Box is very similar to a Message Box but instead of the 7 return values that
indicate which button was pressed, the Input Box returns a string data value
entered by the user.
48
The following is the format of Input Box function:
<str_prompt> works like <str_message> value in Message Box. It is the text that
appears in the Input Box. It is usually an instruction on what the user should enter
in the TextBox provided for in the Input Box. <str_title> is what appears in the
Title Bar. <str_default> is the default String in the TextBox. <intXPos> and
<intYpos> determine the position of the Input Box relative to the Form. They hold
the number of twips from the top and left edge of the Form window to the top and
left edge of the Input Box, respectively. <str_title>, <str_default>, <intXPos>,
<intYpos> are optional parameters.
Input Boxes always containt Ok and Cancel buttons. If the user presses the Ok
button, the function returns the String entered in the TextBox. If the user presses
the Cancel button, a null String (“”) is returned.
Examples:
49
Lesson in Action
The following application uses both Input and Message Boxes. When the
application is executed (therefore, place your code in the Form_Load procedure),
an Input Box will ask for a number from 1 to 10. A Message Box is displayed
when the user enters a number not in the range. When a valid entry is received,
simply display that value in a Label on the Form.
The following are screen shots of the Input and Message Boxes.
Write the
following
procedure:
On your Own
1. Write an application that asks for your age through an InputBox() and then
displays your age 5 years ago through a MsgBox(). Display a default value
of 10 in the InputBox. Note: if the age entered is <=5, output “You were
not yet born 5 years ago”. The InputBox should automatically appear
during program startup.
50
2. Create a program with one CommandButton and one Label. When the
user presses the button, a MsgBox appears with 3 buttons: Yes, No,
Cancel. Display which button was clicked in the Label.
Objectives
To use the Frame and OptionButton controls
To show how Frames work with OptionButtons
Notes
OptionButtons are sometimes called radio buttons. The user can only select one
button among a set of buttons. Buttons are grouped in sets with the use of another
Visual Basic control called Frame. A Frame is a rectangular region that holds other
controls and groups these into a single set. When one button is selected in a set of
option buttons, the rest are automatically deselected by Visual Basic. Thus,
OptionButtons are useful in cases like when you want the user to select a gender
(either male or female; one can never be both male and female).
OptionButtons have similar properties with that of a Label. The text that you see
beside the OptionButton is its caption property; hence, you don’t have to place a
Label to identify it.
Warning: When option buttons are not placed in Frames, Visual Basic assumes that
the option buttons are independent of each other. Thus, the user can select
any of them at the same time (in our example above, the user can be both
male and female).
51
Lesson in Action
optBlue
optRed
What the above procedures do is to format the Label based on which OptionButton
is selected. If the user selects Blue, VB changes the background color of the Label to
blue (through the BackColor property) and sets its caption property to “Blue”.
vbRed and vbBlue are color named literals. Since hex color formats are difficult to
remember, VB provides you with these values that represent hex values of
commonly used colors. The other colors aside from vbBlue and vbRed are as
follows:
Literal Color
vbBlack Black
VbGreen Green
VbYellow Yellow
VbMagenta Magent
a
VbCyan Cyan
VbWHite White
52
Save your work as Lesson7.vbp.
On your Own
Instructions: Create a short math drill. The drill contains 3 items. When the
user presses a button labeled Check Score, a Message Box appears revealing the
his score (e.g. You correctly answered 2 items!). The following is how the Form
should look like.
Objectives
To be able to use and be familiar with the Checkbox and its properties
To be familiar with the different Checkbox styles
Notes
CheckBoxes work just like the OptionButton, with two differences: a selected
CheckBox shows the selection with a checkmark and are never mutually exclusive.
Therefore, the user can select one or more CheckBoxes even if those boxes reside in
the same Frame or on the same Form.
53
Examples of Checkboxes
CheckBoxes may also look like CommandButtons (only that a checked graphical
CheckBox appears in a pressed state). Just set the Style property to 1: Graphical
(the examples above are CheckBoxes of Style set to 0: Standard, which is the
default). The following Form illustrates the various CheckBox property options
available.
Lesson in Action
The application below demonstrates the use of CheckBoxes. The application
counts how many items have been checked and displays the number when the user
presses the “Ok” button.
54
Private Sub cmdOk_Click()
Cnt = 0
If chkMath.Value = 1 Then
Cnt = Cnt + 1
End If
If chkScience.Value = 1 Then
Cnt = Cnt + 1
End If
If chkLiterature.Value = 1 Then
Cnt = Cnt + 1
End If
If chkHistory.Value = 1 Then
Cnt = Cnt + 1
End If
lblOutput.Caption = "You have checked " & Str(Cnt) & " subject(s)."
End Sub
55
On your Own
Add-ons:
Extra Cheese P 8.00
Extra Ham P10.00
Extra Onions P 5.00
The total cost should reflect in a Label. Your application should look like the
following Form:
2. Make a program that formats the Label’s display using 3 CheckBoxes. The
CheckBoxes are: Bold, Italic, and Underlined. If the user checks Bold, then
the Label’s caption is made bold. Refer to the Form below.
56
Objectives
To create selection lists at design time using ListBox and ComboBox
To be able to differentiate ListBox from a ComboBox
To be able to add/remove an item from a ListBox or ComboBox at
runtime.
Notes
IN FOCUS: LISTBOX
ListBox gives the user a choice of several values. The user selects an option
instead of typing a value into a Textbox. The ListBox ensures that the user always
chooses one of the available options.
As in the figure above, the ListBox displays scrollbars if it is not tall enough or wide
enough to display all its data. The contents of the ListBox may be set at design time
or at runtime.
Property Description
BackColor Specifies the ListBox’s background color
Columns Determines the number of columns. If 0, the ListBox scrolls
vertically in a single column. If 1 or more, the ListBox items
appear in the number of columns specified (one or more
columns) and a horizontal scrollbar appears so you can see all
the items in the list.
IntegralHeight Boolean. Determines whether the ListBox can display partial
items, such as the upper half of an item that falls toward the
57
bottom of the ListBox. True (default): Does not display partial
items
List Holds the items in your ListBox.
MultiSelect The state of the ListBox’s selection rules. If 0-None (the
default), the user can select only one item by clicking with the
mouse or by pressing the spacebar over an item. If 1-Simple,
the user can select more than 1 item by clicking with the
mouse or by pressing the spacebar over items in the list. If 2-
Extended, the user can select multiple items using Shift-click
and Shift-arrow to extend the selection from a previously
selected item to the current one. Control-click either selects or
deselects an item from the list.
Sorted Determines whether the ListBox values are automatically
sorted. If False (the default value), the values appear in the
same order in which the program added the items to the list.
Style Determines whether the list box appears in its usual list format
or, as in the figure in the previous page, with the Checkbox
before the items.
The following are the methods supported by ListBoxes. These methods help the
user initialize, add items to, and remove items from a ListBox.
Method Description
AddItem Adds a single item to the ListBox
Clear Removes all items from the ListBox
List A string array that holds items from within the ListBox.
ListCount The total number of ListBox items.
RemoveItem Removes a single item from the ListBox.
where ListCourses is the name of the ListBox and “Computer Science” is the item
to be added.
58
ListCourses.RemoveItem(0)
ListCourses.Clear
IN FOCUS: COMBOBOX
ComboBoxes work much like ListBoxes except that these may allow the user to
add items to a ComboBox at runtime through a built-in TextBox. VB has three kinds
of ComboBoxes. All the properties of a ListBox apply to a ComboBox.
Kind Description
Drop-down Displays only one item unless the user clicks the ‚ button to
ComboBox display additional items (a scrollbar appears if there are more
items than what the ComboBox can display). The user can
also enter values at the top of the ComboBox in the same way
you do in a TextBox.
Simple Looks like a ListBox attached to a TextBox. Items are
ComboBox displayed as if they were in a ListBox. You may also enter
values on top of the ComboBox.
Drop-down Do not allow you to enter values, so it is similar to a ListBox.
ListBox It looks like a Drop-down ComboBox.
Use the Style property to switch from one kind of ComboBox to another. The Form
below displays the three kinds.
59
Lesson in Action
Let us make an application that formats the font style of a Label. A ListBox will
provide a list of available font names.
The ListBox contains the following font names: Arial, Century Gothic, Times New
Roman, and Tahoma. You may add several others.
Now when we select a font from the ones in the ListBox, the Label should
automatically be formatted. Thus, the main event will be a click on the ListBox.
The code is a short one. We just need to assign the Text property of the currently
selected ListBox item to the FontName property of the Label.
60
On your Own
Instructions: Make a program that computes for a pizza’s price based on the size
and toppings selected.
Size:
Small P 40.00
Medium P 75.00
Family P 100.00
Large P 140.00
Extra Toppings:
Cheese P 5.00
Ham P 15.00
Onions P 8.00
Pepper P 10.00
Base your program design on the following Form.
Objectives
To be able to use Horizontal and Vertical Scrollbar controls to select
from ranges of values.
To be able to use Scrollbars to manipulate other controls.
Notes
Scrollbars let users control value changes. Rather than type specific values, the user
can move the scrollbar with the mouse to specify relative positions within a range of
values. There are two types of scrollbars: Horizontal and Vertical Scrollbars.
Except for their orientation, they share exactly the same properties.
61
Example of a Horizontal Scrollbar (Left) and a Vertical Scrollbar (Right)
Property Description
LargeChange Specifies the amount that the scrollbar’s Value property
changes when the user clicks within the scrollbar’s shaft
area.
Max Indicates the maximum number of units that the scrollbar
value represents at its highest setting. The range is from
1 to 32,767 (the default Max value)
Min Indicates the minimum number of units the scrollbar value
represents at its lowest setting. The range is from 1 (the
default Min value) to 32,767.
SmallChange Specifies the amount that the scrollbar’s Value property
changes when the user clicks an arrow at either end of
the scrollbar.
Value Contains the units of measurement currently represented
by the position of the scrollbar.
When you place a scrollbar on a Form, set the range of values the scrollbar is to
represent. Set the Min and Max property to the lowest and highest value the
scrollbar will represent, respectively. When the user eventually clicks any arrow in
the scrollbar, the Value of the scrollbar will change (positive SmallChange when the
right or up arrow is clicked; negative SmallChange when the left or down arrow is
clicked).
Lesson in Action
Let’s use the ScrollBar in a simple application. In the Form below, the ScrollBar
will be used to manipulate the font size of the Label. The main task is simply to
associate the Value property of the scrollbar to the FontSize property of the Label.
Thus, changing the ScrollBar’s Value will subsequently change the FontSize of the
Label.
62
1. Create the Form displayed above.
2. Drag a Label control to the Form and set the following properties:
Name lblBanner
Caption Visual Basic
FontSize 8
FontStyle Arial
BackColor Yellow
On your Own
1. Create a program that manipulates the position of the Label in the Form
using Vertical and Horizontal Scrollbars. Note: Make sure that the Label does not
go beyond the rectangular Shape control.
63
2. Modify the program you have made in the Lesson in Action section.
Display the current font size in a Label.
Objectives
To use FileListBox, DirectoryListBox, and DriveListBox
To understand how these 3 controls interact in a simple application
Notes
A FileListBox is a list of files in a specified directory. A DirListBox displays the
directory structure of a specified drive. DriveListBoxes lists the drive structure of
the user’s computer.
These three controls are initially independent of each other in the Form. Thus, it is
your job to tie them up together. What you can probably do is to update the
contents the FileListBox whenever the user selects a new folder in the DirListBox.
You can also update the directory structure of this DirListBox whenever the user
selects a new drive in the DriveListBox. The primary event of these controls is
Change() — when the user selects a new item in these ListBoxes.
64
The following are the properties of a FileListBox:
Property Description
Archive Boolean. Specifies whether or not archive attributes
are displayed. Default is True.
Hidden Boolean. Specifies whether or not hidden attributes
are displayed. Default is False.
MultiSelect Integer. Specifies whether or not the user can make
multiple selections
Path String. Specifies the current path.
Pattern String. Specifies the files displayed in the FileListBox
ReadOnly Boolean. Specifies whether or not read-only attributes
are displayed. Default is True.
System Boolean. Specifies whether or not system attributes are
displayed. Default is True.
The most important method of a DriveListBox is Drive. The drive method returns
the current drive (in the form C: or D:) of the DriveListBox. Using DirectoryListBox,
the Path method gives you the path to the current folder or directory (e.g.
C:\myfiles\computer).
Lesson in Action
65
Private Sub dirDirectory_Change()
filFiles.Path = dirDirectory.Path
End Sub
On your Own
Modify the application you have created in the Lesson in Action section. In a
Label, display the number of files found with the specified pattern in a specified
location. When the user selects a file in the FileListBox, the file name complete
with its path (drive and directory) appears in another Label.
Objectives
To be able to use and be familiar with the ImageBox control and its
properties.
To be able to use and be familiar with the PictureBox control and its
properties.
To be able to know how the ImageBox differs from PictureBox.
Notes
66
ImageBox and PictureBox share the following properties:
Property Description
BorderStyle Determines the whether the controls have borders (O:
None 1: Fixed Single)
Height Specifies the height of the control
Left Specifies the number of twips from the control’s left edge
to the Form window’s left edge.
Picture Sets the graphic image to be displayed in the control.
Select a file through the dialog box that appears when
this property is clicked.
Visible Determines if the control is visible at runtime.
Once you place an ImageBox or PictureBox on the Form, you can resize the controls
just as you can other controls by dragging the controls’ sizing handles in and out.
The ImageBox has a unique boolean property called Stretch. It determines whether
a graphic resizes to fit the size of the ImageBox. When you resize a PictureBox to a
size smaller than the graphic image, the PictureBox will truncate or clip the image
that does not fit in the PictureBox. Only a portion of the image is displayed. This
holds true to ImageBox if the Stretch property is set to False (the default).
You can set a background color for the PictureBox using the BackColor property.
PictureBoxes also have the AutoSize property. This property, set to False by default,
determines how the PictureBox responds to a loaded image’s size. If Autosize is
False, the control does not resize to fit the image. If however, AutoSize is True, the
control resizes and does not truncate the image. Therefore, the PictureBox’s size is
depends on the size of the image to be displayed.
Loading Pictures
You can load a picture in an ImageBox or PictureBox through:
selecting the image file through a dialog box that appears when the
Picture property is selected
invoking the LoadPicture() function at runtime.
e.g. imgPicture.Picture = LoadPicture(“C:\mypic.jpg”)
67
The following are the file types supported by the Image Control
Lesson in Action
We will create a simple Icon Viewer using the ImageBox control. Icons are small
graphical images with .ico filename extensions. We will have to use the
FileListBox, DirectoryListBox, and DriveListBox controls to browse through the
file system of the computer.
68
On your Own
Instructions: Let’s create a simple guessing game using Picture Box. Using the
Form below, the
user guesses which between the 2 PictureBoxes conceals a particular image e.g.
Apple. The
user clicks the button of his choice.
After the user has given his choice, reveal the two images. In the Label, display
You Got it Right! or Sorry, but it’s not there! whenever the user selects a correct or
incorrect choice, respectively. Refer to the Form below.
Note: Randomize the location of the images. Download images here: apple.jpg
and grape.jpg.
69
Lesson XIII. Timer
Objectives
To know how Timer works
To use Timer control in time-dependent applications
Notes
The Timer control works in the background – you do not see it on the Form at
runtime. The primary purpose of a Timer is to trigger an event at a certain interval.
The following are the properties of a Timer.
Property Description
Enabled Determines whether the Timer can respond to events.
Index Specifies the subscript of the control in a control array.
Interval Specifies the number of milliseconds between calls to a
Timer control’s Timer event. The value must be within
the range of 1 to 65535. This value is in millisecond (or a
thousandth of a second).
What can we do with a Timer? You may want to replace the caption property of a
Label with another quotation every 5 seconds. You may want to simulate animation
by replacing the image of an ImageBox every half a second. Or you may simply
want to give a time-pressured quiz – a sequence of questions appears one after
another at an interval of 10 seconds.
The Timer has one event, the Time event. The procedure <timer_name>.Timer( )
is executed every <interval_value> milliseconds. The Timer control continues this
until we disable the control by setting the Enabled property to False.
Lesson in Action
Let’s have some fun and create a small animation. Animation involves a series of
still images displayed in rapid sequence. We will need several images of an object
to be animated at different times. For this application, we will make a dog walk.
70
The images are named dog1.wmf, dog2.wmf, dog3.wmf, dog4.wmf, and dog5.wmf.
You will later know why we have to make the names similar.
71
What the above code does is to change the picture by calling the
LoadPicture() function. "\dog" & Trim(Str(x)) & ".wmf" specifies the filename
of the image to be loaded and displayed. Variables x serves as our counter.
If x is currently one, then we load dog1.wmf. If it is 2, then we load
dog2.wmf. Had we not named the pictures such, we will have to write the
filenames lexically.
Public x As Integer
On your Own
1. Add a button to the Dog Animation application with caption “Pause”. If the
user presses the Pause button, the animation stops and the caption of the button
changes to “Play”. If the user clicks the Play button, animation resumes.
2. Create an application. Add a Label to the Form with the caption “Timer”.
Set the Font property to Arial, size 6. Drag a Timer control as well. Every
second, add 3 points to the Label’s font size. When the font size grows to a
value that will make the caption too big for the Label, set the font size back to 6
points and start increasing the size once again.
Objectives
To understand how to construct programs modularly from procedures
and functions
To be able to create new procedures and functions
To understand the mechanisms used to pass information between
procedures and functions
To understand the Exit Sub and Exit Function Statement
72
To understand how the visibility of identifiers is limited to specific
regions of programs
To be able to create and use code modules
Notes
Type Description
Visual Basic Procedures provided by Microsoft to perform
Procedures common tasks (e.g. Format(), Str(), Val())
Sub Procedures A block of statements that perform a particular
task. They may receive data from the calling
Procedure.
Event Procedures Similar to Sub Procedures but the Procedure is
executed as a response to an event (e.g. keypress)
Function Similar to Sub Procedures but return a value to the
Procedures calling Procedure
73
x=y+z
lblSum.Caption = “Sum is “ & Str(x)
End Sub
Caller Callee
<return_value_data_type> specifies the data type of the return value. Recall that
all Function Procedures must return a value to the calling procedure. How do we
return a result? You assign the result to a variable whose name is the same with
the Function Procedure name. In the example above, we return the result through
ComputeSum variable. Note: <return_value_data_type> is optional. If you don’t
specify it, the return value will have a Variant data type.
74
Another thing that you should take note in using Function Procedures are the
arguments. Function Procedures may have arguments, and in this case, the calling
procedure must pass the same number of arguments. The order of the arguments
to be passed to the Function must correspond to the order of arguments in the
Function header with respect to the data types. This means that if the Function
requires 2 values, one String and one Boolean, the calling procedure must pass one
String and one Boolean in this order. We will learn more about this parameter
passing process in the following section.
Parameter Passing is a process by which the caller (or the calling procedure) passes
(or transmits) the parameter (or actual arguments) to a called procedure and binds
the actual arguments to the formal parameters. Procedures communicate with each
other through this process. A particular procedure might have this particular
capability and for other procedures to take advantage of its services, it needs to
know the procedure’s name and the data it needs, if any.
There are two parameter passing conventions supported by Visual Basic: Pass-by-
Value and Pass-by-Reference.
Call-by-Value
In Call-by-Value, a copy of the argument’s value is passed, thus, the called
procedure do not manipulate the caller’s data because it is the copy that it received.
There is one known disadvantage: if we have numerous arguments with large sizes,
we incur an overhead of copying large amounts of data. This may cause our
application to run slow.
Call-by-Reference
Call-by-Reference is the default method. The caller gives the called procedure the
ability to directly access the caller’s data and to modify the data if the called
procedure chooses. This is accomplished by passing the reference (the addresses of
the variables) to the arguments. Because of this, duplication is avoided but it has
weak security.
75
Since this is the default passing convention, you need do tell the called procedure to
receive the reference instead of the value. There is one explicit way of doing this:
precede the corresponding parameter variable in the procedure definition with
keyword ByRef as in the following example:
Visual Basic allows programmers to create procedures that take one or more
optional arguments – the caller has the option of passing that particular argument.
-----
Call AAA() ‘Invalid because the first argument is mandatory
Call AAA(True) ‘Valid
Call AAA(True, 10) ‘Valid
IN FOCUS: EXIT SUB AND EXIT FUNCTION
Exit Sub and Exit Function alter the flow of control. They cause an immediate exit
from a Sub Procedure and Function Procedure, respectively. When this happens,
control is then returned to the caller and the next statement in sequence after the
call is executed.
76
IN FOCUS: STATIC PROCEDURES AND VARIABLES
Variables declared within procedures, also known as local variables, are allocated
space when the procedure is active (when it is currently being executed)
and deallocated space when the procedure terminates. Programming
Languages are designed this way to save space – outside of the procedures,
local variables are often not needed, and thus we can just do away with
these. When a variable is deallocated space, the datum stored in it is
erased.
There are cases when you want to maintain a variable all throughout the program’s
execution time. You can do this either by declaring the variable outside of
Procedures or by making them Static. Static variables are allocated and initialized
once the Form is loaded. You declare a Static variable through preceding a variable
declaration with the keyword Static. For example,
If you want to make all local variables Static, you can just create a Static Procedure.
Lesson in Action
Let’s create a simple application that determines the smallest value among 3
numbers entered in 3 TextBoxes. What we need is an interface and a Function
that will determine the smallest value.
77
Write the following procedures.
v1 = val(txtNum1.Text)
v2 = val(txtNum2.Text)
v3 = val(txtNum3.Text)
On your Own
1. Write a Function Procedure that accepts an Integer and returns its square.
78
Lesson XV. Working with Multiple Forms
Objectives
To create applications consisting of more than one Form
To include in applications Forms that have been created previously
To provide simple code to enable users to navigate between Forms at
runtime
Notes
When you create a new project, VB provides a blank Form named Form1. You can
create an application with this Form, but for complex applications, you may need to
work with multiple Forms. For example, it is common to have a welcome screen and
a main Form that branches to different Forms. The high level structure of an
interactive application can often be understood best from a diagram showing the
Forms hierarchy. You can have 3 Forms in your project: One Form might be the
opening Form, the other two for Addition and Multiplication routines. Just imagine
how a Form would look like if it has so many functionalities. It would probably look
cluttered and confusing.
On the Tool Bar, click the Add Form icon . Click Form. This will display
the following dialog box:
79
You can also add another Form by doing a right-click on the Project
Explorer, Click Add, then Click Form.
If you want to add an existing Form (in case your new project needs a Form you
have previously created for another project), follow the same steps but instead:
Method 1: Select Existing Tab of the dialog box displayed above, locate the
Form, select the Form, and click Open.
Method 2: Click Add File instead of Form. Locate the Form, select the
Form, and click Open.
Note: The added Form will have a default name of Form1. Make sure that there
are no other Forms currently in the project with this name. A loading error will
occur if name duplicate is found. You may notice that the filename of this added
Form still has its original filename. This is because VB keeps only one copy of each
file (even if it is used in different applications). So if you want to use and modify an
existing file, you must save it as another file with the Save As option by doing a
right-click on the Form icon in the Project Explorer, click Save
<theOrigFileName> As…, provide a new filename, select the directory where
you would be saving the Form, and click Save.
You may also remove a Form from a project by selecting the Form on the Project
Explorer, then clicking Remove <form_filename>.
frmForm1.Hide
frmForm2.Show
Note: frmForm1 is the Form’s name. Do not confuse this with the Form’s filename
(the one with the .frm extension).
Every Form that is the screen displayed is first loaded into memory. Even when it is
hidden it still remains loaded in memory. This is not a problem with two or three
Forms, but if you have many Forms, you can run out of available memory. If this
happens the solution is to unload some of the Forms the program no longer need.
Use the Unload command to do this:
Unload frmForm1
80
Conversely, the Load command loads a Form into memory without displaying it.
This is usually unnecessary since VB performs a load automatically if the Form to be
displayed is not yet in memory.
You can also show a Form without hiding the current one. In this case, you will
have several Forms on top of the other – the top most is the active one. You may
not want this to happen if do not want the user to interact with another Form
without unloading or disabling the current one. One situation is when you have a
hierarchy of Forms:
Form1
The Main Menu
Form2 Form3
Science Mathematics
Form4 Form5
Biology Chemistry
The Form1 displays the main menu that branches out to Science and Mathematics.
Once the user clicks on the button that leads to Science, you may want to disable
Form1 until the user closes Form2. In this case, there is only one way of going to
Mathematics: through Form1.
We do this by disabling a Form through the Enable property before showing another
Form as in the following statements:
frmMainMenu.Enable = False
frmScience.Show
Somehow, the user is able to close frmScience and focus is given back to
frmMainMenu. We do this by unloading frmScience, enabling frmMainMenu and
giving back the focus to it (note that enabling a Form does not give the Form the
focus). The code will be:
Unload FrmScience
frmMainMenu.Enable = True
81
frmMainMenu.SetFocus ‘Set the focus to frmMainMenu
There is an easier way of doing this. The procedure below calls frmScience with two
arguments: vbModal and Me. vbModal tells VB that the current Form should be
disabled until the called Form is unloaded. Me means that the calling Form is the
owner of the called Form, and that when the latter is unloaded, control is passed to
the owner Form.
Since you have more than one Form in your project, you have to tell Visual Basic
which Form should be displayed during startup. You specify the startup Form
through:
Sometimes you might want your application to start without any Form initially
loaded. For example, you might want to execute code that initializes a couple of
variables before displaying any Form. You can do this by creating a Sub Procedure
called Main in a standard module, as in the following example:
Sub Main( )
intStatus = “Locked”
'Show a startup form
frmMain.Show
82
Lesson in Action
Let’s create an application with 3 Forms. The first Form (frmMain), as shown below,
is the Main Menu. The button labeled Mathematics loads the Mathematics Form
(frmMath). The button labeled Science loads the Form (frmScience).
Set the StartUpPosition of frmMain to 2-CenterScreen. For the 2 other Forms, set
this property to 1 – CenterOwner.
83
Private Sub cmdQuit_Click()
End
End Sub
On your Own
4. Create a simple login functionality. Add 2 Forms to a project. The first Form
asks for a password in a TextBox. Assume that the password is “Letmein”
with the quotes. When the user enters this password, unload this Form and
load the other Form. Otherwise, prompt the user of the incorrect password
using a MsgBox.
Lesson XVI. Working with Menus
Objectives
To be able to create menus to enhance application’s GUI
To be able to use menus to trigger Event Procedures
Notes
If you have been working with the Windows TM operating system, you already have
been exposed to menus. When you open a file in Microsoft Word TM, insert a
PowerPointTM slide, or exit a Windows application, you use menus to select the
functionality you need. What you may not know is that the menu selections File and
Exit are independent controls that VB can create for you using the menu editor.
84
Menus are groups of related commands. The concept that a menu selection is really
a control is because menus support properties and events, just like any other
controls we have been using.
Menus support only one event, the click event (occurs when a menu item is
selected).
Before we get into the menu editor, in which you can set properties of a menu
control, let us look at the complete list of menu control properties.
Properties Description
Caption The visible text you see on the menu item
Name The name used in code to refer to the menu control
Checked Determines whether a small check mark is
displayed to the left of the menu control
Visible Determines whether a menu control can be seen
Enabled If False, the text is grayed out and cannot be
selected
Index If you create a menu control array rather than
name individual menu items uniquely, this property
specifies the menu item’s subscript within the
control array.
Shortcut A key sequence that will invoke the menu
HelpContextID Determines which topic in the help file will be
displayed
NegotiatePosition Works in conjunction with OLE embedment to
determine which menu controls are displayed
WindowList Determines whether a menu control maintains a list
of the current MDI child windows
Our task is to create the menu structure using the Menu Editor and to set the
properties for each menu. Then we add code to each Click event to perform
whatever function you choose in response to a user selection of the menu items.
85
IN FOCUS: MENU EDITOR
As you can see, the editor has two general sections. In the top half, you set the
properties we enumerated on the previous page. In the bottom half you create the
hierarchical structure of the menu (the hierarchy determines how the menu items
are organized and displayed on the Form).
Remember that menus are only associated with a Form. No other control has a
menu. VB provides the built-in ability to manage the display of all of the menu
items. You only have to create the structure and let VB handle it from that point on.
Now, let's talk about each of the properties and see if there's some guidance on
what to use for the properties.
86
identification, the name should be prefixed with
mnu e.g. mnuFile, mnuEdit.
Checked Menu items are either checked or not. You can
check it from within the menu editor or by using
code. Generally, you’ll add checkmarks to menu
options that perform on or off actions, such as
to display or not to display a Form. For
example, this code will cause a menu item to be
displayed with a small checkmark to its left:
mnuFileOpen.checked = True
mnuFileOpen.visible = False
MnuFileOpen.enabled = False
87
Lesson in Action
As shown in the previous page, The File menu has 3 menu items: Open, Close, and
Exit. When we dig in the Open submenu, we can find the items labeled Form and
Project. Under the Edit menu, we have items Copy, Paste, Search, and Replace.
Follow through the following steps:
88
14.For the Close submenu:
Caption &Close
Name mnuClose
Enabled Disable by unchecking the checkbox
15.Click Next.
16.For the Exit submenu:
Caption &Exit
Name mnuExit
17.Click Next.
18.Click the left arrow (ç) button.
19.Create the Edit menu.
Caption &Edit
Name mnuEdit
20.Click Next.
21.Click the right arrow (è) button to add items for the Edit menu.
22.For the Copy menu item:
Caption &Copy
Name mnuCopy
Shortcut Ctrl+C
23.ClickNext.
24.For the Paste menu item:
Caption &Paste
Name mnuPaste
Shortcut Ctrl+V
25.Click Next.
26.Let's insert a divider.
Caption - (one dash)
Name Any name. We won't be referring to this anyway.
27.Click Next.
28.For the Search menu item:
Caption &Search
Name mnuSearch
Shortcut F3
29.Click Next.
30.For the Replace menu item:
Caption &Replace
Name mnuReplace
Shortcut F4
31.Click Next.
32.For the Case Sensitive menu item:
Caption Case Sensitive
Name mnuCase
Checked check the checkbox
33.Click Ok.
89
You can always edit an existing menu structure.
Delete an item: just select the menu item and press the Delete button.
Edit the properties of a menu item: select the item to be edited and edit
the properties.
Modify the order of items listed in the menu editor: select the item and
press either the up (é) or down (ê) button. You can still use the left (ç) or
right (è) buttons to move items from one level to another.
To insert a menu item: Select the position in the menu hierarchy where
you will insert the item and press the Insert button.
On your Own
Create a new project with the following menu bar items: Lessons, and Options.
The menu structure is as follows:
A. Lessons
1. Mathematics
a. Addition
b. Subtraction
2. Science
a. Animals
b. Plants
B. Options
1. Audio On (Checked item)
2. Input Device (Checked item)
a. Keyboard
b. Mouse
Note: Only one Input Device should be checked at a time. If the user selects
Keyboard, then Mouse should be unchecked.
Objectives
To understand the array data structure
To understand controls arrays
To use control arrays in an application
To be able to declare and manipulate arrays
To be able to pass arrays to procedures
90
Notes IN FOCUS: DATA ARRAYS
Arrays are data structures consisting of contiguous memory “cells” of the same
name and type. For example, we can have an array of student names. In Visual
Basic, we refer to each element in an array through an index e.g. name(0),
name(1), .., name(n).
Declaration
Arrays should be declared so that the compiler can determine the amount of
memory space to allocate. Recall that data types have different memory
requirements. You declare arrays through the following syntax:
Examples:
a. Dim grade(7) As Integer
b. Dim grade(7) As Integer, name(7) As String
Example a. tells the compiler to reserve six elements for array grade of type Integer.
The value 7 tells defines the upper bound of the array. The compiler allocates 7
“cells” of equal memory sizes with indices starting at 0 (the lower bound) until 6.
Note: Unlike other variables, arrays should implicitly be declared. Not doing so is a
syntax error. Arrays may be declared in Code or Form Module but may only be
declared Public in the former.
Numeric array elements are initialized to zero (0) by default. Strings are initialized
to a zero-length String. The programmer can also initialize the array with user-
defined values. Take the following examples:
a. grade(0) = 9
grade(1) = 5
b. For x = 0 To 7
grade(x) = 2
Next x
c. For x = 0 To 6
grade(x+a) = 2 ‘Make sure that the expression x+a evaluates to a Long
value
Next x
Passing Arrays
Arrays can be passed to a procedure. To do so, specify the name of the array
followed by a pair of empty parentheses. For example:
91
Call ComputeAverage( grade() )
You can also pass selected elements of an array, as in the following example:
Take note that array or individual array element arguments are always passed by
reference – the procedure can modify the contents of the original array.
On the part of the called procedure, its parameter list must specify that an array will
be received. The procedure header of ComputeAverage might be written as:
The header indicates that the procedure expects to receive integer array in formal
parameter x. The size of x is not specified because it will be referring to the actual
argument array grade() (by virtue of pass by reference).
On the other hand, if the procedure expects to receive an individual array element,
you write the procedure header as you do in expecting non-array arguments. An
example is:
Arrays can have multiple dimensions. One use of this is when you want to represent
data in a table (where each data, is in a spreadsheet, is referred to by its column
and row number). In Visual Basic, we declare, say a 2-dimensional array, through:
Note: Refer to each element as point(2,3) and not as point(2)(3). The latter is a
syntax error.
Visual Basic supports 60 array dimensions, but normally, programmers only need to
use no more than 3 dimensions.
92
IN FOCUS: DYNAMIC ARRAYS
Dynamic arrays are flexible arrays – their size can be changed during the course of
the program execution. Dynamic arrays are very useful when you do not know how
many elements to store in the array during development (programming) time.
ReDim student(8)
ReDim must be written within procedures. You can ReDim an array many times.
It can also be used to change the index bounds. The statement
Note: During declaration, the number of dimensions of the array is not yet
specified. This is determined the first time ReDim is used. Once this is done, the
number of dimensions cannot be changed.
When ReDim is used, all the contents of the array are erased. Numeric arrays are
initialized to 0 and Strings to a zero-length String. If you want to retain the
values, use the keyword Preserve as in the following statement:
If you need to erase the text property of 10 TextBoxes, what do you do? You
make 10 statements: txtName0.Text = “”, txtName1.Text = “”, …, txtName9.Text =
“”. This is one heck of a job. With control arrays, you can group related controls
and refer to each control by an index. We then refer to the TextBoxes as
txtName(0), txtName(1), …, txtName(9). To solve the problem, we write the
following code:
For x= 0 To 9
txtName(x).Text = “”
Next x
93
Note that the names of the controls are all the same. They only vary in index (when
a control is part of a control array, an Index property is added). A control array is
an array of the same control. This means you cannot have an array composed of
TextBoxes and Labels. One good thing about controls array is that when you
format one control (e.g. changing the BackColor property), the format is applied to
all other controls in the array.
So how do you create a control array? When you name a control with an existing
name (of the same type of control), Visual Basic displays a dialog box asking you if
you want to make a control array. Just click Yes. If you click the No button, VB
renames the control. The dialog box appears below.
If we have a control array, we have controls with the same name. How do we know
then which button has been pressed? All Event Procedures related to a control
array has a special argument value passed to them. This value determines which
control is being worked on. Below is a click event of a CommandButton that is part
of a control array.
How do you modify the properties of control array at runtime? Refer to a specific
member of the control array using an index. For example,
txtGrade(0).Text = “90”
lblResult(4).Caption = “Computer”
94
Lesson in Action
Let’s create an application that asks for a maximum of 10 numbers and displays the
average of these numbers.
txtNum cmdAdd lblOutput lblAverage
cmdClear cmdCompute
95
On your Own
Objectives
To be able to open and close sequential files using Open and Close
To be able to detect end-of-file condition
To be able to write to files using Write
To be able to fetch data from files using Input
Notes
Visual Basic offers file handling capabilities and database handling features. In
database handling controls, the file manipulation is transparent to the programmer
and user. However, in non-database applications the programmer has to handle
virtually all aspects of reading or editing the data contained in a file. This is what
this lesson will cover.
Simple text files (also called sequential files) are often used as the storage method
for information. This is because of their universally standard format. You can simple
create text files using DOS Edit TM program and the newer Windows NotePad TM
applications.
To start manipulating files, you must first open it. You do this through the
following:
96
Open <filename> for <mode> As # <filenumber>
Close #<filenumber>
Open tells Visual Basic to locate a file specified by <filename>, open it for some
purpose, and in some cases, create the file if it does not exist. <filename> can be a
string literal such as “D:\myfiles\names.txt” or a string variable containing the name
of the file to be opened. <mode> tells Visual Basic what to do with the opened file.
It can be any of the following:
Mode Description
Input Opens files for reading. An error occurs if the specified
file does not exist.
Output Opens files for writing. If the specified file does not exist,
VB creates the file for writing. Note: It overwrites the
contents of the file specified.
Append Opens files for appending. It appends new data to the
contents (if there are any) of a file. If the specified file
does not exist, VB creates the file.
Random Opens files for reading or writing.
The pound sign (#) is optional. The <filenumber> value (also called file channel),
which can be between 1 and 255 inclusive, represents the specified file. If you need
to manipulate a file, you refer to the file by the <filenumber> to which it is
associated. The number remains associated to the file until such the time when you
close the file using Close statement. Always remember that a <filenumber> can
only be associated to one file only at one time. If the file is closed, you may use the
<filenumber> again for some other file. If you have lost track of the available
<filenumber>, you may use the FreeFile() function as in the following statement:
FileNum = FreeFile()
The Close statement on the other hand performs the opposite job from Open. It
closes a file and releases the <filenumber> for reuse by the Open statement.
There are 2 ways in which you can use this statement. They are as follows:
Close
The first Close format closes one or more files as specified by the <filenumber>.
The second format close all opened files, thereby releasing all <filenumber>s.
97
The Write command writes data of any data type or format to an opened file. You
need to open a file for Output, Append, or Random before you can use Write.
Below is the syntax of Write:
<filenumber> is the number of the opened file where we will write the data.
<expressionlist> contains the value or values that you will be writing to the file. If
you don’t specify <expressionlist>, then Write writes a carriage return (ASCII 13)
and line feed (ASCII 10) character to the file. If you have multiple values in
<expressionlist>, separate these values by a comma. VB automatically writes a
carriage return (ASCII 13) and line feed (ASCII 10) character after these data.
StudeName(0) = “Antonio”
StudeName(1) = “Heidi”
StudeName(2) = “Joni”
StudeAge(0) = 24
StudeAge(1) = 25
StudeAge(2) = 29
When executed, the above code will produce the following file contents:
“Antonio”, 24
“Heidi”, 25
“Joni”, 29
File handling does not only mean writing to files. What are files for if we do not use
the contents? Retrieving files is easy. You do this using the Input statement
through the following syntax:
The Input statement reads the data stored in the file into a list of variables
enumerated in <expressionlist>. Note that the <expressionlist> should match the
98
type and number of data stored in the file. In our example above, we wrote the
name followed by the age of the student. If we fetch these data, a sample code
might be:
Variable StdName will receive the name while StdAge will receive the age. Thus,
they must be of type String and Integer respectively. More, the order of the
variables in the <expressionlist> should match the order of data in the file. The first
value will be stored in the first variable, the second value on the second variable,
and so on. Errors may occur if read more data than the file holds or when you are
storing a data to a variable of incompatible type (e.g. a Boolean value into an
Integer variable).
We are not done yet. What the code above does is simply to fetch the values on
the first line: store “Antonio” to StdName and 24 to StdAge. From this, we say that
Input just fetches one line only. So do we fetch the remaining data? Answer: We
need to do a loop through the file until we reach the end of it. How do we know
that we have reached the end of the file? Answer: VB provides you with the EOF()
function. It returns True if we have reached the End Of File. Therefore, what we
should do is to keep on executing Input while EOF() returns False. The following
code does all these routines:
99
StdName(0) “Antonio” StdName(1) “Heidi” StdName(2)
“Joni”
StdAge(0) 24 StdAge(1) 25 StdAge(2) 29
Lesson in Action
Let’s create a simple file handling application. The Form below contains a
TextBox, a ListBox and 2 CommandButtons. The “Add Name” button adds the
name entered in the TextBox to the ListBox. “Save to File” button saves the
contents of the ListBox in a text file for future use.
‘This procedure saves the contents of the ListBox to a text file named names.txt
Private Sub cmdSave_Click()
Open App.Path & "\names.txt" For Output As #1
For x = 0 To lstNames.ListCount - 1
Write #1, lstNames.List(x)
Next x
Close #1
End Sub
‘When the form is loaded, this procedure retrieves the names saved in the file (if
any)
Private Sub Form_Load()
Open App.Path & "\names.txt" For Input As #1
100
While Not EOF(1)
Input #1, temp
lstNames.AddItem temp
Wend
Close #1
End Sub
On your Own
Instructions: Modify the sample program to include not just the name but also the
age of the person. The program should also be able to delete a person and edit
a person’s data.
The < and > buttons are for browsing through the student records. When > is
pressed, the program displays the records of the next student (if any). Disable
this button when there are no more succeeding records. When < is pressed, the
program displays the records of the previous student (if any). Disable this
button when there are no more preceding records. The records of the first
student (the one stored at index 0 of the array), if any, should be displayed
during start-up. The TextBoxes containing the student’s name and age should
be locked to avoid being edited. Unlock these TextBoxes only when the user
adds a new student (when the New button is pressed) or when the Edit button is
pressed. Disable Edit and Delete buttons when there are no displayed records.
The Save button should be disabled until the user adds a new student record.
Use two arrays StudeName() and StudeAge() to store the students’ data and
store these in StudeRec.txt.
101