Application Programming
Application Programming
0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Introduction
Events
Data Access
Introduction
[email protected] 1
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Step 1 Launch Visual Basic from the Start menu by choosing Programs;
Microsoft Visual Studio 6.0; Microsoft Visual Basic 6.0
Depending on the environment settings, you may see the New Project dialog box.
[email protected] 2
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 1-1
Step 2 If the New Project box appears, select Standard.EXE, then click Open.
Figure 2-1
[email protected] 3
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 2-2
Each control appears as a button in the tool box. If the control you are
looking for is not in the toolbox, select Components from the Project
menu.
If the tool box is not displayed on your screen, or if at any time during the
exercises you close it, choose Toolbox from the View menu.
Figure 2-3
[email protected] 4
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 2-4
If the form designer window is not displayed on your screen, or if at any time during the
exercises you close it, choose Object from the View menu.
The properties window lists all the properties a control has and their value. The default
value of a property can be changed by setting the property value using the properties
window when you design your application or changed by assigning a new value in code
while your application is running.
If the properties window is not displayed on your screen, or if at any time during the
exercises you close it, choose Properties Window from the View menu.
[email protected] 5
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 2-5
A form file contains both the description of the screen layout for the form and the
program code associated with it. If the project explorer window is not displayed on your
screen, or if at any time during the exercises you close it, choose Project Explorer from
the View menu.
You may wish to close the form layout window to allow more
space for the properties window. To open the window again,
select Form Layout Window from the View menu.
Figure 2-6
In the exercise that follows you will create a single form as shown below.
[email protected] 6
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 3-1
The exercise shows you how to add controls to a form and how to set properties at design
time. This first application will not actually do anything until you add code as shown in
chapter 2.
A command button control enables the user of your application to click on a button when
they require an action to be carried out. You will learn later how to write the code that
will be run when the button is clicked.
Drawing controls
Drawing controls is a two step process. First you need to add the control you want by
double clicking on it in the tool box. Secondly, you need to position and size the control
by clicking and dragging on the form.
Firstly you will create the label which contains the text “Hello”.
Step 3 Move the mouse over the controls in the toolbox until the tool tips indicate
that you have found the label control.
[email protected] 7
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 4-1
Step 4 Double click on the label control button and a label will appear in the
middle of the form.
Figure 4-2
Moving controls
Controls can be moved around a form by dragging them with the mouse.
Step 5 Move the cursor to the label and depress the left mouse button. Keeping
the mouse button depressed, drag the control to its new location, shown in
Figure 4-3.
[email protected] 8
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 4-3
Resizing controls
To achieve the form design shown in figure 3-1, you need to make the label control
larger.
Before a control can be resized it must be selected. When a control is selected it will be
surrounded by black dots or handles.
Clicking and dragging one of these handles will adjust the size of the control.
Figure 4-4
Step 8 Drag the bottom right handle to enlarge the control, then release the
mouse button.
[email protected] 9
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 4-5
Step 9 Position the mouse pointer over the right hand edge of the form.
Step 10 Hold down the left mouse button and drag the edge of the form to the left
to make the form smaller.
Setting properties
Once the control is positioned correctly on the form you then need to customise the
properties of the control to suit your requirements.
This application requires you to change the text that is displayed in the label control from
the default “Label1” to “Hello”. You are also going to change the alignment to Centre
and the font to Arial with font size 16.
To change the properties for a specific control, you must have the control selected.
Step 12 If the properties window is not visible, choose Properties Window from
the View menu or right click on the label control and select Properties.
Check that the Properties window shows the properties for the label
Step 13
control.
[email protected] 10
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 4-6
The Caption property determines what text is displayed in the label control.
Step 14 If the Caption property is not highlighted, click on it to select it. If Caption
is not visible in the list, use the scroll bar on the right to display it.
Select the Alignment property and click on the drop down arrow to reveal
Step 16
the choices for this property.
Select the Font property and click the dialog button (…) to bring up the
Step 18
font window. Set the font values to Arial, Regular, 16.
Figure 4-7
[email protected] 11
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Step 19 Double click on the command button control in the tool box.
Figure 4-8
Step 21 Repeat the last two steps to add a second button under the first.
Your form should appear similar to the one shown in figure 4-9.
Figure 4-9
Step 22 Select the button with the caption Command1. Make sure you can see the
handles that indicate that the button is selected.
Step 23 Using the properties window, change the caption property to On.
Step 24 Use the same process to set the caption for the bottom button to Off.
Step 25 Using the properties window, change the Name property for the form to
Hello.
[email protected] 12
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
When you have written code for the buttons, running the application will allow you to
activate the code. For now your buttons will not do anything.
Figure 5-1
Your form will appear like a window from any other Microsoft application.
Step 28 Click on the Stop button on the tool bar to return to the Visual Basic
design environment.
Figure 6-1
Visual Basic first asks you to save the form and then the project file. Remember that each
represents a separate file.
[email protected] 13
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 6-2
Step 30 Change the directory to the a: drive or to the folder where you want to
save your work.
Specify the filename for the form as hello.frm. The file extension “frm” indicates that the
file is a form file.
Figure 6-3
Step 32 Change the name of the project to hello.vbp and click on Save. The file
extension “vbp” indicates a project file.
Always take care to ensure that you save all the files that make up a project.
7.0 Exercises
Exercise 1
1. Open a new project by choosing New Project from the File menu.
[email protected] 14
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
2. Design the form shown below. Note that you should set the caption property for
the form to Project One.
Exercise 2
[email protected] 15
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Visual Basic applications work by executing code written in the Visual Basic
programming language. Code is associated with events.
When an event is generated Visual Basic will run any code you have entered for that
event.
Step 2 Change to the appropriate drive and folder and open hello.vbp.
[email protected] 16
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 2-1
The project window will display the file “Hello.frm” from your project.
Figure 2-2
Step 3 If the form is not visible, click the View Object button.
Each object has an associated set of events which it can respond to. To enter the code,
you must access the code window.
Step 4 Double click on the ‘On’ button or click the right mouse button and select
View Code from the object menu.
[email protected] 17
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 2-3
Figure 2-4
Click on the Object menu and select Command1 from the list.
1. The object menu allows you to change between controls. For example, you could
use this menu to look at the code for the Off button.
2. The event menu lists all of the available events for the selected control. This list
will change depending on the type of control selected.
3. The code for the event is shown in the main part of the window. Your code will
appear between the Private Sub and End Sub statements.
Step 5 Position the cursor in the blank line between the Private Sub and End Sub
statements.
[email protected] 18
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 2.5
Visual Basic 5.0 uses the programming language Visual Basic for Applications, the same
language found in many Microsoft Office applications including Microsoft Excel,
Microsoft Access and Microsoft Project.
The statement you are going to type assigns a value to the Visible property for the label
on your form. This property is set to the value True by default at design time. Your
Visual Basic statement will change the value of the property when the command button is
clicked.
ObjectName.PropertyName
ObjectName.PropertyName = Value
Step 6 Press the tab key to indent the line of code and type Label1.Visible =
True, and press the Enter key.
Figure 2.6
Notice that the True has turned blue. This indicates that True is a special word or symbol
that Visual Basic understands. Such words are known as reserved words.
You will now follow the same process to enter the code for the Off button to make the
‘Hello’ label invisible when this button is clicked.
[email protected] 19
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Step 8 Double click on the Off button to access the code window.
Step 9 Position the cursor between the Private Sub and End Sub statements.
Step 10 Press Tab and type Label1.Visible = False. Press the Enter key.
Each Visual Basic event has a subprogram associated with it. This is why Visual Basic
automatically includes the Sub and End Sub commands in your code.
The name of the control (in this case Command1) and the event (in this case Click) will
be joined together to form the subprogram name. This name follows the Sub statement.
The line of code that you typed for the On button sets the Visible property of the control
named Label1 to True (to make it visible).
Similarly, the code under the Off button sets the Visible property for the Label1 control
to False (to make it invisible). You can now change the value of the Visible property
while you are running your application.
Step 12 Click on the start button on the tool bar to run your application.
[email protected] 20
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
The “Hello” label will initially be displayed because the visible property in the properties
window was set to true.
When you have finished experimenting click on the end button on the tool
Step 15
bar to return to Visual Basic.
Figure 2-7
[email protected] 21
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 2-8
Having added the button you can now write the code to make it work.
Step 18 Double click on the new button to display the code window.
Enter the following code. Note that the Sub and End Sub lines will already
Step 19
be entered by Visual Basic.
The InputBox function displays a dialog box to the user that allows them to enter in a
value. This value is then returned by the function and assigned to the Caption property
for Label1.
[email protected] 22
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 2-9
Step 24 Click on the end button on the tool bar to return to Visual Basic.
Step 25 Click anywhere in the form itself to select it. Be careful not to click on a
control.
Step 26 In the properties window select the drop down menu for the BackColor
property and select Palette. Remember, if you cannot see the BackColor
property, use the scroll bars to move up or down the list.
Figure 2-10
[email protected] 23
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Step 28 Change the BackColor property for Label1 to a colour of your choice.
Exercises
Exercise 1
1.1 Open a new project by choosing New Project from the File menu.
1.2 Design the form shown below with three labels and one command button.
Figure 2-11
1.3 Write the following code for the click event of the Time button.
When you click on the time button the current time should appear as shown below.
[email protected] 24
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 2-12
1.5 Save your application under the names time.frm and time.vbp.
Exercise 2
2.1 Using the form you created above, add a second button and change the Label3
caption as shown below.
Figure 2-13
2.2 Write the following code for the click event for the Date button.
2.3 Add a line of code to the Command1_Click subprogram so that the caption for Label1
is set back to “The time is:” when the Time button is pressed.
2.6 Save your application files with the names DateTime.frm and DateTime.vbp.
[email protected] 25
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
You use a text box rather than an input dialog box when you want the user to enter data
directly onto the form.
The text box control defines an area on a form where the user can type text. Visual Basic
automatically responds to the delete and backspace keys, and other text editing functions
such as copy and paste, without the need for any programming.
In this chapter you will create the form shown below which will allow the user to enter
some text and format it.
[email protected] 26
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 1-1
Step 1 Choose New Project from the File menu, and select Standard EXE.
Step 2 Double click on the text box control in the tool box window.
Figure 1-2
Step 3 Click and drag in the text box to move it to where you want it and to make
it larger.
[email protected] 27
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 1-3
The default name is determined by the type of control and the number of those controls
on your form.
The name is used to refer to a control when programming. It is good practice to change
the name to something meaningful to your application. A useful convention is to give the
control name a prefix which indicates the type of control.
Step 4 Check that the Text1 control is selected. It will appear on your form
surrounded by black handles.
Step 5 If the properties window is not visible, click the right mouse button and
select Properties from the object menu.
Figure 1-4
[email protected] 28
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
You have used the prefix “txt” to show that this control is a text box.
To set the default text to something else, you would change the Text property for the text
box. In this case, you want it to be blank.
Step 8 Check that the txtInput control on your form is selected and click on the
Text property in the properties window.
Figure 1-5
Step 9 Highlight Text1 and press the delete key on your keyboard to delete the
text.
The text should have now disappeared from the control on your form.
Step 11 Click and drag to create a label in the form, positioned above the text box.
[email protected] 29
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Step 12 Change the Caption property of the label to Enter your text here:.
Step 13 Use the Font property and change the font size to 14.
Figure 2-1
Having added the text box and label to your form you can run it to see what it looks like.
Step 16 Click on the stop button on the tool bar to return to Visual Basic
Check boxes are used to represent on/off values. They can either be checked or
unchecked. When they are checked a tick will appear in the box.
Step 17 Double click on the check box control in the tool box.
[email protected] 30
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 3-1
Step 19 Repeat the last two steps to add a second check box below the first.
Figure 3-2
[email protected] 31
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
You will also need to change the caption of the check box. Remember that this is what
appears on the form.
Step 23 Repeat the steps above to change the name of the second check box to
chkItalic and the caption to Italic.
Figure 3-3
Step 24 Click on the Bold check box on your form to select it.
Step 26 Use the pull down menu to see the possible values for this property.
Figure 3-4
[email protected] 32
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
For now, leave the value property as 0 – Unchecked. You are going to write code so that
if this property has the value one (i.e. the user has checked the box), the font will be bold,
otherwise it will not be bold.
Step 28 Enter the code shown below. Remember that the Private Sub and End Sub
statements are automatically included by Visual Basic
Private Sub chkBold_Click ()
If chkBold.Value = 1 Then
txtInput.FontBold = True
Else
txtInput.FontBold = False
End If
End Sub
Figure 3-5
This is an example of the Visual Basic If statement. The If statement in code allows a
choice of actions. The general structure is:
[email protected] 33
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
If expression Then
statements1
Else
statements2
End If
The first line of the If statement in your example tests the current value of the check box.
If the value of the property Value is equal to 1, then the check box is checked.
If the bold checkbox is checked, set the FontBold property of the txtInput control to True.
Otherwise, if the check box value is not 1 (unchecked or inactive), set the FontBold
property of the txtInput control to False.
Step 33 Click on the stop button on the tool bar to return to Visual Basic.
Step 35 Enter the code shown below. Remember that the Private Sub and End Sub
statements are automatically included by Visual Basic.
Private Sub chkItalic_Click ()
If chkItalic.Value = 1 Then
[email protected] 34
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
txtInput.FontItalic = True
Else
txtInput.FontItalic = False
End If
End Sub
Step 39 Click on the stop button on the tool bar to return to Visual Basic.
When one option button is selected the others in the set are automatically deselected.
You will now use a set of option buttons on your form to represent three font type
choices for the text box.
Step 40 Double click on the option button control in the tool box.
[email protected] 35
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 4-1
Step 42 Repeat the steps above to add two more option buttons to your form.
Figure 4-2
Step 43 Change the Name and Caption properties of the option buttons as given
below.
Name Caption
optMSSansSerif MS Sans Serif
optTimesNewRoman Times New Roman
optArial Arial
You may need to resize the option controls so that the caption fits on one line.
[email protected] 36
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 4-3
To do this you set the Value property. The possible values are True or False. True
indicates that the option button is selected.
Step 44 Click on the MS Sans Serif option button on your form to select it.
Step 46 Use the pull down menu in the editing panel to change the value to True
as shown below.
Figure 4-4
[email protected] 37
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Step 47 Double click on the MS Sans Serif option button in your form.
Step 48 Enter the code shown below. Remember that the Private Sub and End Sub
statements are automatically included by Visual Basic.
Private Sub optMSSansSerif_Click ()
txtInput.FontName = "MS Sans Serif"
End Sub
Step 49 Repeat this process to enter the code shown below for the Times New
Roman button.
Private Sub optTimesNewRoman_Click ()
txtInput.FontName = "Times New Roman"
End Sub
Step 50 Repeat the process again to enter the code shown below for the Arial
button.
Private Sub optArial_Click ()
txtInput.FontName = "Arial"
End Sub
Step 52 Click on the Times New Roman option button to select it.
The text in the text box will be displayed in Times New Roman.
Step 54 Click on the Stop button on the tool bar to return to Visual Basic.
You need to add a line of code, which assigns a value to the BackColor property of the
text box, to the option button code.
[email protected] 38
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Step 55 Double click on the MS Sans Serif option button and insert the line
shown:
Private Sub optMSSansSerif_Click ()
txtInput.FontName = "MS Sans Serif"
txtInput.BackColor = vbGreen
End Sub
Step 56 Add code to the Times New Roman button to change the text box colour
to Red and code to the Arial button to change the text box colour to Blue.
Step 58 Click anywhere on the form to select it. Be careful not to click on a
control.
Step 59 Change the Caption property of the form to read Text Formats.
Figure 5-1
[email protected] 39
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Step 62 Save the project. Remember to save both the project file and the form.
6.1 If statements
Use the If statement when you want to carry out different actions depending on current
values in your application.
The syntax of the If statement can be any of the following:
[email protected] 40
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
7.0 Exercises
Exercise 1
1.1 Your boss has commissioned you to design the interface for a name tag recording
system.
1.2 Open a new project by choosing New Project from the File menu and design the form
shown below.
Figure 7-1
1.4 Write the code to make the bold and italic check boxes work.
Exercise 2
2.1 Change the Caption of the form to Name Tag Designer and the name of the form to
frmTag.
2.2 Add Times New Roman and Arial option buttons to change the font of the text box.
Figure 7-2
Exercise 3
3.1 Add a command button to the form so when it is clicked, the background colour of
the text box changes to green if it was blue or changes to blue otherwise.
[email protected] 41
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 7-3
Exercise 4
4.1 Add a command button to the form so that when it is clicked, an input dialog box asks
the user for a font size for the tag.
Figure 7-4
[email protected] 42
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
4.2 Methods
4.3 Displaying Forms
4.4 Summary
5.0 Exercises
Figure 1-1
Step 4 Add the following code to the Quit button to terminate the application.
Private Sub cmdQuit_Click()
End
End Sub
The next stage will add a second form to the application. At this stage, just an outline
design will be sufficient.
[email protected] 43
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 1-2
Click Form from the display list of available forms and then click Open.
Figure 1-3
The form will be displayed in a separate window. Select the new window so you can see
the form.
Figure 1-4
Step 7 Change the name of the form to frmClientList and the name of the Close
button to cmdClose.
[email protected] 44
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Visual Basic provides the keyword Me as a shortcut to refer to the currently active form.
Step 9 Select View Object for frmWidgets from the Project window.
Figure 1-5
When your user clicks on the Client List button, the second form should become active.
The process of making a form active is a two stage process. It must first be loaded into
memory using the Visual basic subprogram Load. Then it must be made visible using the
method Show.
Step 10 Add the following code for the Client List command button.
Private Sub cmdClientList_Click()
Load frmClientList
frmClientList.Show
End Sub
Step 11 Run your application to check that it works correctly. Use the Quit button
to stop the application running.
Step 12 Save the project. Note that there are now three files to be saved. Use the
Visual Basic default of the form names as the file names for the forms.
Save the project file as Widgets.vbp
The Visual Basic default will mean that the filenames for your form files are
frmClientList.frm and frmWidgets.frm.
[email protected] 45
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 2-1
The add button will add the contents of the text box to the list. The delete button will
remove the item in the list which the user has selected. The clear button will delete all the
items from the list.
Step 13 Select View Form for frmClientList from the Project window.
Step 14 Double click on the list box control in the tool box.
Figure 2-2
[email protected] 46
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 2-3
Step 16 Add a label, text box and three more command buttons to the form, as
shown below.
Figure 2-4
Step 17 Name each of the new controls by selecting the control on your form and
changing the name property in the properties window.
Control Name
Text1 txtInput
List1 lstClientList
Command1 cmdAdd
[email protected] 47
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Command2 cmdDelete
Command3 cmdClear
Control Name
Label1 Enter the name to add:
cmdAdd Add
cmdDelete Delete
cmdClear Clear
Step 20 Click on the play button on the tool bar. Click on the Client List button.
The second form should then appear as shown below.
Figure 2-5
Step 21 Click on the Close and Quit buttons once you have checked your form.
[email protected] 48
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Step 22 Double click on the Add button on your form to display the code window.
Step 23 Enter the code shown below. Remember that the Private Sub and End Sub
statements will have been entered for you by Visual Basic.
Private Sub cmdAdd_Click ()
lstClientList.AddItem txtInput.Text
txtInput.Text = ""
txtInput.SetFocus
End Sub
The first line of the code adds an item to the list box (remember the name of the list box
is lstClientList). The item which is added is the current value of the Text property of the
txtInput control. This will be what the user has entered into the text box.
The next line resets the Text property of the text box to a blank string, ready for the next
entry by the user.
The last line repositions the cursor inside the text box so the user can begin typing the
next entry.
Step 25 Type your name as the first client to add to the list.
Your name should appear in the list box and the text box should appear empty. The
cursor will be positioned in the text box ready for the next entry.
[email protected] 49
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 2-6
Step 27 Use the Close and Quit buttons on your forms to stop the application when
you have finished.
Step 28 Double click on the Delete button on your form to display the code
window.
Step 29 Enter the code shown below. Remember that the Private Sub and End Sub
statements will have been entered for you by Visual Basic.
Private Sub cmdDelete_Click ()
If lstClientList.ListIndex >= 0 Then
lstClientList.RemoveItem lstClientList.ListIndex
Else
Beep
End If
End Sub
The code uses an If statement to test whether the user has selected an item in the list.
The ListIndex property for the lstClientList control holds a number indicating which item
in the list has been selected by the user.
If ListIndex is zero then the first item in the list is selected. If ListIndex is equal to one
then the next item in the list is selected and so on.
[email protected] 50
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
If something is selected the next line of the code will remove it from the list. Visual Basic
will remove the item at list position lstClientList.ListIndex.
You should run the application to test the Delete button code.
Step 30 Click on the play button on the tool bar and click the Client List button.
Firstly, test to see what happens if you click the Delete button when the list is empty.
A beep should sound to indicate that nothing in the list is selected for deletion. The action
should not result in an error message.
Next, test that the Delete button correctly deletes list items.
Step 32 Add several items to the list by entering them in the text box and clicking
on the Add button.
Figure 2-7
[email protected] 51
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Step 36 Stop the application running when you have finished testing.
Step 37 Double click on the Clear button on your form to display the code
window.
Step 38 Enter the code shown below. Remember that the Private Sub and End Sub
statements will have been entered for you by Visual Basic.
Private Sub cmdClear_Click ()
lstClientList.Clear
End Sub
The code uses the Clear method to delete all the items from the list.
Step 39 Click on the play button on the tool bar. Click on Client List.
Step 40 Add several items to the list using the Add button.
The items in this list box example are added at design time.
[email protected] 52
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Step 45 Add a list box to the form. Change its name to lstFruits.
Step 46 Select the List property for the list box and click on the drop down arrow.
Step 48 Type the other fruit names shown pressing Ctrl Enter after each one.
Figure 2-8
Step 49 If you cannot see the full list of fruit in the list box on your form, make the
list box larger.
Step 50 Add a label with the caption shown and a text box to your form as in
figure 2-9.
Figure 2-9
[email protected] 53
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
The List property returns the contents of the list for the specified index.
Step 52 Add the following code to the click event for the list box.
Private Sub lstFruits_Click()
txtSelection.Text = lstFruits.List(lstFruits.ListIndex)
End Sub
Step 53 Run the application and test that clicking on an item in the list box will
cause it to be displayed in the text box.
The contents of the Text property of the combo box is displayed at the top of the combo
box.
[email protected] 54
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 3-1
Step 57 Using the List property, add the items Potatoes, Carrots, Peas and Beans
to the list.
Step 58 Run the application. Click on the drop down arrow for the combo box and
select one of the items.
The Text property of the combo box is set to the selected item and it will be displayed.
Combo boxes also allow your user to type in a value to set the text property while the
program is running. This can be useful if the user needs a value that is not in the list.
4.1 Subprograms
A subprogram is a block of code which is activated by an event or called from another
block of code.
SubprogramName [parameters]
or
Call SubprogramName[(Parameters)]
[email protected] 55
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Examples of subprograms provided by Visual Basic are Load, Unload and End.
4.2 Methods
A method is a subprogram which acts on an object.
object.method [parameters]
The main form of a project is automatically loaded into memory and made visible when
the project starts running.
For other forms, statements to Load them and Show them must be executed. For
example:
Load Form2
Form2.Show
If you have forms which you want to open and close frequently, you can avoid the
overhead of loading them into memory each time by loading them once then using the
Show and Hide methods to make them available when required.
Each form has a load event and you can put code here to initialise values. The load event
for the main form is a good place to load other forms.
[email protected] 56
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Form2.Show
Form2.Hide
4.4 Summary
Load is a Sub (subprogram) which loads the specified form into memory. Note that it
doesn’t necessarily make the form visible. (Load is also an event for a Form).
Show is a method which loads the specified form into memory if it isn’t already loaded
and makes it visible.
Hide is a method which makes a form invisible but doesn’t unload it from memory.
End is a subprogram which terminates the currently running project and unloads all its
forms.
5.0 Exercises
Exercise 1
1.1 Open a new project by choosing New Project from the File menu.
1.2 Design the form shown below. Change the Name property to frmDemo. Add code to
the QUIT button to stop the application running.
Figure 5-1
[email protected] 57
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
1.3 Click on the Add Form button and then on the existing tab to add the form
frmClientList, which you saved earlier in the chapter, to this project.
1.4 Add code to frmDemo to access frmClientList when the List Box button is clicked.
Exercise 2
2.1 Choose Add Form from the Project menu or click the Add Form button on the toolbar
to add a new form to your project. Change the name property to frmComboDemo.
2.2 Design the form to look like the following. Set the Style property differently for each
combo box.
2.3 Add the items: eggs, butter and ham to the lists for each combo box.
Figure 5-2
2.4 Add code to the Combo Box button in frmDemo to activate frmComboDemo.
[email protected] 58
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
You can use the line and shape controls to add graphics to your forms or methods such as
circle and pset to draw shapes while your application is running.
The simplest way to add graphics to a form is to use the image or picture box controls to
display a picture or icon.
In this chapter you will use image controls to display pictures and create simple
animation by changing the pictures displayed in the control and by moving the control
across the screen.
Figure 1-1
The Change button will change the colour of the traffic light. When the traffic light
appears green the car will move across the screen.
[email protected] 59
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Change the button Caption to Change and the Name to cmdChange using
Step 4
the properties window.
Figure 1-2
The default unit of measurement is the twip (one twentieth of a printer’s point). You will
probably find it easier to work in units that you are more familiar with.
[email protected] 60
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 2-1
Figure 2-2
This will be the image control in which the traffic light is displayed.
Step 8 Change the Height and Width properties for the image control to 2.
[email protected] 61
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
First, you will add another three image controls to your form. One to hold the traffic light
picture for each possible light colour. The Visible property for these will be set to false so
that they cannot be seen when the application is running.
Second, you will program the Change button to change the picture displayed in the
imgLight image control to the next appropriate picture by setting the Picture property of
the imgLight control equal to the Picture property of the correct traffic light image
control.
Figure 2-3
These controls must be the exactly the same size as imgLight for the animation to look
convincing.
Make sure that the pointer button on the toolbar is depressed and using the
Step 12
mouse, drag a rectangle around the three new image controls.
The three controls are now selected and the properties window can be used to set
properties for all three at the same time.
Step 13 Set the Stretch property to True and the Height and Width properties to 2.
[email protected] 62
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Step 15 Click on the form away from the selected controls to deselect the group.
Change the Name property for the new image controls to imgGreen,
Step 16
imgYellow, and imgRed.
The next step is to set each of the image controls to display the appropriate traffic light
picture.
Step 17 Check that the image control, imgGreen, is selected on your form.
The standard Windows file dialog window will open. The window is used to select the
picture file.
Figure 2-4
Step 21 Click on trffc10a.ico in the file list to select it, and click on Open.
The image control will now display a picture of a traffic light set to green.
[email protected] 63
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Change the Picture property of the other image controls as shown below.
Step 22
The picture files are located in your class folder.
Figure 2-5
Run the form to see the result. At this point, you should only see the
Step 23
change button on screen.
The Load event for your form would be a suitable place to carry out this action.
Step 25 Double click on the form and add the following code to the Load event.
Private Sub Form_Load()
imgLight.Picture = imgYellow.Picture
End Sub
The next step is to write the code which will change the picture displayed in imgLight
when the Change button is clicked.
[email protected] 64
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Double click on the Change button on your form to display the code
Step 26
window.
The code uses a case statement which allows you to enter a number of possible options.
The case statement compares the Picture property of the imgLight control to the Picture
property for each of the other picture box controls.
When it finds one that matches, the code sets the Picture property of the imgLight
control to the next appropriate picture.
Step 31 Click on the stop button on the tool bar to return to Visual Basic.
You want the car to appear initially at the right of the form and move across until it is out
of sight at the left of the form.
[email protected] 65
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Drag the right edge of the form out to increase the size of the form as
Step 32
much as you can.
Add another image control to your form at the right hand edge as shown
Step 33
below.
Change the Name property to imgCar and set the Stretch property to
Step 34
True.
Step 36 Size the image control until you have the car shape of your choice.
Your form should appear similar to that shown in the figure below.
Figure 2-6
Step 37 Drag the right hand border of the form back so that the car is hidden.
There are many programming constructs for loops in Visual Basic. This example uses a
While loop which terminates when the car reaches the left hand side of the form.
[email protected] 66
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Do While condition
statements
Loop
The code to move the car should be executed as soon as the traffic light picture changes
to green.
Double click on the Change button and modify the code as shown. The
Step 38
new code is shown in bold.
Private Sub cmdChange_Click()
Select Case imgLight.Picture
Case imgGreen.Picture
imgLight.Picture = imgYellow.Picture
Case imgYellow.Picture
imgLight.Picture = imgRed.Picture
Case imgRed.Picture
imgLight.Picture = imgGreen.Picture
Do While imgCar.Left > 0
imgCar.Left = imgCar.Left - 0.01
Loop
End Select
End Sub
The statement in the while loop moves the image control to the left 0.01 cm.
You will note that once the car has reached the left hand side of the form, changing the
traffic lights has no further effect. For the car to move again, it should be repositioned at
the right hand side of the form. In order to do this, you need to restore the original value
of the Left property for imgCar.
The following steps show how to store the original value in a variable and use it to
restore the car to its original position.
Step 41 Double click the Change button and modify the code as shown.
Private Sub cmdChange_Click()
Dim Original As Single
Select Case imgLight.Picture
Case imgGreen.Picture
imgLight.Picture = imgYellow.Picture
Case imgYellow.Picture
imgLight.Picture = imgRed.Picture
Case imgRed.Picture
imgLight.Picture = imgGreen.Picture
Original = imgCar.Left
[email protected] 67
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Do While imgCar.Left > 0
imgCar.Left = imgCar.Left - 0.01
Loop
imgCar.Left = Original
End Select
End Sub
The first line of the code dimensions (or declares) a variable. Variables are used to store
information while your program is running.
The Dim statement gives the variable a name and states the type of information which
will be stored in it. For this example, the variable will be used to store the value of the
original imgCar Left property. This is measured in centimetres and will probably not be
a whole number so the data type Single is used.
The second new line of code assigns the left hand position of the image control to the
variable Original. This is so that you can reset the image control to its original position
once it has moved across the screen.
Last, the car image control is repositioned back to its original location using the Original
variable that was set before the loop.
Step 42 Click on the play button on the tool bar to run your code.
Step 43 Click on the Change button on the form until the light appears green.
Click on the Change button on the form until the light appears green
Step 44
again.
Step 45 Click on the stop button on the tool bar to return to Visual Basic.
Keep your saved project in a safe place. You will need it for the following exercises.
[email protected] 68
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Storage
Data Type Range Suffix
Size
Integer 2 bytes -32,768 to 32,767 %
Long (long integer) 4 bytes -2,147,483,648 to 2,147,483,647 &
Single(single- -3.402823E38 to -1.401298E-45 for negative
precision floating- 4 bytes values; 1.401298E-45 to 3.402823E38 for !
point) positive values.
1.79769313486232E308 to 4.94065645841247E-
Double(double-
324 for negative values; 4.94065645841247E-
precision floating- 8 bytes #
324 to 1.79769313486232E308 for positive
point)
values.
-922,337,203,685,477.5808 to
Currency 8 bytes &
922,337,203,685,477.5807.
1 byte per
String 0 to approximately 65,500 bytes $
character
Any numeric value up to the range of a Double or
Variant
any character text
Variable names:
[email protected] 69
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Note that for compatibility with earlier Basics, Visual Basic allows you to use variables
without declaring them first. As you know from other programming courses, this is a
dangerous practice. Most Visual Basic projects use the statement Option Explicit in a
code module to force the use of declarations. Alternatively, set the appropriate option in
the Project Environment from the Options menu.
There are several different ways to declare variables in Visual Basic, many are provided
for compatibility with other Basics e.g. DefInt or the use of the suffixes shown in the
table above to force a type on a name.
The location of the declaration determines its scope. A declaration in an event Sub or
Function means that the variable is local to that Sub or Function. The value of the
variable is not retained between function calls.
If you want the variable to retain the value which it last had, use the STATIC keyword
for the declaration e.g.
A declaration made in the declarations section of a Form makes the variable available to
all the code associated with that form.
A variable which you want to make available to the entire project must be declared in a
Code Module using the format:
[email protected] 70
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
statements
CASE value2
statements
CASE valuen
statements
END SELECT
c) the DO loop
DO WHILE condition
statements
LOOP
DO UNTIL condition
statements
LOOP
DO
statements
LOOPWHILE condition
DO
statements
LOOP UNTIL condition
[email protected] 71
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
EXIT FOR
EXIT WHILE
EXIT DO
EXIT FUNCTION
4.0 Exercises
Exercise 1
1.1 Open the Car project and add another image control to the form. Change the Name
property to imgCarStop. Set the Stretch property to True, the Visible property to False
and the Picture property for the new control to Car2.bmp.
1.2 Size the new control so that it is roughly the same size as the imgCar control.
1.3 Select ‘Save As File’ from the File menu. Save the form as CarStop.frm. Select
‘Save As Project’ and save the project as CarStop.vbp.
1.4 Modify the code for the Change button so that instead of returning the car to the
original position after the while loop, the imgCarStop picture is copied into the imgCar
Picture property.
Your application should look like the following when the car stops moving.
Figure 4-1
Exercise 2
In this exercise you will modify the existing Change button code so that the car appears
to skid to a halt.
1.1 Using the form you created above, modify the condition in the while loop so that the
loop terminates when the car is less than 3 cm from the left hand side of the form.
[email protected] 72
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 4-2
1.3 Copy the while loop and paste it after the imgCar.Picture = imgCarStop.Picture
statement.
1.4 Change the condition so that this loop terminates when the car reaches the left hand
side of the form.
The image control will move more slowly if the distance it is moved is smaller.
1.6 Change the distance moved in the second loop so that the skidding sequence appears
slower.
[email protected] 73
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
4.1 Layering
5.0 Message Boxes
5.1 Return Values
6.0 Exercises
Figure 1-1
The timer can be stopped while the application is running by setting the Enabled
property to FALSE or setting the Interval property to 0.
Step 1 Start a new project and add two labels with Name property set to lblTime
and lblDate respectively. Change the FontName for the labels to Courier
New (a non-proportional font) and choose a suitable FontSize for each
label. Change the caption of the form to Clock.
Step 2 Add a Timer Control to the form. It doesn’t matter where you put this
control because it is invisible when the project is running.
[email protected] 74
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 1-2
Step 3 Select the Properties window for the Timer Control and set Enabled to
True and the Interval property to 1000.
The units for the interval are milliseconds. With these settings, the code in the event
Timer1_Timer will be executed approximately every second.
Step 4 Add the following event procedure code and try out your application.
Private Sub Form_Load()
lblDate.Caption = Date
End Sub
[email protected] 75
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Step 6 Select Add Form from the Project menu, or click on the icon, and add the
file Car.frm which you saved earlier.
You are going to change this form so it would be appropriate to save the form with a
different file name.
Step 7 Make sure that Car.frm is highlighted in the Project window and select
Save As from the File menu.
You now need to make this form the start up form and get rid of the form Form1 which
you do not need.
Step 9 Select Project Properties from the Project menu and click the General tab.
Figure 2-1
Step 11 Highlight Form1 in the Project window and select Remove Form1 from
the Project menu.
[email protected] 76
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Step 12 Add a Timer Control to the form. Name the timer tmrLights.
Step 13 Cut the code from the cmdChange_Click event and paste it into the
tmrLights_Timer event.
Step 15 Change the Name property for cmdChange to cmdStartLights and the
Caption property to Start Lights.
Step 16 Add another command button to the form to be used for stopping
tmrLights. Set appropriate values for the Name and Caption properties
Figure 2-2
Step 17 Set the Interval property of the Timer to 1000 and the Enabled property to
FALSE.
Step 18 Add code to the Click events for the Command Buttons as follows
Private Sub cmdStartLights_Click()
tmrLights.Enabled = TRUE
End Sub
[email protected] 77
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
When you click the Start Lights button, the traffic lights should start to cycle through
their colour changing sequence at approximately 1 second intervals.
A better method is to use a Timer Control and to move the car in the timer event. You can
then stop the car when you need to by disabling the timer. The following example shows
how to use a second timer so that the car starts when the lights go green and stops when
the lights go red.
The speed at which the car moves depends on the timer interval and the distance the
image control is moved. You will need to experiment with these values to get the best
effect.
2.4 Constants
Values that you think might need to be changed in the future should be declared as
constants so that you only need to change the value once, no matter how often you use it
in the project. The syntax for a constant is:
Step 20 Open the code window and select Declarations for the General object.
Figure 2-3
[email protected] 78
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Constants declared in the Declarations section of a form are only available to that form.
Option Explicit
Const LightsInterval = 1000
Const CarInterval = 100
Const Distance = 0.1
Step 21 Add a second timer to your form. Name it tmrCar. Set the Enabled
property to FALSE. Amend the Form_Load, tmrLights_Timer and
cmdStopLIghts event procedures as shown:
Private Sub Form_Load()
imgLight.Picture = imgYellow.Picture
tmrCar.Interval = CarInterval
tmrLights.Interval = LightsInterval
End Sub
[email protected] 79
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
The Scroll Bar control will provide you with a convenient way to change these values so
that you can experiment with the animation while the application is running.
Figure 3-1
Step 24 Add two horizontal scroll bar controls to your form with appropriate
labels as shown.
Figure 3-2
[email protected] 80
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Note that the property values for changing scroll bars must be integer so the actual
distance value must be calculated in the code.
The distance and interval are going to be changed while the application is running. The
change in interval can be stored directly in the tmrCar.Interval property. You will need
to declare a variable in which to store the distance.
Step 28 Add code to the change events for the scroll bars to change the appropriate
values when the scroll bar changes.
Private Sub hsbDistance_Change()
Distance = hsbDistance.Value / 100
End Sub
[email protected] 81
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
It would be useful to see the value that the scroll bar is currently set to.
Step 30 Add a small label at the end of each scroll bar and name them lblDistance
and lblInterval.
Step 31 Add the following code to the scroll bar change events.
Private Sub hsbDistance_Change()
Distance = hsbDistance.Value / 100
lblDistance.Caption = Distance
End Sub
Figure 3-3
[email protected] 82
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
The main difference between the image controls and picture boxes is that, like forms,
picture boxes can be used as containers for graphics.
Step 34 Open a new project. Name the form frmFlying. Save the form as
frmFlying.frm and the project as Flying.vbp
Step 35 Set the Picture property of the form to the picture clouds.bmp which you
will find in the pcskills folder.
Step 36 Add a picture box to the form. Name it picFlying and set its Picture
property to Clouds.bmp also
Figure 4-1
[email protected] 83
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Step 37 Click the image control button on the toolbox. Click and hold the left
mouse button inside the picture box and drag to create a small image
control.
Figure 4-2
Step 38 Name the image control imgPlane and set the picture property to the icon
plane.ico which you will find in the Icons folder under Industry.
Step 39 Add two command buttons to the picture box with names cmdFly and
cmdGoBack. Give them the captions shown (Fly and GoBack
respectively).
Figure 4-3
[email protected] 84
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
imgPlane.Left = imgPlane.Left - 3
imgPlane.Top = imgPlane.Top - 1
Loop
End Sub
The units of measurement are the default, twips, and the coordinates are now relative to
the picture box rather than the form.
4.1 Layering
The form you have just created uses layering.
There are three graphical layers associated with forms and picture boxes.
The back layer is the drawing space, where the results of code drawn graphics methods
appear.
Next is the middle layer where graphical controls and labels appear.
The front layer is where all non-graphical controls like command buttons, check boxes,
and file controls appear. Anything in one layer covers anything in the layer behind. You
can create interesting forms by layering controls, image or picture boxes.
The subprogram MsgBox can be used either as a sub program or as a function which
returns a value which tells you which button your user has clicked.
[email protected] 85
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Step 43 Save the form as frmFlying1.frm and then save the project as
Flying1.vbp. Put an image control, named imgMe and with Picture
property set to face03.ico from the Misc folder in the Visual Basic icons.
Add a label with caption Click Me! as shown.
Figure 5-1
The constant vbInformation is provided by Visual Basic and determines the type of icon
displayed in the message box.
The full list of constants is given below at the end of this section.
Step 45 Add a quit button (named cmdQuit) with the code shown to your
application.
Note how the constants for the message box are specified.
[email protected] 86
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 5-2
[email protected] 87
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Return Values
Constant Value Button chosen
vbOK 1 OK
vbCancel 2 Cancel
vbAbort 3 Abort
vbRetry 4 Retry
vbIgnore 5 Ignore
vbYes 6 Yes
vbNo 7 No
6.0 Exercises
Exercise 1
1.1 Add code to your CarTimer project so that if the car goes off the left of the form, it is
restored to its original position.
Exercise 2
2.1 Add code to your Flying application so that if the plane is at the top left hand corner,
the Go Back button is not visible.
2.2 Add code to the Flying application so that if the plane has flown out of the picture
box, the Go Back button is visible and the Fly button is not visible.
[email protected] 88
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
The following example shows how to use these controls in order to choose and load a file
in graphics format (*.bmp, *.ico or *.wmf ) into an Image control on your form.
Step 1 Start a new project and place the three file system controls plus a Label
with name lblFullPath and an Image control with name imgDisplay (and
with Stretch property set to True) onto your form.
Figure 1-1
Step 2 Set the Pattern property of the File ListBox control to *.bmp;*.wmf;*.ico
The Drive and Dir Change events set up the File1.Path property so that files from the
appropriate directory are listed in the File ListBox.
[email protected] 89
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Sub Dir1_Change ()
File1.Path = Dir1.Path
End Sub
The path to the file you want to display is held in File1.Path. The final step is to add the
selected filename to this path.
If the file you want to display is in a root directory, e.g. A:\, the filename is added to the
end of the string. If the file is not in a root directory, you need to put a ‘\’ between the
path and the filename.
Figure 1-2
[email protected] 90
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
The following application which builds a simple editor program for rich text format or
ASCII text files, provides an opportunity to use the Menu Designer.
Step 6 To see what you will be able to achieve by the end of this chapter, run the
application Viewer.EXE stored in Files folder.
Step 7 Start a new project. Name the form as frmFileViewer and set the caption
of the form to File Viewer. Save the form as frmFileViewer.frm and the
project as FileViewer.vbp. Add a large Rich TextBox control to the form.
(If this control is not in your toolbox, select Components from the Project
menu, and check Microsoft Rich TextBox Control 5.0). Set the Name
property for the Rich TextBox to rtbDisplay, and the Scrollbars property
to 3-rtfBOTH.
Figure 2-1
In the next steps you will create a menu system of options that will appear at the top of
the window. This menu system is designed using the menu editor.
Step 8 Click on the frame to select it. Select Menu Editor from the Tools menu.
[email protected] 91
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 2-2
Step 9 Type &File in the caption cell and mnuFile in the Name cell.
Step 11 Click the right facing arrow to create a submenu item. Type &New in the
Caption cell and mnuNew in the Name cell.
Separators in menus are created by typing the - character as the caption. Separators must
also be given names.
Step 12 Click Next. Type - in the Caption cell and mnuSep1 in the Name cell to
insert a separator in the menu. Click Next.
Step 13 Add further menu items with Captions and Names as shown below, using
the arrow keys to set up the hierarchy of main menu and sub-menus.
[email protected] 92
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 2-3
Step 14 Click OK to close the Menu Editor window and run your application to
check that your menu structure is correct.
Currently, the menu options do not do anything when you select them. In the next step
you will create code that is associated with the menu options.
Step 15 Go to Code View for your form and implement New, Exit and About:
Private Sub mnuNew_Click()
rtbDisplay.Text = ""
End Sub
So far, you have created a menu and added the code for some of the options. In the next
sequence, you will add more functionality to this application by using dialog boxes.
[email protected] 93
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Finally, you will have an application that will allow you to select a file (based on the
previous Icon viewer program) and view the contents.
Method Dialogue
ShowOpen Open File
ShowSave Save File
ShowColor Color Palette
ShowFont Change Font
ShowPrinter Print
ShowHelp Help
Step 17 Add a Common Dialog control to your File Viewer form. If the control is
not in your toolbox, select Components from the Project menu, and check
Microsoft Common Dialog 6.0). When the application is run, the common
dialog box is not visible, so do not worry where it is placed on the form.
Change the Name property to cdlViewer.
[email protected] 94
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 3-1
Step 18 Access the code view and add the following code for
menuOpenFile_Click().
Private Sub mnuOpenFile_Click()
Dim strFileName As String
cdlViewer.Filter = "RTF|*.rtf|Text|*.txt|All|*.*"
cdlViewer.ShowOpen
strFileName = cdlViewer.filename
rtbDisplay.LoadFile strFileName
End Sub
Step 19 Save your files. Run the application and select a file to check that the text
appears in the Rich TextBox.
Your File Viewer application should be displaying the selected file in the window.
However, there are still improvements to be made to the application, and there are still
some menu options that are not working yet. Good applications know how to handle the
unexpected, so in the next step you will add some error handling functionality to the
application.
[email protected] 95
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
The On Error statement is a quick and simple way of trapping errors while a program is
running. It should be used wherever necessary to avoid the inelegance of a program
crash.
You have now created a much more robust procedure. If the file cannot be opened, a
message box will appear and display an error message. Now you will do something
similar when a file is saved, by adding the code and error handling statements to the
mnuSave_Click() function.
Your application is now just about complete. But what about those missing menu options
for changing the fonts and colors? In the next step you will add the necessary code to do
these tasks.
[email protected] 96
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Step 22 Add the following code to the Back Colour option on your menu
Private Sub mnuBackColour_Click()
cdlViewer.Flags = cdlCCRGBInit
cdlViewer.ShowColor
rtbDisplay.BackColor = cdlViewer.Color
End Sub
The constant cdlCCRGBInit sets a default value for the colour palette.
Step 23 Write code for the Change Font option on your menu
Private Sub mnuChangeFont_Click()
cdlViewer.Flags = cdlCFBoth Or cdlCFEffects
cdlViewer.ShowFont
rtbDisplay.SelFontName = cdlViewer.FontName
rtbDisplay.SelFontSize = cdlViewer.FontSize
rtbDisplay.SelBold = cdlViewer.FontBold
rtbDisplay.SelItalic = cdlViewer.FontItalic
rtbDisplay.SelUnderline = cdlViewer.FontUnderline
rtbDisplay.SelColor = cdlViewer.Color
End Sub
The constants used to assign a value to the Flags property specify that the fonts listed will
be both screen and printer fonts and that the effects will include underline, strikeout and
colour effects.
Step 24 Save your application. Run the application and try out this code to see the
font dialog box.
The application is just about complete. However, there is no help! In the next steps, you
will add some help functionality to your application by adding a message to the help
option.
[email protected] 97
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
3.6 Help
Step 25 Add a message box to the How To Help menu option to say that help will
be available soon. If you cannot remember how to do this, look at
mnuAbout.
Private Sub mnuHelpRichTextBox_Click()
cdlViewer.HelpFile = "VB5.HLP"
cdlViewer.HelpCommand = cdlHelpKey
cdlViewer.HelpKey = "RichTextbox Control"
cdlViewer.ShowHelp
End Sub
Step 26 Test your completed application. Save your application.
4.0 Exercises
1.1 Demonstrate your File Viewer application and be prepared to explain any code it
contains.
1.2 Add an Edit menu to your application with a Select All option. Give the option the
shortcut Ctrl A. (Use Shortcut in the Menu Editor). Write code for this option. (Hint set
the SelStart property to 0 and the SelLength property to Len(rtbDisplay.text)).
Modules, the Rnd function, Frames, Control Arrays, Drag & Drop
1.0 Modules
1.1 Event procedures
1.2 General procedures
1.3 Scope of procedures
1.4 The Screen object
1.5 Calling a sub procedure
1.6 The Rnd function
1.7 The RGB function
2.0 The Frame control
2.1 Frames and Option (Radio) buttons
3.0 Control Arrays
3.1 Using control arrays in animation
[email protected] 98
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Modules, the Rnd function, Frames, Control Arrays, Drag & Drop/1
1.0 Modules
Code which you want to access from more than one form is usually stored in a module.
You can use modules like code libraries and attach them to different projects.
The keyword ByVal signifies that the parameter is being passed by value. If ByVal is
omitted, the parameter is passed by reference (address). Passing by value ensures that the
parameter cannot accidentally be changed.
[email protected] 99
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
The keyword PUBLIC indicates that the procedure can be called from other forms or
modules. Event procedures are PRIVATE by default. General procedures are PUBLIC by
default.
The following example shows you how to develop a library of procedures which can be
used to manipulate any form.
The purpose of the first sub procedure is to centre a specified form in the middle of the
screen.
Step 1 Start a new project and add a command button to the form. Set the
properties as follows
Form CommandButton
Name=frmMAIN Name=cmdNextForm
Caption=Module Demo Caption=Next Form
Step 2 Select Add Module from the Project menu, then click on Open, making
sure that the ‘New’ tab and module are selected as shown below. Click
Open.
Figure 1-1
[email protected] 100
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 1-2
Step 4 Type CentreForm for the name of the new procedure and click on OK.
Visual Basic provides the outline template for your procedure. To make the procedure
more generally useful, the name of the form to be centred is passed as a parameter.
Save the project as form as frmMain.frm and the project as Main.vbp. Save the module
as Main.bas.
Call SubName(Parameters)
or
SubName Parameters
[email protected] 101
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Step 6 Put the following statement into the Form_Load event and run your
application to check that your centering works.
CentreForm frmMain
CentreForm Me
Step 7 Right-click on the Main.bas module in the project window and select code
view. Add the following new procedure to your code module.
Public Sub ShrinkForm(theForm As Form)
theForm.ScaleMode = vbTwips ' the mode may have been
changed
Do While theForm.Height > 500 And theForm.Width > 500
CentreForm theForm
theForm.Height = theForm.Height - 50
theForm.Width = theForm.Width - 50
Loop
theForm.Hide
frmMain.Show
End Sub
Step 8 Save the project.
Step 9 Add a second form to your project. Give it the name frmSecond and size
the form so that it is square. Set the caption to Seconf Form and save the
form as frmSecond.frm.
Step 10 Add the following code to the Click event for the second form.
Private Sub Form_Click()
ShrinkForm Me
End Sub
Step 11 Add the following code to the command button on the main form so that it
loads and shows the second form.
Private Sub cmdNextForm_Click()
Load frmSecond
frmSecond.Show
Me.Hide
End Sub
Step 12 Save the project. Run the application and click on the command button.
The second form should appear. Click on the second form and it should
shrink.
[email protected] 102
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
theForm.BackColor=RGB(Int(256*Rnd),Int(256*Rnd),Int(256*Rnd)
)
End Sub
When you use the Rnd function, the statement Randomize should be added to the Load
event for the main form to get a different sequence of random numbers each time the
application is run.
Step 14 Add the line shown in bold to the ShrinkForm procedure in the Main.bas
module.
Public Sub ShrinkForm(theForm As Form)
theForm.ScaleMode = vbTwips ' the mode may have been
changed
Do While theForm.Height > 500 And theForm.Width > 500
CentreForm theForm
theForm.Height = theForm.Height - 10
theForm.Width = theForm.Width - 10
RandomlyColour theForm
Loop
theForm.Hide
frmMain.Show
End Sub
Step 15 Save your files. Try out your application.
[email protected] 103
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Modules, the Rnd function, Frames, Control Arrays, Drag & Drop/2
A frame has a Caption property and an Enabled property. Setting the enabled property to
false disables all the controls that the frame contains.
Figure 2-1
This allows you to refer to an individual control by its index value rather than having to
refer to an individual name.
The following example demonstrates how to manipulate the option buttons as control
arrays.
Step 16 Start a new project and put a frame control on the form, so that the frame
control takes up about half the left side of the form. Name the form as
frmOption and set the caption to Groups of Option Buttons. Save the
form as frmOption.frm and the project as Option.vbp. Change the
caption of the frame control to Foreground Colour.
[email protected] 104
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 3.0-1
Step 17 Click once on the option button control in the toolbox and use the mouse
to position a new option button inside the frame. Change the name of the
option button to optForeground.
Step 18 Click on the option button on the frame to select it. Choose Copy from the
Edit menu.
Step 19 Make sure that the frame is selected and select Paste from the edit menu.
Figure 3-2
The option buttons in the frame will now have the names optForeground(0) and
optForeground(1) as shown in the figure below.
[email protected] 105
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 3-3
Step 21 Select the frame again and Paste a third option button into the frame.
Change the captions as shown
Figure 3-4
Step 22 Add a label to the form with caption Hello! and name lblHello. Set the
forecolor property to red and backcolor to black.
Figure 3-5
Step 23 Add another frame with caption Background Colour containing three
[email protected] 106
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 3-5
You now need to add code that will change the foreground and background colours for
lblHello.
There is one Click event for each set of option buttons. The select case statement selects
the action depending on the value of the parameter, Index.
Step 26 Start a new project and add a Timer control named tmrCyclist, and an
[email protected] 107
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Image control named imgMovingCyclist to the left hand side of the form.
Name the form as frmCyclist. Set the caption on the form to Cyclist
Demo. Save the form as frmCyclist.frm and the project as Cyclist.vbp
Figure 3-7
Step 27 Set the Stretch property of the image control to True.
The animation sequence for this exercise requires seven different pictures. You will need
to set up seven image controls across the bottom of the form, as shown below.
Step 28 Add a new image control named imgCyclist to the form in the bottom left
corner. Set the stretch property to True.
Step 29 Copy and paste this image control until you have a control array of seven
image controls along the bottom of the form.
Figure 3-8
[email protected] 108
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
imgCyclist(1) etc.
Figure 3-9
Step 33 Set the Interval property for the Timer to 100 and add the following code
to the Timer event.
Private Sub tmrCyclist_Timer()
Static Index As Integer
imgMovingCyclist.Picture = imgCyclist(Index).Picture
imgMovingCyclist.Left = imgMovingCyclist.Left + 150
Index = (Index + 1) Mod 7
End Sub
Step 34 Drag the bottom of the form over the control array sequence of pictures so
that the control array is no longer visible on the form. Save the files. Run
the application.
You can see that this kind of animation has its limitations. There are better methods to
use for more experienced users of Visual Basic.
Modules, the Rnd function, Frames, Control Arrays, Drag & Drop/3
[email protected] 109
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 4-1
Step 35 Start a new project. Name the form frmDragDrop and set the caption to
Drag and Drop Example. Save the form as frmDragDrop.frm and the
project as DragDrop.vbp. Add a label to the form. Set the Name property
to lblLetter. Set the Caption property to A. Set the Font property to about
size 18. Set the DragMode property to 1. You can optionally also set the
DragIcon property.
Step 36 Copy the label and Paste to create a control array. Repeat for as many
letters as you require. Change the captions appropriately.
Step 37 Add a new label to the form. Set the Name property to lblWord. Set the
Caption property to _. Set the Font property to size 18 to display the
underscore character as shown in the form below. Copy and Paste to make
a control array with 5 members.
Figure 4-2
Step 38 Write code for the DragDrop event for the lblWord control array.
[email protected] 110
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Private Sub lblWord_DragDrop(Index As Integer, Source As
Control, X As Single, Y As Single)
' Index identifies which element of lblWord the letter was
dropped on.
' Source is the control which was dropped.
' X and Y give the current mouse coordinates in the
target.
lblWord(Index).Caption = Source.Caption
Source.Visible = False ‘ if this is what you want to
happen
End Sub
Step 39 Save the project files. Run the application and drag the letters from the top
to the bottom to create a word.
5.0 Exercises
Exercise 1
1.1 Demonstrate the cyclist application.
Exercise 2
Write an application that generates and displays a column of 6 lotto numbers in a
ListBox. (i.e. 6 random numbers in the range 1 to 40).
You may find it helpful to write and save the following procedure function in a module.
This will save you having to remember how to use Rnd when you need a random
number.
[email protected] 111
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
where
integervariable is required to store the return value of the function. If the Shell
function successfully executes the named program it returns the instance handle
(task identifier) of the started program.
commandstring is the name of the .COM, .EXE, .BAT, or .PIF file to execute,
plus arguments or command line switches.
windowstyle is a number corresponding to the style of the window in which the
program is to be executed. The following table identifies the constants you can
use for windowstyle and the resulting style of window:
[email protected] 112
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Constant Description
vbHide Window is hidden and focus is passed to the hidden window.
vbNormalFocus Window has focus and is restored to its original size and position.
vbMinimizedFocus Window is displayed as an icon with focus.
vbMaximizedFocus Window is maximized with focus.
Window is restored to its most recent size and position. The
vbNormalNoFocus
currently active window remains active.
Window is displayed as an icon. The currently active window
vbMinimizedNoFocus
remains active.
Note The Shell function runs other programs asynchronously. That means that you
cannot depend on a program started with Shell to be finished before the next Visual Basic
statement is executed.
Step 1 Start a new project and add two command buttons and a common dialog
control to the form. Name the form as frmAppManager and set the
caption of the form to Application Manager. Save the form as
frmAppManager.frm and the project as FormManager.vbp
Figure 1-1
Step 2 Name the command buttons cmdCalculator and cmdOtherEXE and set
their captions appropriately.
[email protected] 113
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
cdlGetFile.ShowOpen
TaskID = Shell(cdlGetFile.filename, vbNormalFocus)
End Sub
Step 5 Save the files. Run the application and test the buttons. Select an EXE file
such as Notepad.exe to test the RunAnyEXE button.
The following example shows you how to make an.exe file for a simple application. For
complex applications, you should use the Setup Wizard to ensure that all necessary files
are distributed to your user and installed correctly.
Step 6 Use the same project you currently have open (the Application Manager).
Click on the form. In the properties window, set the Icon property for the
opening form to a suitable icon. (There are lots of icons in subfolders of
the Visual Basic Icons folder).
Figure 2-1
This button will be used to retrieve version information from your application.
[email protected] 114
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Step 9 Select Make EXE File... from the File menu. You will be prompted for the
location and name for the EXE file.
Figure 2-2
The options panel enables you to enter version information which will be stored in the
EXE file. This information can be accessed from code using properties of the App object.
Figure 2-3
Step 11 Enter some suitable data into the Company Name field.
[email protected] 115
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Step 15 Run the EXE file from the folder where you saved it.
Step 16 Click on the Company Name button to display the company information.
If you have the Professional or Enterprise Edition of Visual Basic 6.0, you can compile
your code either in standard Visual Basic p-code format or in native code format. Native
code compilation provides several options for optimizing and debugging that aren’t
available with p-code. P-code, or pseudo code, is an intermediate step between the high
level instructions in your basic program and the low-level native code your computer’s
processor executes. At run time, Visual Basic translates each p-code statement to native
code. By compiling directly to native code format, you eliminate the intermediate p-code
step.
The compile tab under Project Properties in the Project Menu allows you to select
compilation code options.
The three most commonly used DLLs are KERNEL (system services), GDI (graphics
device interface) and USER (window management).
[email protected] 116
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
or
The declaration is usually placed in the declarations section of a form or module and
must be typed on one line.
Step 17 Start a new project. Set the frame name to frmDLL and set the caption to
DLL Example. Save the form as frmDLL.frm and the project as
DLL.vbp. Insert a new Module.
Step 18 Type the declaration shown below into the declarations section of the new
module. It must be on one line.
The first parameter, lpBuffer, is the string in which the path will be stored
(most DLL functions were originally written in C and the different way in
which strings are handled in Visual Basic is the reason that this parameter
is passed by value).
The second parameter, nSize, is the declared length of the string lpBuffer.
The function returns a long integer which tells you the actual length of the
path found.
Step 19 Save the module as DLL.bas. Add a label named lblPath to your form
and write the following code:
Private Sub Form_Load()
Dim Path As String
Dim pathLength As Long
[email protected] 117
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Path = Space$(100) ' set up a string for the path
pathLength = GetWindowsDirectory(Path, 100)
lblPath.Caption = Path
End Sub
Step 20 Save the files. Run the application.
In this exercise you used some functions that already exist in Windows. This meant
adding a declaration for the function you were going to use and specifying the correct
parameters. The advantage of using these DLL’s is that many of the complex things you
might want to do already exist in Windows, so why rewrite them!
4.0 DoEvents
The Windows environment is event driven and commercial applications are programmed
to temporarily yield control to Windows when a time-intensive calculation is in progress.
The DoEvents statement allows you to do this from Visual Basic. It is built-in to Visual
Basic. You do not need a DLL declaration.
[email protected] 118
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
You should always use DoEvents to ensure that any event which happens while a lengthy
loop is being processed can be attended to.
5.0 Exercises
Exercise 1
The API function GetTickCount returns the number of milliseconds that Windows has
been running.
You are to develop an application which tells the user how long Windows has been
running. The application be run by double clicking an icon on the desktop. The main
form will look something like the following:
Figure 5-1
Your application will include an About menu which opens a form providing similar
information to the About form for Visual Basic or other Microsoft products. The About
form uses properties which are set when the application is made into an EXE file. Your
form should look something like:
Figure 5-2
Clicking the System Information button will start up the MS System Information program
shown below.
[email protected] 119
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 5-3
Steps
1.1 Design the main form. It needs a menu and a label to display the Windows has been
running... message. Choose a suitable icon for the form.
1.2 Find the API declaration GetTickCount and paste it into a new module. (You may
wish to develop a module containing the dll declarations which you use commonly).
1.3 Add code to the Form Load event to display the message shown in the label. For
example:
frmMain.Show
NumOfMins = calculation
lblMinutes = “Windows has been running for “ & NumOfMins & “
minutes.”)
For the calculation of NumOfMins, remember that the GetTickCount function returns the
number of milliseconds since windows started so you will need to divide by 60000 and
use the Int function to round the result.
1.4 Select Add form from the project menu and select an ABOUT DIALOG form. Look
at the code attached to this form and see how it uses dlls to find the location of the
program MSInfo32.exe.
1.5 Return to your main form and add code to the About menu item to show the about
form.
1.6 Add labels to the About form to display values for CompanyName (to the name of
someone who is buying your software), Legal Copyright and Legal Trademarks. Add
code to the load event to display in these labels, suitable properties for these values.
Make the application into an EXE file. When you do this, select Options and enter values
for the new labels. Save the EXE file on your desktop.
[email protected] 120
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Visual Basic also provides a data control which provides simple access to Microsoft
Access databases from your Visual Basic application. The following simple example
shows you how to view the data from a table.
Step 2 Start a new project and put a data control, three text boxes and a label on
your form. Name the form as frmDataControl and set the caption to
Data Control Demo. Save the form as frmDataControl.frm and save the
project as DataControl.vbp
[email protected] 121
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 1-1
Step 4 Set the DatabaseName property of the Data control to the name and path
of the Employees database.
Step 5 Set the RecordSource property to the name of the Table “Employee
Details”.
Now that the Data control is attached to the Employee Details table, you can use the Text
Boxes to display the values of fields from that table.
Step 6 Set the DataSource and DataFields properties of the Text Boxes as
shown.
[email protected] 122
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Step 7 Save the files. Run the application and use the data control to step through
the records in the Employee Details table.
Figure 1-2
If you type into the text boxes which are bound to the data control, you will change the
data in the underlying field unless the database is in read only mode. You can protect the
data by setting the Locked property of the text boxes or by using labels instead of text
boxes to display the data.
Step 8 Set the Locked property for each of the bound text boxes to True.
The Label control is going to be used to display a message depending on the salary of the
current employee. The code to do this is placed in the Reposition event for the data
control. This event is triggered each time a new record is selected.
Step 9 Add the following code to the Reposition event for the data control.
Private Sub datEmployees_Reposition()
Select Case txtSalary.Text
Case Is > 40000: lblMessage.Caption = "seriously
rich"
Case 30000 To 39999: lblMessage.Caption = "almost
rich"
Case Else: lblMessage.Caption = "has far to go"
End Select
End Sub
Step 10 Save the project. Run the application and change the records to see the
label caption change.
[email protected] 123
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 1-3
The DBList ad DBCombo controls are data bound list boxes and combo boxes which are
automatically populated from a field in an attached Data control, and can be used to
optionally update a field in a related table of another Data control.
The DBGrid control displays and enables data manipulation of a series of rows and
columns representing records and fields from a Recordset object.
The MSFlexGrid control displays and operates on tabular data. It allows complete
flexibility to sort, merge, and format tables containing strings and pictures. When bound
to a Data control, MsFlexGrid displays read-only data.
The following simple example shows how to use the DBList, DBCombo and DBGrid
controls to select values from a field in a table from an Access database. The values
selected are added to a listbox. See visual Basic Books Online for more complex
examples.
Step 11 Start a new project. Add a Combo box and set the name to dbCombo.
Add a dbList object (you may need to select Components from the project
[email protected] 124
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
menu). Add a Data Control object. Add a dbGrid object. Add three list
boxes. Name the form as frmDataBound and set the caption to Data
Bound Demo. Save the form as frmDataBound.frm and the project as
DataBound.vbp
Figure 1-2
Step 12 Set the DatabaseName property of the Data control to the name and path
of the Employees database.
Step 13 Set the RecordSource property to the name of the table “Employee
Details”.
Step 14 Select the DBCombo control. Set the RowSource property to Data1 and
the ListField property to Surname.
Step 15 Save the project and files. Run the application. You should see the
employees names in the drop down combo box.
Step 16 Add the following code to the Click event for DBCombo1.
Private Sub DBCombo1_Click(Area As Integer)
If Area = dbcAreaList Then
List1.AddItem DBCombo1.Text
End If
End Sub
The Area parameter is used to detect that the user has clicked an item in the list rather
than the drop down arrow.
Step 17 Select DBList1. Set the RowSource property to Data1 and the ListField
property to Surname.
Step 18 Add the following code to the Click event for DBList1.
Private Sub DBList1_Click()
List2.AddItem DBList1.Text
End Sub
[email protected] 125
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Note that the DataSource and Datafield properties for the DBList and DBCombo controls
are Not used to fill the control.
Step 19 Select the DBGrid control. Set the DataSource property to Data1.
The default settings will display all the fields in the grid. You can specify only certain
fields by using the Custom property.
The following step shows how to retrieve the data value from a specified column in the
grid by clicking anywhere in the row.
Step 20 Add the following code to the MouseUp event for DBGrid1.
Private Sub DBGrid1_MouseUp(Button As Integer, Shift As
Integer, X As Single, Y As Single)
Dim theCol As Integer, Bookmark As Variant
theCol = DBGrid1.ColContaining(X)
Bookmark = DBGrid1.RowBookmark(DBGrid1.RowContaining(Y))
List3.AddItem DBGrid1.Columns(1).CellValue(Bookmark)
End Sub
Step 21 Save the project and files. Run your application and select an item from
each of the data bound controls to test that your code works.
OLE allows you to display and edit data from other applications. An object is data plus
the link to the application software where the data originated e.g. an Excel Worksheet, an
Excel Chart, a Word document.
Link i.e. share the data with other applications. The data remains in its
original location.
or
[email protected] 126
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Embed i.e. to copy the original data into your application and store the
copy there.
Double clicking the OLE control on your form will activate the object’s application.
Visual Basic also allows you to activate the object from your code.
The following steps show you how to create a form like the following to demonstrate
some of the power of OLE.
Figure 1-1
Step 22 Start a new project and add an OLE control to the form. Name the form as
frmOLE and set the caption to OLE Demo. Save the form as
frmOLE.frm and save the project as OLE.vbp
When you put an OLE control on the form, a dialog box appears.
Step 23 Select Create New and Microsoft Word Picture from the Object Type
list.
Figure 1-2
[email protected] 127
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Creating a Word Picture will allow you to access the WordArt application to define the
text and style for your title. You may need to adjust the scrollbars to position the wordart
in the centre of the screen.
Figure 1-3
Step 24 Select Insert; Picture; WordArt from the menu and choose a suitable style.
Enter ‘OLE Demonstration’ in the font and style of your choice and click
on OK.
Step 25 Close the Word window to return to the Visual Basic application. Set the
BackStyle property of the OLE control to Transparent and the SizeMode
property to Stretch.
Step 26 Save the files and project. Run your application. Double click on the OLE
control and WordArt to make adjustments to your title.
Step 28 Select Create from File and use the Browse button to find the Word
document pcskills/oledemo.doc.
[email protected] 128
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 1-5
This Word document page has been sized so that it will fit onto a form.
Figure 1-6
Step 31 Save your project and files. Run your application. Double click the OLE
control to see that Word is activated with the selected document opened.
If you have a sound card and speakers, you can use a .wav file for the following example.
Otherwise, create and save a Powerpoint presentation.
[email protected] 129
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Step 34 Select create from file and select a .wav file or a Powerpoint presentation.
Select Link.
Step 35 If you have chosen a Powerpoint presentation, check the Display as Icon
box.
Step 36 Click on OK. Save the form as frmOLE2.frm. Save the project as
OLE2.vbp.
Step 37 Change the Name property to oleWaveFile (for using a wave file) or
olePowerpoint (if using a powerpoint).
Step 39 Add a command button to the form. Set the Name property to
cmdActivateSound or cmdActivateSlideShow and set the Caption
property to something appropriate.
The DoVerb method for an OLE control allows you to carry out the specified action. For
example, an object can be opened for editing or can be played. You can find out what
actions are available for an object by clicking the right mouse button on the object at
design time.
The constant vbOLEPrimary will carry out the primary (most usual) action for the object.
Otherwise use the numeric position in the list of actions (starting at zero).
Step 40 Add the following code to the Click event for the command button.
Private Sub cmdActivateWave_Click()
oleWaveFile.DoVerb vbOLEPrimary
End Sub
or
[email protected] 130
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 1-7
Step 41 Save your project and files. Try out your application.
Step 43 Start a new Visual Basic project and add the following code to a command
button on the form.
Private Sub cmdPrintReport_Click()
Dim DBPath As String
Dim appAccess As Object
Set appAccess = CreateObject("Access.Application.7")
DBPath = " path and name of your database … "
appAccess.OpenCurrentDatabase DBPath
appAccess.DoCmd.OpenReport "name of your report…"
End Sub
This code activates Access, prints the report to the printer and returns to your Visual
Basic application.
[email protected] 131
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
If you are worried about your print budget, change the last line of the code to
appAccess.DoCmd.OpenReport "name of your report…",2
5.0 Exercises
Exercise 1
Add an image control to the form for the Data control application you developed in Steps
2 to 10. Use this control to display a suitable picture for each of the three categories of
salary as you step through the Employee Details table.
Exercise 2
Add an embedded spreadsheet in an OLE control to your OLE Demo application. Set the
visible property for the OLE control to False.
Add a command button to the form and write code so that when the button is clicked, the
OLE control becomes visible and opened for editing.
[email protected] 132
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
In an MDI application, the main form is called the MDI form, and the document forms
are called MDI child forms. You usually design only one child form for an MDI
application. This form is then copied for each document that is opened.
In this chapter, you will create an MDI application based on the SDI FileViewer which
you developed in Chapter 7.
Step 1 Start a new project and remove the existing Form1 (select Remove Form1
from the Project menu).
Step 2 Select Add MDI Form, New, from the Project menu. Click on MDI Form.
Click Open.
[email protected] 133
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 2-1
Step 3 Change the Name property for this form to MDIEditor.
Step 4 Select Add Form, Existing, from the Project menu and add the form you
developed for the FileViewer application (frmFileViewer.frm).
Step 5 Select the Fileviewer form. Change the MDIChild property to True.
Step 6 Change the Name property to frmDoc. Save the form as frmDoc.frm.
Save the MDI form as mdiEditor.frm and the project as MDI.vbp
You will write code to create a new instance of this form each time a new document is
opened.
Step 7 Add the following code to the Resize event for the frmDoc form
Private Sub Form_Resize()
rtbDisplay.Move 0,0,Me.Width – 100, Me.Height - 300
End Sub
[email protected] 134
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
attach all the menu options to the MDI form and disable the options not available
until there is a child form open
attach menu options to the child form and use a different menu on the MDI form –
the menu on the MDI form will automatically be replaced by the menu on the
child form as soon as a child form is opened
The child form that you have just added to the project, already has a menu attached so the
second option is preferable for this project.
Step 8 Select code for the frmDoc form and amend the mnuNew and
mnuOpenFile options as shown
The main MDI form can be given a simple menu to enable the first document to be
opened.
Step 9 Select the MDIEditor form and use the Menu Editor to set up a menu
which looks like the following
[email protected] 135
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 2-2
Caption Name
&File mnuFile
&New mnuNew
&Open mnuOpen
- mnuSep1
E&xit mnuExit
Step 10 Add a common dialog control to form MDIEditor. Change its Name
property to cdlViewer.
Step 11 Copy the code from the frmDoc form New and Open options to the New
and Open options for the MDIEditor form.
Step 12 Add code for the mnuExit option to the MDIEditor form
Private Sub mnuExit_Click()
End
End Sub
Step 13 Save the project and files. Run the application to test the main menu
options. (You will need to set Start Up Object to MDIEditor).
Figure 2-3
[email protected] 136
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
You will also need to ensure that the child forms are properly closed if the user presses
the close button on the main MDI form.
Step 15 Add the following declaration to the General Declarations section of the
frmDoc1 form (below the Option Explicit statement).
Step 16 Add this code to the Change event for the rtbDisplay (the rich textbox).
Private Sub rtbDisplay_Change()
Changed = True
End Sub
Step 17 Amend the code for the mnuSaveFile option for frmDoc1 form as shown
Private Sub mnuSave_Click()
Dim strFileName As String
cdlViewer.Filter = "RTF|*.rtf|Text|*.txt"
cdlViewer.ShowSave
On Error GoTo SaveProblems
strFileName = cdlViewer.filename
If cdlViewer.FilterIndex = 1 Then
cdlViewer.DefaultExt = “RTF”
rtbDisplay.SaveFile strFileName, rtfRTF
[email protected] 137
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Else
cdlViewer.DefaultExt = “txt”
rtbDisplay.SaveFile strFileName, rtfText
End If
Me.Caption = strFileName
Changed = False
Exit Sub
SaveProblems:
MsgBox "Can’t save the file, try again.",
vbCritical
Exit Sub
End Sub
Step 18 Add code to the mnuClose option of the frmDOC1 form.
Private Sub mnuClose_Click()
Unload Me
End Sub
The Unload event will cause the child form to be unloaded but before it does this, it
triggers the QueryUnload event for the form. This event allows you to cancel the unload
if you wish.
Step 19 Add the following code to the QueryUnload event for the frmDoc1 form
(select Form, QueryUnload in the code window)..
Private Sub Form_QueryUnload(Cancel As Integer, _
UnloadMode As Integer)
Dim Response As Long
If Changed Then
Response = MsgBox("Are you sure you want to close_
without saving?", vbYesNoCancel, Me.Caption)
Select Case Response
Case vbNo: Cancel = True
Case vbCancel: Cancel = True
End Select
End If
End Sub
This QueryUnload code will also be executed if the user clicks the Close button on a
child form.
Step 20 Amend the code for the mnuExit option on the frmDoc1 as shown
Private Sub mnuExit_Click()
Unload MDIEditor
[email protected] 138
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
End
End Sub
An Unload event for the main form is triggered if the Close button on the main form is
clicked so you don’t need to do anything further to deal with this event.
Figure 2-4
Caption Name
&Edit mnuEdit
C&ut mnuCut
C&opy mnuCopy
&Paste mnuPaste
&Delete mnuDelete
[email protected] 139
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
The collection also includes the ImageList control which is used as a central repository to
supply other controls with images. An ImageList control contains a collection of
ListImage objects, each of which can be referred to by its index or key.
This section shows you how to use the Toolbar and ImageList control to add an edit
toolbar containing Cut, Copy and Paste buttons to your application.
[email protected] 140
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
5.1 Using an ImageList control to store button pictures for the toolbar
The imagelist control will be used as a repository for the images on the toolbar buttons.
Step 26 Change the Name property for the ImageList control to imlToolbar.
Step 27 Right click on the ImageList control and select Properties to bring up the
property pages.
Figure 5-1
Step 28 On the General tab, select Custom size. (This will size the images to the
size of the first image added).
Step 30 Add an image for the Cut button and set the Key property to Cut.
Step 31 Repeat the last step for Copy and Paste. Then click OK to close the
Property Pages dialog box.
[email protected] 141
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 5-2
Note that the cut picture has an index value of 1, the copy image an index value of 2, and
the paste image an index value of 3. The images in the imagelist control can be
referenced either by using the index or the key values.
Step 32 Add a ToolBar control to the MDIEditor3 form. Change the Name
property to tlbEditor.
Step 33 Right click on the toolbar control and select Properties to bring up the
property pages.
Figure 5-3
Step 35 Select the Buttons tab and select Insert Button.
[email protected] 142
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Step 36 Set the Key, ToolTip Text and Image values as shown.
Figure 5-4
Button Index ToolTipText Key Image
Cut 1 Cut text Cut 1
Copy 2 Copy text Copy 2
Paste 3 Paste text Paste 3
Step 37 Repeat the last step for the Copy and Paste buttons.
Figure 5-5
[email protected] 143
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Step 38 View the code for form frmDoc3 and change the Private declaration to
Public for the Cut, Copy and Paste menu options.
Public Sub mnuCut_Click()
Clipboard.Clear
Clipboard.SetText rtbDisplay.SelText, vbCFRTF
' Delete selected text.
rtbDisplay.SelText = ""
End Sub
Step 39 View the code for form MDIEditor3 and add the following event code
Private Sub tlbEditor_ButtonClick(ByVal Button As
ComctlLib.Button)
On Error GoTo NoActiveForm
Select Case Button.Key
Case "Cut": Me.ActiveForm.mnuCut_Click
Case "Copy": Me.ActiveForm.mnuCopy_Click
Case "Paste": Me.ActiveForm.mnuPaste_Click
End Select
Exit Sub
NoActiveForm:
Exit Sub
End Sub
The error code is added to deal with the buttons being clicked when there is no child form
open.
Step 40 Using the Menu Editor, add an Options menu to the MDIEditor3 form
menubar. Add a submenu to this called toolbar.
Caption Name
&Options mnuOption
&Toolbar mnuToolbar
[email protected] 144
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Figure 5-6
Step 41 Select the checked option for the toolbar menu item. Close the menu
editor.
This example displays a pop-up menu at the cursor location when the user clicks the right
mouse button over the rich textbox displaying a document.
[email protected] 145
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Step 43 Add a menu to the frmDoc3 form that contains the options shown
Figure 6-1
Caption Name
&Popup mnuPopup
&Cut mnuPopupCut
C&opy mnuPopupCopy
P&aste mnuPopupPaste
C&hange Font mnuPopupChangeFont
Step 44 Make sure that the Visible box for the menu header is not checked.
[email protected] 146
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Step 46 Add the following code to the MouseUp event for rtbDisplay (the rich
textbox) on form frmDoc3.
Private Sub rtbDisplay_MouseUp(Button As Integer, Shift As
Integer, x As Single, y As Single)
If Button = 2 Then
Me.PopupMenu mnuPopup
End If
End Sub
Save the project and files and test the application. You should now get a context menu if
you click the right mouse button anywhere in a document.
7.0 Exercises
Exercise 1
Add an undo option to the Edit menu which undoes the last delete. (Hint: declare a public
string variable and copy the selection to this variable when Delete is executed).
Exercise 2
Add a Windows menu to your application which includes the options to Tile or Cascade
the currently open child windows. (Hint: use the Arrange method for MDIEditor).
Data Access
[email protected] 147
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Data Access/1
These tools include the Microsoft Jet database engine, the Data control, and the data
access objects (DAO) programming interface.
Using data access objects, you can create databases and build full-featured applications
that access existing databases in many popular formats, including Microsoft Access,
Btrieve, dBASE, Microsoft FoxPro, and Paradox, as well as Open Database Connectivity
(ODBC) client/server databases like Microsoft SQL Server.
The ability to create and access structured database systems gives you many
programming advantages:
Visual Basic provides data access capability based on the Microsoft Jet database engine,
the same database engine that powers Microsoft Access.”
The following examples show you how to use the data control with more flexibility. The
examples use a database called TheWarehouse.mdb which includes table Customers
(with fields CustomerID, CustomerName, Address, City).
[email protected] 148
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
[email protected] 149
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Note the single quotes around London. These would not be necessary if you were
matching a numeric field.
[email protected] 150
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Changes made to the contents of a bound control will be made to the underlying recordset
unless the Locked property of the control is set.
The current record can be deleted using the Delete method but take care because there is
no prompt to check that you really mean it!
[email protected] 151
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
End Sub
Requirements: IBM-PC
One 5.25" floppy diskette (supplied by tutor,
returnable at end of course)
1.1.1 Insert the special tutor supplied diskette into Drive A (the topmost slot) of the
IBM-PC.
1.1.2 The IBM-PC has a red power switch on the right-hand side, towards the
rear of the base unit. This switch has two positions marked 0 and
1. Flip this power switch to the position marked 1.
[email protected] 152
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
1.1.3 If the computers power switch is already at the position marked 1, re-
initialise the computer by pressing the Ctrl Alt Del keys
simultaneously.
1.1.4 The computer will display the messages similar to those which follow, at
the top of the screen.
A>
[email protected] 153
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
2 STARTING BASIC
A>GWBASIC<enter>
The <enter> signifies that you must press the enter key after
entering the keyword GWBASIC. In fact, in order for the
computer to accept all commands, they must be terminated with
the <enter> key. This informs the computer that you have
finished typing, and it may now act on your instructions.
The screen will clear, the cursor prompt should now have
changed to an underscore, and a message informing you that
basic is available.
Coding is the task of converting the small steps into the actual
computer language, then combining these steps into one unit (ie,
the program.
[email protected] 154
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
10 LET A = 3
20 PRINT A
30 END
LINE 10
LINE 20
[email protected] 155
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
LINE 30
_LIST<enter>
_LIST
10 LET A = 3
20 PRINT A
30 END
Ok
_
_RUN<enter>
The computer will start execution at the lowest line number, line
10, and continue executing each statement until the END
statement is encountered in line 30. The resultant display will be,
_RUN
[email protected] 156
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
3
Ok
_
_SAVE "Myprogram"<enter>
_NEW<enter>
_LOAD "Myprogram"
_FILES<enter>
[email protected] 157
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
_LLIST<enter>
_DELETE 10<enter>
_DELETE 20-50<enter>
_SYSTEM<enter>
A>
[email protected] 158
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
LLIST Lists the lines of the program to the printer. The program will not be printed
until you exit from BASIC.
LLIST 100-200 lists lines 100 to 200 to the printer
SYSTEM Exits BASIC and returns to DOS (Disk Operating System). Any
programs waiting to be printed will now go to the printer.
[email protected] 159
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
BASIC
Example of a BASIC program Given a rate of 500mph and time traveled of 6 hours,
display the distance traveled.
10 LET X = 4
10 LET A = 1
20 LET B = 2
30 LET Y = A + B Y = ___________
10 LET X = 1
20 LET C = 4
30 LET X = X - C X = ___________
[email protected] 160
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
10 LET D = 2
20 LET Z = D * 3 Z = ___________
10 LET E = 8
20 LET W = E / 8 W = ___________
Exponential ^ Means a number raised to the power of, ie, 102 means 10 * 10, and Y3
means Y * Y * Y
10 LET F = 2
20 LET V = F ^ 3 V = ___________
1 Exponential ^
2 Multiplication and division * /
3 Addition and Subtraction + -
4 The operators are always evaluated left to right
Parenthesis can be used to override the order of precedence. Consider the following
equation,
Y+B
X = -------
C
10 LET X = Y + B / C
[email protected] 161
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Brackets can be placed around terms to instruct BASIC about how to perform
calculations. BASIC always performs those calculations inside brackets first, so the
above statement is actually written as
10 LET X = (Y + B) / C
/*------------------------------------------------------------------*/
SELF TEST on Operator precedence Given that
10 LET A = 1
20 LET B = 2
30 LET C = 4
40 LET X = A / B / C _____________
50 LET X = A + B / C _____________
60 LET X = A * B * C _____________
70 LET X = A * B - C _____________
80 LET X = A ^ B + C _____________
90 LET X = A / B * C _____________
100 LET X = A * B / C _____________
110 LET X = A ^ B - 1 _____________
/*------------------------------------------------------------------*/
A+B
X = -------
C+D
10 LET X = ( A + B ) / ( C + D )
and
B
X=A+-+D
C
[email protected] 162
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
10 LET X = A + ( B / C ) + D
/*------------------------------------------------------------------*/
SELF TEST on Expressions Write statements in BASIC to correctly evaluate each of
the following expressions.
2 2
1. Z = X + Y 2. Z = ( X + Y )
A+B+E B
3. Z = ----------- 4. Z = A + -
D+E C
A+B B
5. Z = ------- 6. Z = A + -------
C D-C
/*------------------------------------------------------------------*/
In BASIC, all calculations must be performed on the right hand side of the = sign. The
statement
10 LET -C = Y
is wrong, because you cannot do assignments ( - ) on the left side. The statement should
be re-written as,
10 LET C = - ( Y )
[email protected] 163
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
/*------------------------------------------------------------------*/
SELF TEST on BASIC STATEMENTS for each of the following statements, re-write
them correctly.
10 LET Y = 2X + A
10 _________________________
20 LET 4 = X - Y
20 _________________________
30 LET A = 1 / ( X + ( Y - 2 )
30 _________________________
40 LET -J = K + 1
40 _________________________
50 LET S = T / * 3
50 _________________________
60 LET Z + 1 = A
60 _________________________
/*------------------------------------------------------------------*/
DATA NAMES Names given to variables which represent data can be a maximum of
32 alphanumeric characters. Some BASIC versions only recognize the first two
characters. The first letter of the data name must be ALPHABETIC and lowercase letters
are treated as uppercase.
Examples of NUMERIC VARIABLES are,
Data names should be meaningful and self explanatory. It is pointless having cryptic
variable names.
[email protected] 164
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
THE PRINT STATEMENT The PRINT statement in BASIC is provided to allow the
displaying of text and the value which variables contain, on the screen. There are many
variations to the PRINT statement.
10 PRINT A;B In this case, a space will occur between the values
of A and B.
Referring back to the first program, the displayed result can be made easier by changing
line 50 as,
/*------------------------------------------------------------------*/
SELF TEST on PRINT What would you expect to be displayed after the following
program is executed.
10 LET A = 1
20 LET B = 5
30 LET C = 1.20
40 PRINT "A=";A
50 PRINT "B= ",B
[email protected] 165
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
60 PRINT B+A;B
70 PRINT "C = ";C
80 END
(NOTE: The END statement signifies the end of the program and must have the highest
line number. If execution is to stop elsewhere then use a STOP statement)
/*------------------------------------------------------------------*/
EXERCISE ONE Write a program to calculate the time required to travel 3000 miles at
a speed of 500 mph.
EXERCISE TWO Write a program to calculate the gross pay for a worker named
FRED given that FRED worked 40 hours at $2.90 per hour.
Everything after the REM statement on that line is treated as a comment and is ignored
by the computer when the program is executed. The student should use lots of comments,
especially for subroutines. The entry and exit conditions and variables used should be
clearly listed for each subroutine.
[email protected] 166
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
The relational operators used to compare two values as part of the decision making
process are,
When the condition associated with the IF statement is true, the program statement
following the THEN keyword is executed.
Examples,
/*------------------------------------------------------------------*/
SELF TEST on IF THEN ELSE What is displayed when the following program is
executed?
10 LET A = 5 : B = 3 : C = 99 : D = 5
50 IF A > 6 THEN PRINT "A"
60 IF A > B THEN PRINT "B"
70 IF B = C THEN PRINT "C" : PRINT "D"
80 IF B <> C THEN PRINT "E" ELSE PRINT "F"
90 IF A >= C THEN PRINT "G" ELSE PRINT "H"
100 IF A <= D THEN PRINT "I" : PRINT "J"
110 END
/*------------------------------------------------------------------*/
[email protected] 167
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
EXERCISE FIVE Write a program which inputs two values, call them A and B. Print
the value of the largest variable.
EXERCISE SIX Modify the program you wrote in response to EX 5, to accept three
values, A B C, and print the largest value.
10 IF A = 1 OR B = 2 THEN PRINT X
/*------------------------------------------------------------------*/
SELF TEST on AND OR NOT What is displayed when the following program is
executed?
10 LET A = 5
20 LET B = 3
30 LET C = 99
40 IF A = 5 OR B > 2 THEN PRINT "A"
50 IF A < 5 AND B > 2 THEN PRINT "B"
60 IF A = 5 AND B = 2 THEN PRINT "C"
70 IF C <> 6 OR B > 10 THEN PRINT "D" ELSE PRINT "E"
80 IF B = 3 AND C = 99 THEN PRINT "E"
90 IF A = 1 OR B = 2 THEN PRINT "F"
100 IF NOT (A < 5 AND B > 2) THEN PRINT "G"
110 END
/*------------------------------------------------------------------*/
EXERCISE SEVEN Write a program which inputs the ordinary time and overtime
worked, calculating the gross pay. The rate is given as $4.20 per hour, and overtime is
worked out at time and a half.
[email protected] 168
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
EXERCISE EIGHT For the first twenty values of Celsius, print out the equivalent
degree in Fahrenheit ( Use a tabular format, with appropriate headings). Use the CLS
command to initially clear the screen.
EXERCISE NINE Modify exercise seven to also calculate the NET pay ( Gross - tax).
Tax is to be calculated as follows,
LOOPS (ITERATION in JSP) The most common loop in BASIC is the FOR NEXT
loop. Whatever is inside the for next block will be executed a number of times depending
on the iterated condition. Its format is,
10 CLS
20 PRINT "DEG C","DEG F"
30 FOR C = 1 TO 20 STEP 1
40 LET F = (9 / 5) * C + 32
50 PRINT C,F
60 NEXT C
70 END
If a step count is omitted, a step increment of one is assumed. The variable name after the
NEXT should be included.
/*------------------------------------------------------------------*/
SELF TEST on FOR NEXT What is the output of this program.
10 S = 0
20 FOR J = 1 TO 5
30 PRINT J;
40 LET S = S + J
50 NEXT J
60 PRINT S
70 FOR K = 0 TO 1 STEP .3
80 PRINT K;
90 NEXT K
[email protected] 169
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
[email protected] 170
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
NESTED LOOPS For next loops may be nested one within another, so that the inner
loop ( which contains a block of statements ) is repeated by the outer loop.
/*------------------------------------------------------------------*/
SELF TEST on NESTED FOR NEXT LOOPS What is the output of the following
program,
10 PRINT "LINE"
20 FOR L = 1 TO 6
30 PRINT L,
40 FOR C = 1 TO 4
50 PRINT "COLUMN ";C,
60 NEXT C
70 PRINT
80 NEXT L
90 END
/*------------------------------------------------------------------*/
eg, 3! = 1 * 2 * 3 = 6
Evaluate the factorial of an integer less than 20, for five numbers input successively via
the keyboard.
THE READ AND DATA STATEMENTS The read and data statements can be used to
simplify programming. The two statements are used together, eg,
10 DATA 8,2,1,78,3,91,7
[email protected] 171
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
20 READ N
30 FOR I = 1 TO N
40 READ A
50 PRINT A;
60 NEXT I
70 STOP
80 DATA 13,11
90 END
/*------------------------------------------------------------------*/
SELF TEST on READ and DATA What is displayed after the following code is
executed?
10 READ A,B,C
20 PRINT A + B + C
30 LET S = 0
40 FOR I = 1 TO 5
50 READ X
60 LET S = S + X
70 NEXT I
80 PRINT S
90 STOP
100 DATA 11,2
110 DATA 6,18,21
120 DATA 3,5,19
130 END
/*------------------------------------------------------------------*/
THE WHILE WEND LOOP Loops should not be implemented using GOTOS. These
are considered harmful and make a program difficult to debug and to follow program
logic.
[email protected] 172
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
10 SUM = 0
20 READ NUMBER
30 WHILE NUMBER > 0
40 SUM = SUM + NUMBER
50 READ NUMBER
60 WEND
70 PRINT SUM
80 DATA 10, 20, 30, 15, 40, 0
90 END
Notice that the program has been implemented without the use of a GOTO command.
This has benefits in that changing the line numbers, inserting code etc, will not effect the
program.
NOTE: The program also illustrates the READ AHEAD technique. Before entering the
while loop the data is first read (Line 20). It is tested for validity on entry to the loop
(Line 30) and then processed (Line 40). Before looping again, the data is read again (Line
50), which allows escaping from the while loop.
/*------------------------------------------------------------------*/
SELF TEST on WHILE WEND What is the output?
10 LET PASSED = 0
20 READ NAME$, MARK
30 WHILE NAME$ <> "LAST"
40 IF MARK >= 50 THEN PASSED = PASSED + 1
50 READ NAME$, MARK
60 WEND
70 PRINT PASSED
80 STOP
110 DATA "ALF", 33
120 DATA "BERT",81
130 DATA "DAVE",50
140 DATA "ERIC",49
150 DATA "FRED",49
160 DATA "LAST",0
170 END
/*------------------------------------------------------------------*/
RESTORE This statement resets the data list pointer back to the beginning of the list so
that it may be processed again.
[email protected] 173
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
EXERCISE 11 Given data as in the self test on the while/wend statement above, write a
program to list the grade achieved by each student. Given
A grade 70 - 100
B grade 60 - 69
C grade 50 - 59
D grade 40 - 49
E grade 0 - 39
Also grade ABC as passes, DE as failures. Print each student's name and grade, and at the
end print the total number of passes and failures.
ARRAYS Arrays are defined using the DIM statement. The array consists of so many
elements, specified within the brackets, where each element can hold a piece of data. The
DIM statement informs the computer to find enough space for the array. You cannot use
a variable to specify the number of elements in the array as part of the DIM statement.
eg, 10 DIM A(5) This dimensions an array called A which has five
elements. The elements are accessed using an index (subscript).
[email protected] 174
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
30 FOR I = 1 TO 5
40 READ A(I)
50 NEXT I
x(i)
so that x(5) refers to the fifth element in an array called x. In BASIC, array elements start
with 1. Assigning values to array elements is done by,
DECLARING ARRAYS Arrays may consist of any of the valid data types, characters or
numeric. Arrays are declared along with all other variables in the declaration section of
the program, which occurs at the beginning of the program, eg,
The above program declares two numeric arrays, assigns 10 as the contents of the tenth
element of array x, subtracts ten from this value, and finally prints the value.
10 DIM m(10,10)
/*------------------------------------------------------------------*/
SELF TEST on ARRAYS What is displayed after the following code is executed?
[email protected] 175
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
30 FOR I = 1 TO 8
40 READ F(I)
50 NEXT I
60 PRINT F(3), F(6)
70 LET S = 0
80 FOR I = 1 TO 8 STEP 2
90 LET S = S + F(I)
100 NEXT I
110 PRINT S
120 LET L = 0
130 FOR I = 1 TO 8
140 IF F(I) > L THEN L = F(I)
150 NEXT I
160 PRINT L
170 END
10 DATA 33, 81, 72, 58, 63, 71, 90, 85, 83, 53
20 DIM N(10)
30 FOR I = 1 TO 10
40 READ N(I)
50 NEXT I
60 PRINT "STUDENT NUMBER","MARK"
70 FOR P = 1 TO 10
80 LET M = 0
90 FOR I = 1 TO 10
100 IF N(I) > M THEN LET M = N(I) : LET S = I
140 NEXT I
150 PRINT S,M
160 LET N(S) = 0
170 NEXT P
180 END
/*------------------------------------------------------------------*/
EXERCISE 12 Given the following marks achieved in a programming test, and that the
pass mark is the average of all the marks, write a program to list those students who have
passed.
FRED 21
GEORGE 56
ANNE 52
MARY 89
ROBERT 71
[email protected] 176
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
ALFRED 71
CECIL 33
MIKE 54
JENNIFER 41
PAULINE 48
FRED A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B
BERT A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A
JEAN A,B,C,D,A,B,C,D,A,B,C,D,A,B,C,D,A,B,C,D
ADRIAN A,B,C,D,A,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E
ALISON A,B,C,A,A,B,C,A,A,B,C,A,A,B,C,A,A,B,C,A
Write a program which has the above information set up in data statements, and then
mark each student, displaying name and mark (%).
EXERCISE 13A Given the data for exercise 12, write a program that sorts the students
into ascending order of marks and prints them out ( name and mark).
10 T = 0
20 INPUT C
30 LET S = 2 * C
40 GOSUB 100
50 INPUT C
60 IF C = 5 THEN LET S = 20 ELSE LET S = 15
70 GOSUB 100
80 STOP
100 LET T = T + S
110 PRINT C, S, T
120 RETURN
130 END
/*------------------------------------------------------------------*/
[email protected] 177
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
10 LET A = 0
20 GOSUB 200
30 FOR I = 1 TO 5 STEP 2
40 GOSUB 200
50 NEXT I
60 A = A / 2
70 GOSUB 200
80 STOP
200 LET A = A + 1
210 PRINT A;
220 RETURN
230 END
/*------------------------------------------------------------------*/
[email protected] 178
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
FUNCTIONS There are many special functions which can be used to return specified
values. Two of these are RND and INT.
INT Returns the largest integer not greater than the numeric
expression. eg,
INT(16.753) will give 16
INT(-3.2) will give -4
Sample program,
5 CONTINUE = 1
10 WHILE CONTINUE <> 0
20 LET B = RND
30 LET B = INT(B * 20)
40 LET C = INT(RND * 20)
50 PRINT B;" + ";C;" = ";
60 INPUT TA
70 IF TA = 0 THEN CONTINUE = 0
80 LET A = B + C
90 IF TA = A THEN PRINT "Correct"
100 ELSE GOSUB 200
110 WEND
TAB The TAB(c) command in the print list moves the cursor the number of spaces
specified by the variable c, on the current line, eg,
PRINT TAB(5);"A";TAB(11);"B";"C"
LOCATE row, column is used to move the cursor to the co-ordinates specified by the
variables row and column. The screen is arranged as 80 columns across (0-79) by 25
rows down (0-24).
[email protected] 179
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
10 LET A = 1.1
20 LET B = 20
30 LET F$ = "#.# ##"
40 PRINT USING F$ ; A,B
displays 1.1 20
/*------------------------------------------------------------------*/
SELF TEST on FORMATTED OUTPUT What will be displayed for the following
code?
10 A = 1.2
20 B = 333
30 C = 0.121
40 F$ = " ## ####.# #.##"
50 PRINT USING " ### ###.#"; B,B
60 PRINT USING F$; A,B,C
70 PRINT USING F$; A,A,A
80 PRINT USING F$; C,C,C
90 END
/*------------------------------------------------------------------*/
TRUNCATION
[email protected] 180
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
calculate the total breakdown of required coins ( ignore dollars) into 50c, 20c, 10c, 5c, 2c,
1c pieces.
STRINGS
ASSIGNMENT OF STRINGS
10 LET N$ = S$
20 LET S$ = "STEM"
30 LET N$ = "" ! "" is a null string
10 READ A$
20 DATA FRED ! assigns FRED
30 DATA " FRED " ! assigns ...FRED.
NOTE: Leading spaces, commas, and semicolons must be inside quotes if they are
included as part of the string.
Thus, the code for A is less than the code for B so,
When strings are being compared, comparison is done from left to right until a non-match
is found, thus
[email protected] 181
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
/*------------------------------------------------------------------*/
SELF TEST on STRING CONCATENATION Work out what will be printed when
the following program is run.
10 LET A$ = "BAT"
20 LET W$ = A$ + "TY"
30 PRINT W$
40 PRINT A$ + A$ + A$
50 LET A$ = A$ + A$
60 PRINT A$
70 LET M$ = ""
80 FOR I = 1 TO 5
90 LET M$ = M$ + "*"
100 PRINT M$
110 NEXT I
120 END
/*------------------------------------------------------------------*/
[email protected] 182
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
/*------------------------------------------------------------------*/
SELF TEST on MID$ What does the following statements assign to X$
10 LET A$ = "ABCDEFGH"
20 FOR I = 1 TO 7 STEP 2
30 PRINT MID$(A$,I,I + 1)
40 NEXT I
50 FOR I = 9 TO 1 STEP -1
60 PRINT MID$(A$,I,I);
70 NEXT I
80 END
/*------------------------------------------------------------------*/
Examples,
LET A$ = "ABCDEFGH"
[email protected] 183
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
/*------------------------------------------------------------------*/
SELF TEST on LEN What is printed for each of the statements below, given that A$ =
"ABCD"
EXERCISE S1 Input a string and print the string out in reverse order. Also replace all
spaces by asterisks. eg,
EXERCISE S2 Input a letter of the alphabet, and print out its alphabetical
position. Find the position by comparing it against a string containing A to Z. Make sure
that the input character is alphabetic, and continue requesting until it is. Continue the
program until a null string is entered.
More examples,
PRINT INSTR(A$,"AN") !default start is 1
/*------------------------------------------------------------------*/
SELF TEST on INSTR$ What is the output from this program?
[email protected] 184
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
60 PRINT B$
70 END
/*------------------------------------------------------------------*/
THE LAST MAN IN THE WORLD MANAGED TO MEET THE LAST WOMAN
IN
THE WORLD
input two words. For every occurrence of the first word replace it with the second word.
If no match is found for the first word, print a warning, otherwise print the changed
sentence. Repeat until the first word is a null string.
[email protected] 185
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
Example,
THE LAST DOG IN THE WORLD MANAGED TO MEET THE LAST WOMAN IN
THE
WORLD.
First Word? MAN
Change to? DOG
Warning! The word 'MAN' was not found.
FILE HANDLING
RECORD 1,
NAME :
ADDRESS :
PHONE.NUMBER:
FIELDS Each of the above items that make up a record is called a field. Each field is
usually designated as consisting of so many digits or characters.
TYPES OF FILES There are TWO BASIC types of files, SEQUENTIAL and DIRECT
{ also known as Random Access }.
SEQUENTIAL FILES These files consist of a number of records. Normally, the records
are sorted into some logical order, usually by one of the fields. The general format of a
sequential file is,
[Name][Address][Phone#][Name][Address][Phone#][Name][Address][Phone#]
! ....Record 1 .... !! .... Record 2 ... !! .... Record n ... !
Because each field may have a different length, sequential files are normally appended to
( information is added at the end of the file). Individual records are not usually updated
or altered. In practice, a MASTER file holds all the records. When deletions, etc are
[email protected] 186
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
required, the master file is loaded by the program. The records are then UPDATED,
SORTED, and rewritten to a new UPDATE file. This update file then becomes a new
master file.
In order to find out particular details of a customer, each record must be processed until
the correct record is found. This searching is done using one of the fields, Example.. To
find out the details of a client named 'Waldorf', then the following might be done,
READ RECORD
WHILE NAME <> WALDORF
READ RECORD
WEND
Each record will be read until the record containing the details of a customer named
Waldorf is found. The details of that record can then be processed by the program ( ie,
printed out etc). When data is written to a sequential file, it is added to the place after
where the last data was written. This makes it very difficult for the user to update,
because the data is stored serially, ie field after field without any gaps.
DIRECT FILES Direct files are similar to sequential files, but every record also has a
record number. Similar fields of each record normally have the same length. The typical
format of a direct file is,
[RC1][Name][Address][Phone#][......][RCn][Name][Address][Phone#]
! ..... Record 1 ..... !! !! .... Record n .... !
Because each record has a number, details of a particular record can be read without
first processing all the previous records. Example, if record number 10 needs to be read,
then the BASIC command,
GET #1, 10
will achieve this (whereas in the sequential case, records 1 to 9 would have had to be
read first). Records in direct files can be updated, deleted etc easily. Each record, when
written to the file, usually occupies 256 bytes. This translates directly into a small portion
of user space ( called a sector ) on magnetic media (ie, a hard disk unit). When the user
updates a record as part of a direct file, the sector is rewritten. However, in a sequential
file, each sector may hold more than one record, or parts of a record, so the remaining
records in that sector are erased when the updated record is written back to the disk.
PREPARING A FILE READY FOR USE A certain amount of memory space must be
allocated to hold the information passed between the file and the program. The memory
space is called a BUFFER. To prepare a file ready for reading or writing use,
[email protected] 187
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
where Buffer_number is the number of the buffer that you have allocated for the file to
use (Use numbers from 1 to 8), and ACCESS_MODE is INPUT, OUTPUT, APPEND
(for sequential files) or RANDOM (for direct files. The default record size is 128 bytes)
Using arrays, the above information can be stored effeciently, or you can use data
statements. The program can be written as follows,
WRITE #1, Variable command writes the information through the buffer to the file.
Once all data has been written, then it is necessary to inform the system that the buffer
can be closed (ie, it is no longer needed). This is done by,
1080 CLOSE #1
READING DATA FROM A SEQUENTIAL FILE The command to read data from a
file is,
[email protected] 188
Microsoft Windows Visual Basic 6.0
College of Computer Studies
Computer Communication Development Institute-CALABANGA
HANDLING THE END OF A FILE (EOF) There are times when the number of
records associated with a file may not be known. The EOF (end of file ) command is
useful here.
Example,
EXERCISE F1 Implement a BASIC program which allows the storing and recalling of
a group of student marks. The program is to output the highest and lowest marks, as well
as the mean. Use an array to store the names and marks. Using an output file, sort the
student names, marks into ascending order, so that the student with the highest mark
will be written first. The details are,
- Write a program which inputs the file, sorts it descending order, then writes the sorted
information to a new output file.