SlideShare a Scribd company logo
1 of 144
Page 2 of 144 Paul Bolton 2012
Table of Contents
Part 1 - The Basics ...........................................................7
Introduction: Three Steps in Developing a Windows Application ............... 7
Exercise 1.1 - Changing the text in a label control .................................................9
Designing the Form .......................................................................................12
Coding .......................................................................................................13
Running the Program ....................................................................................14
Saving the Program ......................................................................................14
More on the VB Integrated Development Environment (IDE)................. 14
Menu Bar ...................................................................................................14
Toolbox......................................................................................................16
Solution Explorer Window ...............................................................................17
Standard naming conventions for controls ...........................................................19
The Visual Basic 2010 IDE – In depth.............................................. 21
Structure of a Visual Basic Windows Application..................................................22
Part 2 - Moving on from the Basics....................................23
Consolidation exercises introducing Visual Basic ................................... 23
Exercise 2.1 ...............................................................................................23
Exercise 2.2 ...............................................................................................24
Exercise 2.3 ...............................................................................................24
Exercise 2.4 ...............................................................................................25
Part 3 – Arithmetic & Variables.........................................26
Arithmetic Introductory Exercise 3.1............................................... 26
Introduction to data types ............................................................................26
Task 1 ....................................................................................................26
Task 2 ................................................................................................... 27
Task 3 ...................................................................................................28
Observations ............................................................................................28
Arithmetic & Variables: Underpinning Knowledge ................................ 29
Data Types ................................................................................................29
Arithmetic Exercise 3.2 Declaring variables & type casting.....................................30
Page 3 of 144 Paul Bolton 2012
Task 1 ....................................................................................................30
Task 2 ...................................................................................................33
Task 3 ...................................................................................................33
Task 4 ...................................................................................................34
Arithmetic, Data-Types & Variables ................................................ 35
Converting data before storing it into variables (known as data “ Type Casting”) ........35
Part 4 - More on Arithmetic & Variables.............................36
Arithmetic Exercise 4.1................................................................ 36
Introducing the scrollbar control ......................................................................36
Scrollbar Setting scrollbar properties ............................................... 38
(1) Setting Max and Min properties ................................................................40
(2) Setting SmallCange and LargeChange properties.............................................40
(3) Setting Value property ............................................................................41
Arithmetic Exercise 4.2 – Wallpaper Estimator...................................................43
Data types, arithmetical operators & variables .................................................43
Part 5 - Making selections using If..Then..Else .................48
Program Control – making selections using “If..Then..Else”................... 48
Tax Calculator Program - Scenario ....................................................................51
Part (a) ..................................................................................................51
Part (b).................................................................................................52
Part (c) .................................................................................................52
If…Then…Else - Exercise 5.1 - Tax Calculator......................................................53
If…Then…Else - Exercise 5.2 Tax Calculator Enhancements .....................................58
(a) Using the TabIndex property ..................................................................58
(b) Providing a “Clear” button and improving navigation ....................................58
(c) Protecting data and improving navigation...................................................59
If…Then…Else – Exercise 5.3 Tax Calculator – adding a password form .....................60
Task 1 ....................................................................................................60
Task 2 ....................................................................................................61
Part 6 - More on making selections using If..Then..Else ...........64
Page 4 of 144 Paul Bolton 2012
Sports Club Membership Fees Program - Scenario .............................. 64
Part (a) – creation of basic program ...............................................................64
Part (b) enhancing basic program to provide a password protection form .................64
Part (c) enhancing basic program to provide a printed receipt ...............................64
Part (d) enhancing basic program to work without a mouse ..................................65
If..Then..Else – Exercise 6.1 Using multiple criteria to make selections .....................65
If..Then..Else – Exercise 6.1 SOLUTION ............................................................66
Part 7 Creating menus using the MenuStrip Control ............... 67
MenuStrip Control.......................................................................67
Exercise 7.1 adding a menu to the Tax Calculator ................................................ 67
Part 8 Making selections using Select Case ........................ 70
Select Case................................................................................70
Exercise 8.1 Demonstration of advantage of Select Case construction........................ 70
Sports Club Membership Fees Program - Revisit of scenario: converting
If..Then..Else to Select Case............................................................ 71
Select Case – Exercise 8.2 Membership fees program revisited ................................71
Select Case - Further theory ......................................................................... 74
Select Case Demonstration of advantage of If..Then..Else construction
over Select Case construction .....................................................76
Select Case – Exercise 8.1 SOLUTION ............................................................... 77
Part 9 - Iterations (loops) using For..Next........................... 78
For…Next loops - underpinning knowledge..........................................78
Background................................................................................................. 78
Example .................................................................................................... 78
For..Next Loops - Exercise 9.1 Beep exercise ....................................................80
For.. Next Loops - Underpinning knowledge (continued) ...................... 82
Counting in steps ........................................................................................82
Counting backwards ......................................................................................82
For.. Next loops - Exercise 9.2 - Mobile phone credits exercise ..............................84
Extended Task ............................................................................................84
For… Next Loops - Quiz .............................................................................86
For… Next Loops - Quiz (Answers) ...............................................................88
Page 5 of 144 Paul Bolton 2012
Coding solution to Exercise 9.2 For... Next loops - Mobile phone credits exercise
SOLUTION.................................................................................................89
Part 10 - Iterations (loops) using Do..Loops .........................90
Conditional loops ........................................................................ 90
Exercise 10.1 “Do…” loops introductory exercise ..................................................90
Conditional loops continued ........................................................... 93
Exercise 10.2 “Do…” loops exercise: Moving a picture ..........................................93
Task 1 ....................................................................................................93
Task 2 ...................................................................................................94
Task 3 ...................................................................................................94
Part 11 - Debugging, Testing & Error Handling .......................95
Debugging ................................................................................. 95
Exercise 11.1 Sales Department Wage Calculator ..................................................95
Debugging – Exercise 11.1: Sales Department Wage Calculator code ........................... 97
How to write testing documentation .............................................. 99
Design-time errors .......................................................................................99
Run-time errors..........................................................................................99
How to write testing documentation (continued) ............................... 101
Sample Test Plan .......................................................................................103
How to write an Error Report ..................................................... 105
Error Report (action taken to correct errors)................................................... 107
Error Handling .......................................................................... 108
Exercise 11.2 Tax Calculator program revisited ...................................................108
Task 1 ...................................................................................................108
Task 2: Error Handling ............................................................................... 111
Task 2 (continued) – Further study ..............................................................113
Task 3: Exception Handling..........................................................................114
Task 3 (continued) – Further study ..............................................................116
Part 12 - File Handling: Using Sequential Data Files (Text Files)117
File handling.............................................................................. 117
Exercise 12.1: Storing student marks in a Data File .............................................117
Page 6 of 144 Paul Bolton 2012
Task 1 – writing one record .........................................................................117
Task 2 – reading one record ........................................................................118
Task 3 – writing multiple records .................................................................118
Task 4 – reading multiple records ................................................................120
Part 13 Dialog Controls ................................................... 121
Dialog Controls .......................................................................... 121
Exercise 13.1: Adding the Color Dialog control to a program ..................................121
ColorDialog Customisation ...........................................................................122
Exercise 13.2: Adding Open / Save File Dialogs to the “Student Marks” program ......124
(1) Customising the dialog box display .............................................................126
(a) Setting the default filename .................................................................126
(b) Filtering the list of file types................................................................128
(c) Setting the default file location (folder) ..................................................128
(d) Setting the title................................................................................129
(2) Dealing with errors ...............................................................................129
(a) Errors when clicking the “Cancel” button .................................................129
Exercise 13.3: Adding Save File Dialog to the “Student Marks” program .................132
Code for the SaveFile dialog control:.............................................................134
Additional customisation ............................................................................134
Part 14 - Listbox & Combobox controls...............................136
List & Combo Box ..................................................................... 136
Exercise 14.1 Flight Seat Planner....................................................................136
List & Combo Box ..................................................................... 139
Exercise 14.2: Flight Seat Planner enhancement .................................................139
Task 1 ...................................................................................................139
Task 2 ..................................................................................................139
Task 3 ..................................................................................................139
Part 15 Multiple Event Handlers........................................ 141
Multiple Event Handlers............................................................... 141
Exercise 15.1: Colour Picker ............................................................................141
Page 7 of 144 Paul Bolton 2012
Part 1 - The Basics
Introduction: Three Steps in Developing a Windows Application
The Visual Basic Integrated Development Environment (IDE)
Makes building an application a straightforward process. There are three
primary steps involved in building a Visual Basic application:
1. We draw the user interface by placing
controls on a Windows form
2. We assign properties to controls
3. We write code for control events (and perhaps write other procedures)
Example
Example
Page 8 of 144 Paul Bolton 2012
These same steps are followed whether you are building a very simple
application or one involving many controls and many lines of code.
The event-driven nature of Visual Basic applications allows you to build your
application in stages and test it at each stage. You can build one procedure,
or part of a procedure, at a time and try it until it works as desired. This
minimises errors.
Example
Page 9 of 144 Paul Bolton 2012
Exercise 1.1 - Changing the text in a label control
- Go to the Start Menu on the computer
- Find Microsoft Visual Studio 2010
- Select Microsoft Visual Studio 2010 from the sub menu
Once Visual Basic has opened select File / New Project from the menu
Change the name of your
application to
LabelMessageYourName.
So if your name is John Smith
you would name your
application
LabelMessageJohnSmith
Visual Studio will now load. This may take a
few minutes, BE PATIENT. If you are asked
which settings you would prefer, select
Microsoft Visual Basic.
Leave the template type
selected as Windows Forms
Application.
Page 10 of 144 Paul Bolton 2012
(no spaces between the words).
Click OK
Page 11 of 144 Paul Bolton 2012
You should now see the Visual Basic design environment appear similar to the screen
shown below.
Take a few moments to familiarise yourself with the various features before
continuing the exercise. If your screen does not look like the one shown below, tell
your teacher.
Tip: to make the windows stop disappearing, click the drawing pin symbol at
the top of each window then becomes
Click these two icons to alternate
between the Form1 Design window
and the Code window
Solution Explorer windowControls Toolbox Menu
Properties window
Error List window
Form Design
window
Exercise 1.1 (continued)
Page 12 of 144 Paul Bolton 2012
The Form Designer Window is, as the name implies, where you design your
visual interface. You can add controls from the Toolbox, on the left, onto
your form.
The title bar area shows you the name of your project and the name of the
form currently displayed. Also shown in brackets is one of three words:
Design, Run or Break. This shows the mode Visual Basic is operating in.
Visual Basic operates in three modes.
 Design mode - used to build application
 Run mode - used to run the application
 Break mode - application halted and debugger is available
We focus here on the design mode. You should, however, always be aware of
what mode you are working in.
Now continue with Exercise 1.
The finished program can be seen here:
Designing the Form
1. Make sure Form 1 is selected and in the properties window change the Text
property of the form to Change a message.
lblMessage
This button
has been
clicked to
display the
message above
btnGoodMessage
btnBadMessage
How the program will work: When a button is clicked the message “I LIKE Visual Basic”
appears. When a second button is clicked the message changes to “I HATE Visual Basic”
Exercise 1.1 (continued)
I LIKE Visual Basic
Page 13 of 144 Paul Bolton 2012
2. Click on the Label control in the toolbox, and then with the mouse draw a
rectangle in the upper part of the form (by holding down the left mouse button
and dragging the mouse).
3. Find the label’s Name property in the Properties window and change it from
Label1 to lblMessage, using the prefix ‘lbl’. Note that this prefix begins with the
letter ‘l’for lion and not the number 1.(one)
4. Set the label’s Text property to blank by deleting the default value “Label1".
5. The default value for the label’s BorderStyle property is None, meaning that it
has no border will be shown when the program runs. To get the sunken border
effect in the illustration, change this to Fixed3D.
6. Set the label’s Font property to 14 Bold.
7. Set autosize to false
8. Set size width to 200 and height to 50
9. Drag a button from the Toolbox and draw a rectangle at the bottom left of the
form. Set its Text property to Good Message. Change its Name property to
btnGoodMessage. Now place a second button at the bottom right of the form.
Set its Text property to Bad Message. Change its Name property to
btnBadMessage.
Coding
10.Double-click on the Good Message button and you’ll see the code template for its
Click() event as shown below.
The words after the brackets, Handles btnGoodMessage.Click, shows that the code
you are about to write will be executed if the btnGoodMessage is clicked when
the program is running. The code template plus any code that is written inside
the template, is known as an event procedure.
11. Type the line of code below to set the Text property of the label to the
message you wish to display in the label.
Page 14 of 144 Paul Bolton 2012
12. Return to the form either by clicking the Form1.vb [Design] Page tab or the
View Designer button in the Solution Explorer’s small toolbar (you will need to
hover the mouse over the button to see its name.
13. Double-click the Bad Message button on the form. Type in a line of code similar
to that in step 10 to display the “I do not like Visual Basic” message when the
Bad Message button is clicked.
Running the Program
14. Click the Start button on the toolbar or select Debug/Start from the menu.
Click on each of the two buttons to check that the message changes. Close the
program by clicking the red “X” in the top-right corner of the program window
(i.e. the “form” you created)
Saving the Program
15. Click the icon on the menu. In the Save Project window you should see
LabelMessage automatically displayed as the application name. Don’t alter any of
the entries. Just click the Save button.
More on the VB Integrated Development Environment (IDE)
Menu Bar
Under the title bar is the Menu. This menu is dynamic, changing as you try to do different
things in Visual Basic .NET. When you start working on a project, it should look like this:
You will become familiar with each menu topic as you work through the course. Briefly, they
are:
File Use to open/close projects and files. Use to exit Visual Basic .NET
Edit Used when writing code to do the usual editing tasks of cutting, pasting, copying and
deleting text
View Provides access to most of the windows in the Integrated Development Environment
(IDE)
Project Allows adding files and objects to your application
Build Allows you to compile and run your completed application (go to Run mode)
Debug Comes in handy to help track down errors in your code (works when Visual Basic .NET
is in Break mode)
Background information
Page 15 of 144 Paul Bolton 2012
Team Ability to work in a Team Foundation Server
Data Used when building database applications
Format Useful for manipulating controls placed on your forms
Tools Allows custom configuration of the IDE. Be particularly aware of the Options choice
under this menu item. This choice allows you to modify the IDE to meet any personal
requirements.
Test Used for testing and debugging your applications
Window Lets you change the layout of windows in the IDE
Help Perhaps, the most important item in the Menu. Provides access to the
Visual Basic on-line documentation via help contents, index or search.
The View menu also allows you to choose from a myriad of toolbars available in the Visual
Basic .NET IDE. Toolbars provide quick access to many features. The Standard (default)
toolbar appears below the Menu:
New project
Open file
Save all
Undo, Re-do
Move backward / forward
Build configuration
View Solution Explorer Window
View Properties Window
View Object Browser
View Toolbox
Team Explorer Window
Start Page
Extensions
Command Window
If you forget what a
toolbar button does,
hover your mouse cursor
over the button until a
descriptive tool tip
appears.
We will discuss most of
these toolbar functions in
the remainder of the IDE
information.
Page 16 of 144 Paul Bolton 2012
Toolbox
The Toolbox is the selection menu for controls used in your application. It is active when a
form is shown in the design window.
The tools you will use
most are found under
the Windows Forms tab.
Use the scroll arrows to
scroll up and down the
full list of controls.
Many of these tools will
look familiar to you.
They are used in a wide
variety of Windows
applications you have
used (the Visual Basic
IDE even uses them!)
We will soon look at how
to move a control from
the toolbox to a form.
Background information (continued)
Page 17 of 144 Paul Bolton 2012
Solution Explorer Window
Two other windows (not illustrated) which are useful when running an application are the
Task List Window and Output Window. The task list window highlights any errors
encountered while trying to run an application.
The window will direct you to the line(s) of code with identified errors. The output window
outlines the steps followed as an application is compiled.
Background information (continued)
The Solution Explorer Window displays a
list of all forms, modules and other files
making up your application. To view a
form in this window, simply double-click
the file name. Or, highlight the file
and press <Shift>-<F7>.
Or, you can obtain a view of the Form
or Code windows (window containing the
actual Basic coding) from the Project
window, using the toolbar near the top
of the window. As we mentioned,
there are many ways to do things using
the Visual Basic IDE.
The Properties Window is used to establish design
mode (initial) property values for objects
(controls). The drop-down box at the top of the
window lists all objects in the current form.
Two views are available: Alphabetic and Categorized
(selection is made using menu bar under this box
are the available properties for the active
(currently selected) object.
Help with any property can be obtained by
highlighting the property of interest and pressing
<F1>.
Page 18 of 144 Paul Bolton 2012
Page 19 of 144 Paul Bolton 2012
Standard naming conventions for controls
List continued on next page
lbl...
btn...
txt...
mnu...
chk...
rad...
grp...
pic...
pnl...
dgd...
lst...
cbo...
hsb...
vsb...
tmr...
lblDisplay
btnEnter
txtInput
mnuEditPaste
chkBold
radYellow
grpFontSize
picLogo
pnlFontStyle
dgdEmployees
lstAge
cboFavoriteFood
hsbWidth
vsbHeight
tmrAnimate
Type of control Prefix Example
We name controls using the first 3 letters (the prefix) written in lowercase to represent what
type of control it is. A list of prefixes is shown below. The rest of the name can be any
meaningful word or combination of words representing what the control does. There must be
no gaps in the name. We therefore start each word after the prefix with a capital letter.
This is known as “camel-case”, because the middle of the name has taller (capital) letters, like
the humps of a camel.
For more information on Visual Basic naming conventions, go to:
http://www.akadia.com/services/naming_conventions.html
and scroll to the bottom of the page and find the heading: “12) Visual Control Type
Notation”
Background information (continued)
Page 20 of 144 Paul Bolton 2012
We usually give
dialogue controls these
standard names rather
than use different
names for different
applications – as we
do with the other
controls. This is
because there is
usually only one dialog
control of each type
on any of our forms.
dlgOpenFile
dlgSaveFile
dlgFont
dlgColor
dlgPrint
dlgPrintPreview
Type of control Prefix AND Example (see explanation below)
Background information (continued)
Page 21 of 144 Paul Bolton 2012
The Visual Basic 2010 IDE – In depth
Visual Basic is an integrated development environment within the Visual Studio. Net
Framework. The visual environment is used to design, develop, debug and deploy Windows
Forms and Web Forms applications. These applications can also be used to integrate database
applications. The major advantage of this new environment is that multi-language applications
can be used over the Internet, thus creating, in theory, a truly open application platform.
In summary the visual studio has the following features:
1. Windows Forms Designer. A graphical design surface for creating GUI. You can drag &
drop controls onto forms.
2. Tools for Windows Forms. A Windows Forms Designer, A Windows Application Template
(e.g. windows or database application etc.), project references and generated starter
code for the applications.
3. Tools for Web Forms. A Web Forms Designer, an ASP.Net Web Application template,
project references and generated starter code.
4. Tools for XML (eXtendible Markup Language) Web Services. A generalised web language
can be generated from your .net application solution file.
5. Multiple language Support. A range of language such as C# and VB.net can used in the
same application or solution. The environment now has Object-Oriented Programming
(OOP) capabilities.
6. Data Access. Components for creating applications that share data, visual database
applications for accessing data using the ADO.NET classes.
7. Error handling. Has a range of debugging tools, classes and objects to find and fix
errors within your application.
8. Wizards. Help you create common and complex tasks, by choosing options, configuring
settings and customising projects.
Background information (continued)
Page 22 of 144 Paul Bolton 2012
Structure of a Visual Basic Windows Application
We want to get started building our first Visual Basic Windows application. But, first we
need to define some of the terminology we will be using. In Visual Basic .NET, a Windows
application is defined as a solution.
A solution is made up of one or more projects. Projects are groups of forms and code that
make up some application. In most of our work in this course, our applications (solutions)
will be made up of a single project. Because of this, we will usually use the terms
application, solution and project synonymously.
Thus an Application (Project) is made up of:
 Forms - Windows that you create for user interface
 Controls - Graphical features drawn on forms to allow user interaction (text boxes,
labels, scroll bars, buttons, etc.) (Forms and Controls are objects.)
 Properties - Every characteristic of a form or control is specified by a property.
Example properties include names, captions, size, colour, position, and contents. Visual
Background information (continued)
Page 23 of 144 Paul Bolton 2012
Basic .NET applies default properties. You can change properties when designing the
application or even when an application is executing.
 Methods - Built-in procedures that can be invoked to impart some action to a
particular object.
 Event Procedures - Code related to some object or control. This is the code that is
executed when a certain event occurs. In our applications, this code will be written in
the BASIC language
 General Procedures - Code not related to objects. This code must be invoked or called
in the application.
 Modules - Collection of general procedures, variable declarations, and constant
definitions used by an application.
Part 2 - Moving on from the Basics
Consolidation exercises introducing Visual Basic
Exercise 2.1
 Start a new project.
 Create a form with two labels.
Exercises 2.1 to 2.4
Visual Basic uses a very specific directory structure for
saving all of the components for a particular application.
When you start a new project (solution), you will be
asked for a Name and Location (folder / directory).
A folder named Name will be established in the selected
Location. That folder will be used to store all solution
files, project files, form and module files (vb extension)
and other files needed by the project.
Two subfolders will be established within the Name
folder: bin and obj. The bin folder contains your
compiled application (the actual executable code or exe
file). Later, you will see that this folder is considered
the ‘application path’ when ancillary data, graphics and
sound files are needed by an application. The obj folder
contains files used for debugging your application as it is
being developed.
Page 24 of 144 Paul Bolton 2012
 When the program runs display your name in label 1 and your address in label 2
by using the Form_Load() event. (Double-click on the grey area of the form at
design time display the code window for this event.)
Exercise 2.2
 Start a new project.
 Place a button on a form. When it is clicked the title bar of the form should
display Welcome to Visual Basic .NET.
Exercise 2.3
 Start a new project.
Public ClassForm1
Private SubForm1_Load(...) HandlesMyBase.Load
lblName.Text = "MyName"
lblAddress.Text = "MyAddress"
End Sub
End Class
Public ClassForm1
Private SubbtnWelcome_Click(sender As System.Object, e As
System.EventArgs) Handles btnWelcome.Click
Me.Text = "Welcome to Visual Basic .NET"
End Sub
End Class
Page 25 of 144 Paul Bolton 2012
 Place two buttons on a form and set their Text properties to Show and Hide
respectively using the Properties Window.
 Place a label on the form and set its Visible property to False (which means it
will be invisible when the program first runs).
 Clicking the Show button should make the label visible and display the message
Hello inside it. Clicking the Hide button should remove the label and its message.
(Note: When you set the Visible property in code you do not need quotation
marks around the True or False.)
Exercise 2.4
 Start a new project.
 Write a program with a label and two buttons.Label width:200 height: 100
 Clicking the ForeColour button displays the message shown in a blue colour.
Clicking the BackColour button displays a different message and colours the rest of
the label yellow. Note that the message is centred within the label. Use the
label’s ForeColor and BackColor properties. To set these properties write
Color.Blue or Color.Yellow to the right of the assignment statement ( = ).
Public ClassForm1
Private SubbtnShow_Click(sender As System.Object, e As System.EventArgs)
HandlesbtnShow.Click
lblHello.Visible = True
lblHello.Text = "Hello"
End Sub
Private SubbtnHide_Click(sender As System.Object, e As System.EventArgs)
HandlesbtnHide.Click
lblHello.Visible = False
lblHello.Text = "Hello"
End Sub
End Class
Public ClassForm1
Private SubbtnForeColour_Click(sender As System.Object, e As System.EventArgs) Handles
btnForeColour.Click
lblColour.Text = "MyForeColour propertyis set to blue"
lblColour.ForeColor = Color.Blue
End Sub
Private SubbtnBackColour_Click(sender As System.Object, e As System.EventArgs)Handles
btnBackColour.Click
lblColour.Text = "MyBackColour propertyis set to yellow"
lblColour.BackColor = Color.Yellow
End Sub
End Class
Page 26 of 144 Paul Bolton 2012
Part 3 – Arithmetic & Variables
Arithmetic Introductory Exercise 3.1
Introduction to data types
We are going to look at how we can use the properties of controls to transfer
information (data) from one control to another. The program we are about to
create will enable us to:
(1)assign a new BackColor property value (yellow) to a textbox on the left of
the form by copying the existing BackColor property value from a textbox on
the right
(2) assign a new Text property value to a textbox on the left of the form
by copying the existing Text property value from a textbox on the right
(3) assign a new Text property value to a textbox on the left of the form
by copying the existing Text property values from two textboxes on the right.
We will see if we can get two numbers to add up using this technique (a
simple maths calculation).
Task 1
Open a new Windows Application project and create a form like the one illustrated:
txtCopiedColour
txtCopiedText
txtResult
btnCopyColour btnCopyText
txtOriginalColour
txtOriginalText
Exercise 3.1
Page 27 of 144 Paul Bolton 2012
At design-time, set the BackColor property of txtOriginalColour to yellow (select this
from Custom on the BackColor property list).
Double-click on the Copy Colour button. The code window should open revealing the
template code for this button procedure ready for us to write code into. Write the
following code shown in bold:
Run your program, click the Copy Colour button an see if the yellow colour appears
in the first textbox.
If so, we have successfully assigned a new value to the BackColor property of the
textbox on the left of the form by copying the existing BackColor property value
from a textbox on the right.
Task 2
Now see if you can complete the line of code for the next button, as shown below:
Run your program again, write your name in the txtOriginalText textbox on the
right, click the Copy Text button and see if your name appears in the txtCopiedText
textbox on the left.
Public ClassForm1
Private SubbtnCopyColour_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs)HandlesbtnCopyColour.Click
txtCopiedColour.BackColor = txtOriginalColour.BackColor
End Sub
End Class
btnAdd txtFirstNumber txtSecondNumber
Private SubbtnCopyText_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs)HandlesbtnCopyText.Click
txtCopiedText.Text = .
End Sub
Exercise 3.1
Page 28 of 144 Paul Bolton 2012
Task 3
Repeat the process with the final button (“Add”). See if you can complete the line
of code below:
Run your program again, write your 2 whole numbers in the txtFirstNumber and
txtSecondNumber textboxes on the right (e.g. 2 + 2), click the Add button and see
if the correct answer appears in the txtResult textbox on the left.
Observations
Try to answer the following questions:
 what result did you get in txtResult?
 how do you think VB is processing the data you have input?
 what data type do you think VB has assumed the number “2” is?
Now look at the handouts / tutorials on data types and converting data types
(“type-casting”) and see if you can work out what must be added to your code to
cure the problem we are encountering.
Private SubbtnAdd_Click(ByValsender As System.Object, _
ByVal e As System.EventArgs)HandlesbtnAdd.Click
txtResult.Text = .
End Sub
Page 29 of 144 Paul Bolton 2012
Arithmetic & Variables: Underpinning Knowledge
Data Types
Data Type Usage
Size
(1 byte = 8 bits)
To store numeric data
Short (or Int16)
(“Shortinteger”)
Wholenumbersonly
Can hold whole numbers(positiveor negative) between
approx +32,000 to -32,000
2 bytes
(i.e. 16 bits)
Integer (or Int32) Can hold whole numbers(positiveor negative) between
approx +2 billion to -2 billion (i.e. +2 followed by 9 zeros
or -2 followed by 9 zeros)
4 bytes
(i.e. 32 bits)
Long(or Int64)
(“Long integer”).
Can hold whole numbers(positiveor negative) between
approx +9 (followed by18 zeros) to -9 (followed by18
zeros)
8 bytes
(i.e. 64 bits)
Single
(“Single-precisionfloating-
point”)
WholeORdecimalnumbers
Can hold whole numbersORnumberscontaininga
decimalpoint (positiveor negative) Therangeof values
which can bestored forpositivenumbersis
approximately:+3 (followed by38 zeros) for verylarge
values, to +0.0 (followed by45 zerosand then 1) for very
small values. For negativenumbers,therangeis
approximately:-3 (followed by38 zeros) for verylarge
values, to -0.0 (followed by45 zerosand then 1) for very
small values.
4 bytes
Double
(“Double-precision floating-
point”)
Can hold whole numbersORnumberscontaininga
decimalpoint (positiveor negative) Therangeof values
which can bestored forpositivenumbersis
approximately:+1 (followed by308 zeros) for verylarge
values, to +0.0 (followed by324 zerosand then 4) for
verysmallvalues. For negativenumbers,therangeis
approximately:-1 (followed by308 zeros) for verylarge
values, to -0.0 (followed by324 zerosand then 4) for
verysmallvalues.
8 bytes
Decimal Can hold numberscontainingadecimalpoint (positive
or negative) between approx
+7 (followed by28 zeros) to -7 (followed by28 zeros)
16 bytes
To store other data
Boolean
Otherdata
Used to hold True or False 2 bytes
Date Can hold datesfromJanuary1,0001to December 31,
9999,and timefrom00:00:00to 23:59:59
8 bytes
String
Used to hold characters(e.g.all theletters & symbolson
the keyboard and numbers 0-9,butNOTif thenumbers
are to be used in calculations).
Variable size
Object
An object variable holds a referenceto an object,notthe
objectitself. Thereforethe variableonlyneeds a small
amountof memory. In theory,any data typecan be
stored in an objectvariable.
4 bytes
Background information
Page 30 of 144 Paul Bolton 2012
Arithmetic Exercise 3.2 Declaring variables & type casting
Task 1
We are going to
create a simple
calculator. Open a
new Windows
Application project
and create a form
like the one
illustrated:
Give the buttons suitable names (e.g. btnAdd, btnSubtract etc.). Give the
textboxes the names txtFirstNumber, txtSecondNumber and txtResult respectively.
Double-click on the Add button. The code window should open revealing the
template code for this button procedure ready for us to write code into:
Move the cursor and insert it between the line: Public Class Form1 and the line:
Private Sub btnAdd_Click(…) and then write the following code:
Public ClassForm1
Private SubbtnAdd_Click(ByValsender As System.Object, _
ByVal e As System.EventArgs)HandlesbtnAdd.Click
|
End Sub
End Class
Cursor
Public ClassForm1
'declare variables
Dim intFirstNumber As Integer
Dim intSecondNumber As Integer
Dim intResult As Integer
Private SubbtnAdd_Click(ByValsender As System.Object, _
ByVal e As System.EventArgs)HandlesbtnAdd.Click
End Sub
End Class
Cursor
Exercise 3.2
Page 31 of 144 Paul Bolton 2012
Page 32 of 144 Paul Bolton 2012
You will notice that the above process is in 3 main steps:
(1) Input (where the numbers typed by the user are stored into variables)
(2) Calculation (where we use the variables to do the arithmetic)
(3) Output (where we display the result into a text box)
This is a sequence we will use again and again in our programming projects.
We have declared three variables of Integer type – intFirstNumber, intSecondNumber
and intResult. We want the program to accept two whole numbers (integers) in
txtFirstNumber and txtSecondNumber and then perform the calculations indicated by
the buttons.
In order to do this we need to:
(1) store the two values which the user has typed into txtFirstNumber and
txtSecondNumber into our variables intFirstNumber and intSecondNumber.
(2) do the arithmetic and then store the result into the variable intResult.
(3) display the result. For this we need to change the .Text property of
txtResult to the value held in intResult.
Add the code below to the _Click() event procedure of btnAdd:
HINT
Public ClassForm1
'declare variables
Dim intFirstNumber As Integer
Dim intSecondNumber As Integer
Dim intResult As Integer
Private SubbtnAdd_Click(ByValsender As System.Object, _
ByVal e As System.EventArgs)HandlesbtnAdd.Click
'INPUT
'load contents of 1st textbox into 1st variable
intFirstNumber = txtFirstNumber.Text
'load contents of 2nd textbox into 2nd variable
intSecondNumber = txtSecondNumber.Text
'CALCULATION
'add 2 variables and load result into 3rd variable
intResult = intFirstNumber + intSecondNumber
'OUTPUT
'display contents of 3rd variable in 3rd text box
txtResult.Text = intResult
End Sub
End Class
Exercise 3.2
Page 33 of 144 Paul Bolton 2012
Run you program, enter two numbers and click the add button. See if the correct
answer appears in txtResult.
Task 2
We have relied upon Visual Basic automatically converting data into the appropriate
data types for us. For example, it took the text from the first textbox (a String
data-type) and converted it into an Integer before adding it to the second number.
This is data-type conversion is known as type casting.
We are now going to do this with functions in our code.
Add the following statement to the top of your code:
You will immediately see parts of the code underlined in blue and errors appear in
the Error List Window.
To solve this problem we need to convert the data-type of the numbers from String
to Integer in the first button (btnAdd) by including the conversion function CInt().
Amend you code as follows:
Run your program, enter two numbers and click the add button. See if the correct
answer appears in txtResult.
Task 3
So far we have used the + operator to add the two numbers together. The other
operators that we can use are:
Option Strict On
Public ClassForm1
'declare variables
Dim intFirstNumber As Integer
Dim intSecondNumber As Integer
Dim intResult As Integer
Private SubbtnAdd_Click(ByValsender As System.Object, _
ByVal e As System.EventArgs)HandlesbtnAdd.Click
End Sub
End Class
Private SubbtnAdd_Click(ByValsender As System.Object, _
ByVal e As System.EventArgs)HandlesbtnAdd.Click
'INPUT
'load contents of 1st textbox into1st variable
intFirstNumber = CInt(txtFirstNumber.Text)
'load contents of 2ndtextbox into2ndvariable
intSecondNumber = CInt(txtSecondNumber.Text)
Exercise 3.2
Page 34 of 144 Paul Bolton 2012
+ Add
- Subtract
/ Divide
* Multiply
MOD Modulus
^ Raise to the power of
Now add sections of code to perform the correct arithmetic for each of the buttons
shown in the example.
(Note: we cannot use the % symbol to calculate percentages. Instead we must
divide the first number by the second number and then multiply by 100.)
Task 4
Cint() is a function that converts text, provided it is a numeric, to Integer data
format. There are other function like this. To find out about them read the
Background Information on the next page. (If Online Help is available on your
computer, you can also highlight CInt() and then press the F1 key.)
Test your program with numbers like 350 and 260.You will get overflow.
Now try using Long instead of Integer in your Dim statements. You will need to
change the CInt() functions to CLng()
Try dividing 13 by 2. You won’t get the right answer. Use Single instead of Long
in your Dim Statements. (Again you will have to change the conversion function –
use the help facility to look up what you need to use or read the next page on this
subject.)
Exercise 3.2
Page 35 of 144 Paul Bolton 2012
Arithmetic, Data-Types & Variables
Converting data before storing it into variables (known as data “Type
Casting”)
So far we have looked at how to declare a variable and store data into it. For
example, suppose our user is going to type the number “123” into a text box called
txtFirstNumber. We want to write code which will store this number into a variable
called intFirstNumber and then do a maths calculation with it. To do this we would:
(1)declare the variable:
Dim intFirstNumber As Integer
(2) then store the data into it by writing:
intFirstNumber = txtFirstNumber.Text
But this does not actually convert the string “123” into numbers which our program
can use to do maths with. Remember that because the number is in a text box,
Visual Basic does not automatically recognise that this is a number. It assumes the
number is a series of characters (a “string”) like a telephone number or bank account
number. If we try to get VB to add 1 to this string, we will probably get the
answer 1231 instead of 124. VB will simply put the 1 on the end of 123 like a
putting letter on the end of a word.
Declaring a variable as an Integer type does not convert the data to an integer, it
simply puts a “filter” over the variable so that it refuses to accept anything but an
integer! So if we try to store the decimal number 0.75 into it we will simply get
an error message.
Therefore we need to use a function to convert the data in the text box into the
correct data type before we try to store it into the variable. To do this we use
one of the following data type conversion functions, for example:
Numeric data types:
CShort( ) to convert to Short data type
CInt( ) to convert to Integer data type
CLng( ) to convert to Long data type
CSng( ) to convert to Single data type
CDbl( ) to convert to Double data type
CDec( ) to convert to Decimal data type (used especially for currency data)
Otherdata types:
Background information
Page 36 of 144 Paul Bolton 2012
CBool( ) to convert to Boolean data type (True / False)
CDate( ) to convert to Date / Time data type (e.g. #17/10/06 13:50:02#)
CStr( ) to convert to String data type (e.g. "My name is John")
For example, to convert the string “123” contained in text box txtFirstNumber into
an integer and then store it into our variable, we would write:
intFirstNumber = CInt(txtFirstNumber.Text)
We need to be careful however, because if the data doesn’t exactly match the data
type, VB will do its best to convert it anyway. For example, if we write the above
code and the user writes the string 12.75 into the text box, the integer 13 will be
stored in the variable intFirstNumber. In other words the 0.75 part of the number
will simply be rounded up to the next whole number. (Note: if we actually wanted
to store decimal numbers we would need to declare the data type of our variable as
a single and use the conversion function CSng() instead.)
Part 4 - More on Arithmetic & Variables
Arithmetic Exercise 4.1
Introducing the scrollbar control
Create a form like the one above.
The aim of the program is to allow the user to convert temperatures from Farenheit
into Celsius by moving the scroll bar. The Farenheit temperature values will range
from –60 to +120. (Moving the scroll bar thumb upwards should increase the
temperature values.) Set the initial Text property of txtTempF and txtTempC to
32 and 0 respectively, and the Value of the scroll bar to 32.
txtTempF txtTempC
vsbTemperature
Exercise 4.1
Page 37 of 144 Paul Bolton 2012
(a) From the above information work out what the Min and Max property values of
the scroll bar should be. (Remember that for vertical scroll bars the Min property
always corresponds to the topmost position of the thumb!)
(b) Write code into the scrollbar _Scroll(...) event which will take the Farenheit
value displayed in txtTempF, convert it to Celsius and display it in txtTempC. The
conversion formula is:
Celsius = (Farenheit – 32) x 5
/9
Public ClassForm1
Dim intTempF As Integer 'declare variables
Dim intTempCAs Integer
'----------------------------------------------------------------------------
Private SubvsbTemperature_Scroll(ByVal sender As System.Object, _
ByVal e As System.Windows.Forms.ScrollEventArgs)HandlesvsbTemperature.Scroll
'store value of scrollbar intoF variable
intTempF= vsbTemperature.Value
'convert F value to stringanddisplayinF textbox
txtTempF.Text = CStr(intTempF)
'calculate Cvalue, convert to integer and store inCvariable
intTempC= CInt((intTempF - 32) * 5 / 9)
'convert Cvalue to string anddisplayin Ctextbox
txtTempC.Text = CStr(intTempC)
End Sub
'-------------------------------------------------------
End Class
Scroll bar property settings
required to achieve full
temperature range displayed:
Vertical scroll bar
(vsbTemperature)
Min:120
Max:-60
Small change:1
Large change:10
Value:32
Page 38 of 144 Paul Bolton 2012
Scrollbar Setting scrollbar properties
A scroll bar returns a numeric value depending on the position of the slider or
(“thumb”).
Scroll bars are quite complex because they have 5 main properties to set and 2
events to code in order for them to work properly.
The 5 properties are listed below:
Property Horizontal
ScrollBar
Vertical
ScrollBar
Max the value returned when the slider
is at the right hand end of the
ScrollBar
The value returned when the slider
is at the bottom of the ScrollBar
Min the Value returned when the slider
is at the left hand end of the
ScrollBar
The Value returned when the slider
is at the top of the ScrollBar
Large Change The amount by which the Value property is changed when the user
clicks on the grey area between the slider and either end of the
ScrollBar.
Small Change The amount by which the Value property is changed when the user
clicks on the arrows at either end of the ScrollBar
Value This returns an integer which indicates the position of the slider in
terms of the range set by Max and Min.
slider or “thumb”
clicking here
affects
SmallChange
property
clicking here
affects
SmallChange
property
clicking here
affects
LargeChange
property
Background information
Page 39 of 144 Paul Bolton 2012
Page 40 of 144 Paul Bolton 2012
(1) Setting Max and Min properties
We set Max and Min to suit the application we are using. For example, if we
wanted to use a scroll bar to input the temperature of a pan of water in degrees
Celsius we would set the Min property to 0 and the Max property to 100 to
correspond to the freezing and boiling point of water. When you first draw a scroll
bar on your form the default value of Min is 10 and Max is 100. Note that with
vertical scroll bars, the Min value is always returned when the thumb is at the top.
Therefore it is quite common for the Min value to be set greater than the Max
value when using vertical scroll bars.
(2) Setting SmallCange and LargeChange properties
There are no rules governing what values you should set the SmallChange and
LargeChange properties to. However, by default the SmallChange property is set to 1
when you first draw the scroll bar, and the LargeChange property is set to 10. This
means that if the range of the scrollbar (i.e. the Max value minus the Min value) is
quite large the thumb will move incredibly slowly when the user clicks on the arrows.
Therefore it is very important that you set these properties to values which will give
reasonable travel of the thumb.
As a rough guide, set the LargeChange property to one tenth of the range value, and
set the SmallChange property to one tenth of the LargeChange property.
Note: The ratio of LargeChange property to the range also affects the length of the
thumb. The thumb is lengthened to restrict the distance it travels, as shown in the
diagram below: In this example the Min property is set to 0 and the Max is 100,
meaning that the range is 100. If the LargeChange property is left at the default
value of 10, the thumb remains quite small. However, if the LargeChange property is
increased to 50, the size of the thumb increases to one third the length of the
scroll bar, since it only requires 2 clicks to move the thumb to its maximum value.
(The value is taken from the position of the left edge of the thumb.)
Size of the thumb when LargeChange property is set to 1:Min = 0
Max = 100
Background information
Page 41 of 144 Paul Bolton 2012
Size of the thumb when LargeChange property is set to 50 on the same scroll bar:
(3) Setting Value property
This is the initial value of the scroll bar at run-time, and hence determines the
initial position of the thumb. The Value property must be within the range of the
Max and Min properties. Often the Value property will be the same as the Min
property so as to put the thumb at one end of the scrollbar, but this is not always
the case.
Scrollbars
Summary of features
 The purpose of a scrollbar is to generate numbers
which we can use elsewhere in our program
 We can use these numbers to:
o change the value of properties of other
controls
o perform calculations
 We use the scrollbar’s value property as the source of these numbers
 As the user clicks the scrollbar arrows (or drags the scrollbar slider) the value of
the scrollbar changes
 We control what range of values will be generated by setting the Max and Min
properties of the scrollbar at design time
 We can decide where the position of the slider is when the program first opens
by setting the scrollbar’s value property at design time (but this initial value
must lie somewhere between the Max and Min values)
Min = 0 Max = 100
(position allows for width of
thumb)
Page 42 of 144 Paul Bolton 2012
 We can decide how quickly the value of a scrollbar changes when the user clicks
the scrollbar arrows (or drags the scrollbar slider). We do this by setting the:
o SmallChange and
o LargeChange properties
 (As a guide, set the LargeChange property to 1/10th
the value of the Max
property, and set the SmallChange property to 1/10th
the value of the
LargeChange property)
 when the user clicks the scrollbar arrows or drags the scrollbar slider it fires the
_Scroll(...) event
Page 43 of 144 Paul Bolton 2012
Arithmetic Exercise 4.2 – Wallpaper Estimator
Data types, arithmetical operators & variables
In this exercise we will be revising what we have covered so far on:
 data types
 converting data to different types (known as “type casting”)
 declaring variables of appropriate data types
 arithmetical operator precedence using the common operators:
Your task is to estimate the amount of wallpaper required to cover the wall
illustrated below which has one window.
The wallpaper comes in rolls 0.7 metres wide and 10 metres long.
Cost per roll is £8.00
Your task is to calculate and display:
4.5m
3m
4.5m2.5m
1.5m
Area A Area B
Area C
Area D
0.5m
Order of precedence:
(1)( ) brackets (parentheses)
(2) ^ exponentiation (“power of”)
(3) + - positive & negative signs
(4) * / multiplication & division
(5)  integer division (gives only whole number result of
Exercise 4.2
Page 44 of 144 Paul Bolton 2012
 the number of rolls required
 the total cost of wallpaper
 the relative cost of wasted wallpaper left over from the last full roll (e.g. if
half a roll was left over, we could say that £4.00 worth of wallpaper was
wasted)
Assume the wallpaper pieces can be pasted in any sequence / orientation irrespective
of where the joins occur, and that there is no wastage due to overlap or off-cuts.
In other words, assume the total area of one roll covers exactly the same amount of
area of the wall.
Page 45 of 144 Paul Bolton 2012
(1) Find total area of wall
Here are some tips on how to calculate the total area of the wall. After reading
the tips, try to create one line of code in your program which uses all the
measurements and stores the answer in a variable sngWallArea.
Area A:
height * width
3m * 4.5m = 13.5 square meters
Area B is the same, so multiply the area of A by 2
Area C:
height * width
0.5m * 2.5m = 1.25 square meters
Area D:
We haven’t been told the height but we can work it out by subtracting
the height of the window plus the height of Area C from the height of
the room. Once we have found this we multiply height * width as
usual to find the area of D.
Finally, Total Area = Area A + Area B + Area C + Area D
Here is the start of the code you will need. The figures calculating Areas A & B
have been written for you already. See if you can finish off the line. Be careful to
remember the rules about operator precedence and use parentheses (brackets) if
necessary:
sngWallArea = ((3 * 4.5)*2) +
(2) Find area of one roll of wallpaper
Area of one roll = length * width
= 10 * 0.7
= 7 square meters
Again, here is the start of the code you will need:
Exercise 4.2 (continued)
Page 46 of 144 Paul Bolton 2012
sngOneRollArea =
(3) Find number of whole rolls needed
(4) (a) Find area of wallpaper roll left over
(4) (b) Find length of wallpaper roll left over
(5) Find cost of total wallpaper rolls purchased
(6) Find relative cost of fraction of wallpaper roll left over
Page 47 of 144 Paul Bolton 2012
Public ClassForm1
Dim sngWallArea As Single
Dim sngOneRollArea As Single
Dim intNoOfRolls As Integer
Dim sngRemainderAreaOfRoll As Single
Dim sngRemainderLengthOfRoll As Single
Dim decCostOfWallpaperPurchased As Decimal
Dim decCostOfWallpaperWasted As Decimal
Private SubbtnCalculate_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnCalculate.Click
'(1) calculate total area of wall
sngWallArea = ((3 * 4.5) * 2) + (0.5 * 2.5) + ((3 - (1.5 + 0.5)) * 2.5)
MsgBox("Wall area is:" & sngWallArea & " square metres")
'(2) calculate area ofone rollof wallpaper
sngOneRollArea = 0.7 * 10
MsgBox("Area of one roll is:" & sngOneRollArea & " square metres")
'(3) calculate number ofwhole rolls ofwallpaper needed
intNoOfRolls = (sngWallArea sngOneRollArea)+ 1
MsgBox("Noof rollsneededis:" & intNoOfRolls)
'(4)(a) calculate fractionarea ofroll left over
sngRemainderAreaOfRoll = sngWallArea ModsngOneRollArea
MsgBox("Area of roll left over is:" & sngRemainderAreaOfRoll & " sq m")
'(4)(b) calculate length ofroll left over
sngRemainderLengthOfRoll= sngRemainderAreaOfRoll / 0.7
MsgBox("Length ofroll left over is:" & sngRemainderLengthOfRoll & " m")
'(5) calculate total cost ofwallpaper
decCostOfWallpaperPurchased= intNoOfRolls * 8.0
MsgBox("Cost ofwallpaper purchased:£" & decCostOfWallpaperPurchased)
'(6) calculate relative cost ofwallpaper wasted
decCostOfWallpaperWasted = sngRemainderLengthOfRoll* 8.0 / 10
MsgBox("Relative cost ofwallpaper wasted:£" & decCostOfWallpaperWasted)
End Sub
Solution to Exercises 4.2
Page 48 of 144 Paul Bolton 2012
Part 5 - Making selections using If..Then..Else
Program Control – making selections using “If..Then..Else”
So far we have only written code for a sequence of actions for any one event.
However, in many programs we need to make selections according to certain criteria.
In other words, make a decision.
For example, imagine we were shopping for a new mobile phone, and we could spend
up to £100. In our minds we would be performing the following test as we browsed
the shops looking at all the different phones on offer:
If the phone costs up to £100, then
Ask the shop assistant for more details about the phone
Else
Look for a different phone
End of decision
We could write this process into Visual Basic code. If the cost of the mobile phone
was stored in a variable called decCost, we could write:
If decCost < 101 Then
txtMessage.Text = "Make further enquiries"
Else
txtMessage.Text = "Look for a different phone"
End If
The general way this code structure works is:
If a certain condition is true Then
Do this action
Else
Do this other action
End If
The code written between “If” and “Then” is a condition. A condition is an
expression which may be considered to be either “True” or “False”. If the condition
is “True” then the code up to “Else” is carried out. If the Condition is false, then
the code between “Else” and “End If” is carried out.
Background information
Page 49 of 144 Paul Bolton 2012
Notice that if the condition is False (that is, if the mobile phone does not cost up
to £100), we don’t have to test the condition again. If the phone does not cost up
to £100, then logically it must cost more than £100, and the code underneath the
“Else” will run. Also, the Else is optional. Sometimes, depending on our program,
we don’t need to write any code dealing with an Else condition.
< less than
> greater than
= equal to
<> not equal to
>= greater than or equal to
<= less than or equal to
In our code have used the “ < “ symbol
which means “less than”. This is known as
a relational operator, because it compares
one value with another. The full list of
relational operators is:
Page 50 of 144 Paul Bolton 2012
Going back to our example of buying a mobile phone, let’s suppose we wanted to
avoid buying very cheap phones because they wouldn’t have all the features we are
looking for. Suppose we didn’t want to look at any phones which cost less than
£50.
We could amend our code as follows:
If decCost > 50 And decCost < 101 Then
txtMessage.Text = "Make further enquiries"
Else
txtMessage.Text = "Look for a different phone"
End If
The And is known as a logical operator. The full list of logical operators is as follows:
Finally, it is important to realise that in our programs we may be making decisions
which have more than 2 outcomes. In the mobile phone example, we are either
doing one thing or another. We are:
either making further enquiries
or looking for a different phone
But often there will be more than 2 possible courses of action. Suppose we would
consider placing a deposit on the phone if it was outside our price range but had an
internet facility. (Perhaps we would save up and pay for the phone next month.)
Our decision process would look like this:
If the phone costs between £50 and £100, then
Ask the shop assistant for more details about the phone
ElseIf the phone has an internet facility, then
Place a deposit
Else
Look for a different phone
End of decision
And This means both conditions must be True for the entire condition to be True
Or This means if one or both conditions are True, the entire condition is True
Not This reverses the condition so that a True condition will evaluate False, and vice versa.
Background information (continued)
Page 51 of 144 Paul Bolton 2012
The code for the above process could be written as follows. (The answer to whether
the phone has an “internet facility” is stored in a “Yes/No” variable called
“blnInternet”):
If decCost > 50 And decCost < 101 Then
txtMessage.Text = "Make further enquiries"
ElseIf blnInternetFacility = True Then
txtMessage.Text = "Place a deposit"
Else
txtMessage.Text = "Look for a different phone"
End If
We can write as many ElseIf tests as we want to, and each one can result in a
different course of action.
Tax Calculator Program - Scenario
Read the scenario below and then try to carry out the exercises on the following
pages.
Part (a)
A wages department wants you to create a program to help them calculate their
employees’ pay.
At the moment this calculation is done on a hand-held calculator. They want the
program to run as follows:
(1)The wages clerk will type in the Gross Pay and the Tax Allowance for an
employee. (The clerk does not need to type in the employee’s name, just the
figures.)
(2) When the clerk clicks the “Calculate” button, the program will display the Tax
Payable and the Net Pay.
(3) The clerk will then write down the Net Pay for the employee and then type
in figures for the next employee.
The Rate of Tax is 25%. The Tax Payable is calculated by the following equation:
Tax Payable = (Gross Pay – Tax Allowance) x Rate of Tax
Exercises 5.1 – 5.3
Page 52 of 144 Paul Bolton 2012
Because the wages need to be calculated quickly, the wages clerk does not want to
have to use the mouse on the computer. So the program must run by using only
the computer keyboard. You will therefore need to think about:
- how to get the cursor to move about the screen in the right order, and
- how to clear any text boxes after the wages clerk has processed the figures for
one employee and wants to enter details for the next employee.
Part (b)
Once you have demonstrated that the program works to their satisfaction, the wages
department want you to amend the program so that the wages clerk only has to use
the numeric keypad on the keyboard.
Part (c)
Finally, the wages department will want you to restrict access to the program by
creating a password system. When the program first opens there should be a
Password Form which invites the wages clerk to enter a password into a text box.
If the correct password is entered, the Tax Allowance Calculator form you created in
Parts (a) and (b) should open.
If an incorrect password is entered, the program should display a message stating
that the password is incorrect, the text box on the password form should clear and
the cursor return to the text box. If an incorrect password is entered for a total
of 3 times, a message should be displayed that the program is shutting down, and
the program should terminate.
Page 53 of 144 Paul Bolton 2012
If…Then…Else - Exercise 5.1 - Tax Calculator
In this exercise we will be looking at the following topics:
 making selections using If…Then…Else statements
 relational operators such as “>” (“greater than”)
 declaring constants
 drawing Group boxes
 using data-type conversion function to convert String data to decimal
Create a new project and draw group boxes, labels, text boxes and buttons on the
form as shown below:
The aim of the program is that the user should be able enter values into
txtGrossPay and txtTaxAllowance. When the Calculate button is clicked, the program
should calculate and display the Tax Payable and Net Pay.
For this exercise we are assuming the Tax Rate is 25%. The Tax Payable is therefore
calculated by subtracting the Tax Allowance from the Gross Pay, and then finding
25% of the remainder.
txtGrossPay
txtTaxAllowance
txtTaxPayable
txtNetPay
grpInput
grpOutput
btnCalculate
Exercise 5.1
Page 54 of 144 Paul Bolton 2012
For example, if the Gross Pay is £200 and the Tax Allowance (the amount of wage
which is free of tax) is £100, the Tax Payable would be £25 and the Net Pay would
be £175.
Page 55 of 144 Paul Bolton 2012
First, we need to declare 4 variables in which to store the input data (Gross Pay
and Tax Allowance) and the output data (Tax Payable and Net Pay). The data-
type Decimal is the best one to use for currency data. In the code window, declare
the following variables as Decimal by writing:
Note that when we declare variables in this place (just
below the line Public Class Form1) they are available for
use in any procedure in the form (e.g. code written
behind any button). Because the form is technically
known as a module, variables declared here are known as
module-level variables.
Since the Tax Rate is going to remain constant throughout our calculations, we can
declare it as a constant. (A constant is similar to a variable, except that its value
does not change during the life of the program.) We usually write the names of
constants in CAPITAL letters, separated by an underscore if there is more than one
word. Because Tax Rate is a decimal number it is best to store it in a variable of
data-type: Single. We would therefore name the constant SNG_TAX_RATE and
declare it follows:
Note that when we declare constants we must assign a value to them in the same
line of code. Writing 0.25 is the same as writing 25% or 25/100. Remember, we
cannot write 25% in VB code.
Public ClassForm1
Dim decGrossPay As Decimal 'declare variables
Dim decTaxAllowance As Decimal
Dim decTaxPayable As Decimal
Dim decNetPay As Decimal
Const SNG_TAX_RATE As Single = 0.25 'declare constant
Point
to note
Exercise 5.1 (continued)
Page 56 of 144 Paul Bolton 2012
Next we need to write code into btnCalculate which carries out the following steps:
Input Gross Pay and Tax Allowance data from text boxes and store into 2 variables
Calculate Tax Payable as follows:
If Gross Payis greater thanTax Allowance Then
Tax Payable = (Gross Pay – Tax Allowance)x Tax Rate whichis 25%
Else Tax Payable = 0
Calculate Net Pay as follows:
Net Pay= Gross Pay– Tax Payable
Output Tax Payable by displaying in text box txtTaxPayable
Output Net Pay by displaying in text box txtNetPay
The “>” symbol means “greater than”, and it is one of the many relational operators
we can use to compare values in the If…Then…Else statements. The full list of
relational operators is as follows:
< less than
> greater than
= equal to
<> not equal to
>= greater than or equal to
Note: the code for calculating the Tax Payable is as follows:
If decGrossPay > decTaxAllowance Then
decTaxPayable= (decGrossPay - decTaxAllowance) * SNG_TAX_RATE
Else
decTaxPayable= 0
End If
Exercise 5.1 (continued)
Page 57 of 144 Paul Bolton 2012
Try to work out the rest of the code for btnCalculate yourself. Remember that
when data is written in textboxes it is String data-type by default. We therefore
need to convert this to Decimal data-type when it is input to the two variables
using the CDec( ) function.
Page 58 of 144 Paul Bolton 2012
If…Then…Else - Exercise 5.2 Tax Calculator Enhancements
In this exercise we will be looking at the following topics which will protect the data
to processed and make our program more user friendly:
 Setting the TabIndex property
 Using the .Focus() method to move focus to a textbox or button
 Enabling / disabling textboxes using .Enabled = True / False
 Formatting output textboxes by using Format(... ,"Currency") function
 Re-formatting input textboxes by using this same function
 Using the .Clear() method to clear a textbox
 Using the _LostFocus(...) event to run code
(a) Using the TabIndex property
We want to make the program user friendly by arranging it to work without the
user having to use the mouse. We can arrange that the Tab key on the keyboard
will move the focus from one control to another in any order we choose. We do
this by setting the TabIndex property of the controls at design time.
Set the TabIndex of the following controls and check the results when running your
program:
Control name TabIndex Result
value
txtGrossPay 1 Puts cursor in text box when form loads
txtTaxAllowance 2 Puts cursor in text box after pressing Tab key
btnCalculate 3 Sets focus to command button after pressing
Tab key so that user only needs to press
Enter key to “Click” the command button
(b) Providing a “Clear” button and improving navigation
We want to make it easier for the user to re-set the form after they have
performed one calculation. Draw another button on the form, set its Text property
to “Clear” and name it btnClear. Double-click it and write the following code in its
Click event procedure:
PrivateSub btnClear_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnClear.Click
txtGrossPay.Clear() 'clear textbox entries
txtTaxAllowance.Clear()
Exercise 5.2
Page 59 of 144 Paul Bolton 2012
Run your program, enter some data in the first two textboxes and check that both
buttons work as expected.
(c) Protecting data and improving navigation
There is an easy way to provide guidance to the user about which controls to use,
and that is by disabling controls in a set order in response to the user’s actions.
This technique can also be used to protect data.
Double-click on the form itself and write the following code in the Form_Load()
event procedure:
Can you think of similar code you need to write in the btnCalculate_Click() and
btnClear_Click() event procedures?
PrivateSub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
txtTaxPayable.Enabled = False 'disabletextboxes
txtNetPay.Enabled = False
End Sub
Exercise 5.2 (continued)
Page 60 of 144 Paul Bolton 2012
If…Then…Else – Exercise 5.3 Tax Calculator – adding a password form
In this exercise we will be looking at the following topics:
 Making further selections using If…Then…ElseIf…Else statements
 Incrementing counter variables using the += operator
 Using .Show() and .Hide() methods with forms
 Using .Clear() and .Focus() methods with controls
We are going to enhance the program we created earlier to incorporate a password
protection system. When the program first opens there should be a Password Form
which invites the user to enter a password into a text box.
Feature A: If the correct password is entered, the Tax Calculator form we created
in Exercise 5.1 should open. If an incorrect password is entered, the program should
display a message stating that the password is incorrect, the text box on the
password form should clear and the cursor return to the text box.
Feature B: If an incorrect password is entered for a total of 3 times, a message
should be displayed that the program is shutting down, and the program execution
should terminate.
Task 1
Add a new form to your project by
Clicking Project / Add Windows Form…
on the top menu of the design window.
Accept the name of the new form as Form2
Resize the form so that it resembles
the size of a logon screen and draw
the controls as illustrated:
To create Feature A described above, add the following code to the OK button’s
Click() event. Run your program and check if it works as expected by entering an
incorrect password and clicking “OK”, then the correct password (“tax”) and clicking
“OK”.
Private SubbtnOK_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnOK.Click
'if password correct
If txtPassword.Text = "tax" Then
'display message
MsgBox("Access to Tax Calculator permitted.")
'show Tax Calculator form
txtPassword
btnOK
Exercise 5.3
Page 61 of 144 Paul Bolton 2012
Task 2
To create Feature B we need to amend the code we have just written so that if an
incorrect password is entered for a total of 3 times, a message should be displayed
that the program is shutting down, and the program execution should terminate.
We need to create a variable which will keep a tally of the number of times the OK
button has been clicked, then add an ElseIf statement to our If…Then…Else
construction to add further conditions to the decision-making process. Add/amend
the following code shown in bold and highlighted below.
(Note: Be careful to declare the variable intAttemptNumber outside the
btnOK_Click() procedure. If you declare it inside the procedure, it won’t hold its
value between button clicks and won’t count up the number of incorrect password
attempts.)
Public ClassForm2
Dim intAttemptNumber As Integer
Private SubbtnOK_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnOK.Click
'increment counter to store number of attempts
intAttemptNumber += 1
'if passwordcorrect
If txtPassword.Text = "tax" Then
'displaymessage
MsgBox("Access to Tax Calculator permitted.")
'showTax Calculator form
Form1.Show()
'and hide Passwordform
Me.Hide()
'else if attempt number lessthan3
ElseIf intAttemptNumber < 3 Then
'displaymessage
MsgBox("Password incorrect. Please re-type password.")
'clear text box
txtPassword.Clear()
'and put cursor back in text box
txtPassword.Focus()
Else
'else display message
Exercise 5.3 (continued)
Page 62 of 144 Paul Bolton 2012
Further study
Can you think how to incorporate the number of incorrect attempts into the message
displayed to the user, like this:
Page 63 of 144 Paul Bolton 2012
Public Class Form1
Dim decGrossPay As Decimal 'declare variables
Dim decTaxAllowance As Decimal
Dim decTaxPayable As Decimal
Dim decNetPay As Decimal
Const SNG_TAX_RATE As Single = 0.25 'declare constant
'---------------------------------------------------------------------
Private Sub btnCalculate_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnCalculate.Click
'(1) INPUT from textboxes into variables:
'****************************************
decGrossPay = CDec(txtGrossPay.Text) 'store Gross Pay
decTaxAllowance = CDec(txtTaxAllowance.Text) 'store Tax Allowance
'(2) CALCULATE using only variables:
'***********************************
'(a) calculate Gross Pay
If decGrossPay > decTaxAllowance Then 'if Gross Pay > Tax Allowance
decTaxPayable = _
(decGrossPay - decTaxAllowance) * SNG_TAX_RATE 'calculate Tax Payable
Else
decTaxPayable = 0 'else Tax Payable = 0
End If
'(b) calculate Net Pay
decNetPay = decGrossPay - decTaxPayable 'calculate Net Pay
'(3) OUTPUT from variables to textboxes
'**************************************
txtTaxPayable.Text = decTaxPayable 'output Tax Payables
txtNetPay.Text = decNetPay 'output Net Pay
End Sub
'---------------------------------------------------------------------
End Class
Solution to Exercise 5.1
Page 64 of 144 Paul Bolton 2012
Part 6 - More on making selections using If..Then..Else
Sports Club Membership Fees Program - Scenario
Part (a) – creation of basic program
A newly-opened local sports club wants has ask you to create a program to help
them display the difference subscription fees payable by new members.
There are 3 rates:
 Full rate (“F”) is £100
 Senior rate (“S”) is £75
 Junior rate (“J”) is £50
The club wants you to create a program to be used by the receptionist, to run as
follows. The receptionist will enter one letter (either “F”, “S” or “J”) and the
program will display a fee of either £100, £75 or £50 respectively.
Part (b) enhancing basic program to provide a password protection form
The Sports Club want you to restrict access to the program by creating a password
system. When the program first opens there should be a Password Form which
invites the user to enter a password into a text box If the correct password is
entered, the Membership Fees form you created in Part (a) should open.
If an incorrect password is entered, the program should display a message stating
that the password is incorrect, the text box on the password form should clear and
the cursor return to the text box. If an incorrect password is entered for a total
of 3 times, a message should be displayed that the program is shutting down, and
the program should terminate.
Part (c) enhancing basic program to provide a printed receipt
The Sports Club also want the program to provide a printed receipt for each
member. The receipt show contains the following data:
 member name
 member type
 fee paid
 date
Exercise 6.1
Page 65 of 144 Paul Bolton 2012
Part (d) enhancing basic program to work without a mouse
Once you have demonstrated that the program works to their satisfaction, the
sports club wants you to amend the program so that the receptionist only has to
use the keyboard to perform most of the repetitive operations. You will therefore
need to think about:
 how to get the cursor to move about the screen in the right order, and
 how to clear any text boxes after the receptionist has processed the details
for each member.
If..Then..Else – Exercise 6.1 Using multiple criteria to make selections
We can use an If… Then… ElseIf statement in the Click Event for
btnCalculateFeeIfThenElse, (highlighted below):
Private Sub btnCalculateFeeIfThenElse_Click(...)
Dim strMemberType As String 'declare variables
Dim decFee As Decimal
'INPUT data
strMemberType = txtMemberType.Text 'load data into variable
'CALCULATE Membership Fee
If strMemberType = "F" Then 'if Member Type is "F"
decFee = 100 '.. load 100 into variable
ElseIf Then 'if Member Type is "S"
'.. load 75 into variable
ElseIf Then 'if Member Type is "J"
'.. load 50 into variable
Else 'if Member Type is none of the above,
MsgBox("YouNeedto input F, S or J in UpperCase") '..display message
End If
'OUTPUT data
txtDisplayFee.Text = FormatCurrency(decFee, 2) 'format output to currency
'..& display into text box
btnCalculateFeeIfThenElse
txtMemberType
txtDisplayFee
Exercise 6.1 continued
Create the Sports Club Membership Fees form shown
here. In this exercise, the fee for a Full member is
£100, that for a Senior is £75 and that for Junior
is £50.
Page 66 of 144 Paul Bolton 2012
End Sub
See if you can complete the missing code listed above, copy all the code into your
program and then check the program runs as expected.
Further study
In the above example, if the user types in a lowercase letter “f”, “s” or “j”, these
letters are not recognised. See if you can amend your code so that the user can
type in either uppercase or lowercase “F”, “f”, “S”, “s”, “J” or “j”.
(HINT: you can use the Or operator to add criteria to each If / ElseIf statement.
If..Then..Else – Exercise 6.1 SOLUTION
Private Sub btnCalculateFeeIfThenElse_Click(...)
Dim strMemberType As String 'declare variables
Dim decFee As Decimal
'INPUT data
strMemberType = txtMemberType.Text 'loaddata into variable
'CALCULATE Membership Fee
If strMemberType = "F" OrstrMemberType = "f" Then 'if MemberType is "F" or "f"
decFee = 100 '.. load 100 into variable
ElseIf strMemberType = "S" OrstrMemberType = "s" Then'if MemberType is "S" or "s"
decFee = 75 '.. load 75 into variable
ElseIf strMemberType = "J" OrstrMemberType = "j" Then'if MemberType is "J" or "j"
decFee = 50 '.. load 50 into variable
Else 'if Member Type is none of the above,
MsgBox("YouNeed to input F, f, S, s, J or j") '..display message
End If
'OUTPUT data
txtDisplayFee.Text = FormatCurrency(decFee, 2) 'format output to currency
'.. & display into text box
End Sub
Exercise 6.1 continued
Page 67 of 144 Paul Bolton 2012
Part 7 Creating menus using the MenuStrip Control
MenuStrip Control
Exercise 7.1 adding a menu to the Tax Calculator
Open your Tax Calculator program which you completed in Exercise 5.2
Exercise 7.1
Drag a MenuStrip Control
onto the form. An icon
will appear in the grey
Component Tray below the
form, and a blue menu bar
will appear on the top
part of the form
containing he words “Type
Here”.
Page 68 of 144 Paul Bolton 2012
Double-click on the word “Exit” on the top-level menu and the following event
procedure should open in the code window. Type in the code Application.Exit() as
shown
Private SubExitToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
'exit program
Application.Exit()
End Sub
Run your program and check that when you click the menu items File / Exit with
your mouse, the program exits.
Further study
Add a second top-level menu
item “Options”. Add two sub-
menu items beneath this:
“Calculate” and “Clear”:
Double-click on the “Calculate” menu item and write the following code in the event
procedure:
Private SubCalculateToolStripMenuItem_Click(ByValsender As System.Object, _
ByVal e As System.EventArgs) Handles CalculateToolStripMenuItem.Click
'click Calculate button remotely(evoke PerformClickmethod)
btnCalculate.PerformClick()
End Sub
Page 69 of 144 Paul Bolton 2012
Run your program and see if the Calculate menu item performs the calculation in the
same way as when you click the Calculate button.
See if you can work out how to add code to the Clear menu item to clear all the
textboxes and place the cursor back in the Gross Pay textbox.
Can you think of any other menu items and sub-menus you may want to add to
enhance your program?
Page 70 of 144 Paul Bolton 2012
Part 8 Making selections using Select Case
Select Case
Exercise 8.1 Demonstration of advantage of Select Case construction
Complete the following code (and include a message which responds to the user
entering any number not between 1 and 12):
Private Sub btnMonth_Click(...) Handles btnMonth.Click
Dim intMonthNumber As Integer
'input month number intovariable
intMonthNumber = CInt(txtNumber.Text)
'output monthbasedonmonth number
Select Case intMonthNumber
Case 1
MsgBox("Youhave selectedJanuary")
Case 2
MsgBox("Youhave selectedFebruary")
'** continue coding from this point onwards **
End select
End Sub
txtNumber
btnMonth
Exercise 8.1
Page 71 of 144 Paul Bolton 2012
Sports Club Membership Fees Program - Revisit of scenario:
converting If..Then..Else to Select Case
Select Case – Exercise 8.2 Membership fees program revisited
We have looked at two program control structures so far:
(1) A straight sequence of commands, which are executed one after the other.
(2) A selection using “If ... Then... ElseIf… Else… End If”
There is an alternative to the If statement, which is the Select Case structure.
We have already used an If… Then… ElseIf statement in the Click Event for
btnCalculateFeeIfThenElse, (highlighted below):
Private Sub btnCalculateFeeIfThenElse_Click(...)
Dim strMemberType As String 'declare variables
Dim decFee As Decimal
'INPUT data
strMemberType = txtMemberType.Text 'loaddata into variable
'CALCULATE Membership Fee
If strMemberType = "F" Then 'if Member Type is "F"
decFee = 100 '.. load 100 into variable
ElseIf strMemberType = "S" Then 'if Member Type is "S"
decFee = 75 '.. load 75 into variable
ElseIf strMemberType = "J" Then 'if Member Type is "J"
decFee = 50 '.. load 50 into variable
Else 'if Member Type is none of the above,
MsgBox("YouNeedto input F, S or J in UpperCase") '..display message
btnCalculateFeeIfThenElse
txtMemberType
txtDisplayFee
btnCalculateFeeSelectCase
Exercise 8.2
Existing code
Open (or create) the Sports Club Membership
Fees form shown here. In this exercise, the
fee for a Full member is £100, that for a
Senior is £75 and that for Junior is £50.
Run your program and check that the first
button works as expected before coding the
second button (see next page).
Page 72 of 144 Paul Bolton 2012
End If
'OUTPUT data
txtDisplayFee.Text = FormatCurrency(decFee, 2) 'format output to currency & display into text box
End Sub
Using the Select Case structure as an alternative to the If…Then…Else structure.
Code the btnCalculateFeeSelectCase button as follows and check the program runs
with this alternative code. Compare the two constructions.
'CALCULATE Membership Fee
Select Case strMemberType
Case "F" 'if Member Type is "F"
decFee = 100 '..load 100 into variable
Case "S" 'if Member Type is "S"
decFee = 75 '.. load 75 into variable
Case "J" 'if Member Type is "J"
decFee = 50 '.. load 50 into variable
Case Else 'if Member Type is none of the above,
MsgBox("You Needto input F, S or J in UpperCase") 'display message
End Select
Each Case acts like an If / ElseIf Statement. The instructions after an individual
Case are carried out if the variable being tested matches it.
Further study:
Multiple tests within one “case” using a comma to separate tests.
In the above example, if the user types in a lower case letter “f”, “s” or “j”, these
letters are not recognised. We can get round this by the following construction:
Select Case strMemberType
Case "F", "f" 'if Member Type is "F"or "f"
decFee = 100 '..load 100 into variable
Case "S", "s" 'if Member Type is "S" or "s"
decFee = 75 '.. load 75 into variable
Case "J", "j" 'if Member Type is "J" or "j"
decFee = 50 '.. load 50 into variable
Case Else 'if Member Type is none of the above, display message
MsgBox("You Needto input F, S or J in Upper or LowerCase")
End Select
Try amending your code and check if it works.
Exercise 8.2 (continued)
Page 73 of 144 Paul Bolton 2012
Page 74 of 144 Paul Bolton 2012
Select Case - Further theory
Testing for a range using the “To” keyword.
You may wish to display exam grades according to a range of marks obtained by
students. You would use the keyword “To” and the code would look something
like this:
Select Case txtExamGrade.Text
Case 90 To 100
strGrade = “A”
Case 60 To 89
strGrade = “B”
Case 40 To 59
strGrade = “C”
Case 0 To 39
strGrade = “FAIL”
Case Else
MsgBox ("You Need to input a number between 0 and 100")
End Select
Using “Case Is” followed
by “relational operators”
You can also test how the input value compares to another value by using the
optional keyword “Is" followed by a relational operator in this way:
Select Case decSales
Case Is > 2000
decCommission = (decSales * 10 / 100) + 100
Case Is > 1750
decCommission = (decSales * 10 / 100)
Case Is > 1000
decCommission = (decSales * 7 / 100)
Case Is > 750
decCommission = (decSales * 5 / 100)
Case Is > 500
Background information
< less than
> greater than
= equal to
<> not equal to
>= greater than or equal to
Page 75 of 144 Paul Bolton 2012
decCommission = (decSales * 2 / 100)
Case Else
decCommission = 0
End Select
Page 76 of 144 Paul Bolton 2012
Select Case Demonstration of advantage of If..Then..Else
construction over Select Case construction
Private Sub btnOK_Click(...)HandlesbtnOk.Click
Dim intAge As Integer
Dim strGender As String
'input age and gender
strGender = CStr(txtInputGender.Text)
intAge = CInt(txtInputAge.Text)
'process data and displayappropriate message
If strGender = "M" And intAge < 21 Then
MsgBox("Premium is £500")
ElseIf strGender = "M" And intAge >= 21 Then
MsgBox("Premium is £250")
ElseIf strGender = "F" And intAge < 21 Then
MsgBox("Premium is £300")
ElseIf strGender = "F" And intAge >= 21 Then
MsgBox("Premium is £150")
Else
MsgBox("Youhave entered invaliddata")
End If
End Sub We cannot test 2 conditions at once
using Select Case
Background information
Page 77 of 144 Paul Bolton 2012
Select Case – Exercise 8.1 SOLUTION
Solution to Exercise 8.1
Private Sub btnMonth_Click(...) Handles btnMonth.Click
Dim intMonthNumber As Integer
'input month number intovariable
intMonthNumber = CInt(txtNumber.Text)
'output monthbasedonmonth number
Select Case intMonthNumber
Case 1
MsgBox("Youhave selectedJanuary")
Case 2
MsgBox("Youhave selectedFebruary")
Case 3
MsgBox("Youhave selectedMarch")
Case 4
MsgBox("Youhave selectedApril")
Case 5
MsgBox("Youhave selectedMay")
Case 6
MsgBox("Youhave selectedJune")
Case 7
MsgBox("Youhave selectedJuly")
Case 8
MsgBox("Youhave selectedAugust")
Case 9
MsgBox("Youhave selectedSeptember")
Case 10
MsgBox("Youhave selectedOctober")
Case 11
MsgBox("Youhave selectedNovember")
Case 12
MsgBox("Youhave selectedDecember")
Case Else
MsgBox("Youhave not entereda number between1 and12")
End Select
'clear textbox
txtNumber.Clear()
'put cursor backintextbox
txtNumber.Focus()
End Sub
Page 78 of 144 Paul Bolton 2012
Part 9 - Iterations (loops) using For..Next
For…Next loops - underpinning knowledge
Background
There are 3 program control structures covered by this course. We have already
looked at the first two:
- sequences (one instruction after another)
- selections (such as “If… Then… Else” or “Select Case” statements)
The third program control structure introduces the concept of iteration (meaning
“repeat the process”) using loops. There are two types of loop:
the counter loop, and
the conditional loop (such as “Do… While” ).
Here we are only going to deal with the counter loop (otherwise known as the “For…
Next” loop).
Example
Suppose we wanted to make the computer beep 5 times. (By the way, there is a
simple line of code which makes the computer beep, namely: “beep”!) You could put
this line of code behind a command button, and press the button 5 times:
Private Sub btnBeep_Click(...)
Beep
End Sub
However, what if we wanted to only click the command button once, and then make
the code run automatically 5 times? The answer is to use a counter loop (known as
a “For…Next” loop). For… Next loops need to have a variable in which to store the
number of times the code should be run. In this example, let us name the variable
“intCounter” and declare it as an integer. The code would be written as follows:
Private Sub btnBeep_Click(...)
Dim intCounter As Integer
For intCounter = 1 To 5
Beep
Next intCounter
End Sub
This code means:
“Increment the value of the “intCounter” variable from 1 to 5,
Background information
Page 79 of 144 Paul Bolton 2012
and every time you increment it, execute the code below”.
This is the simplest way of using the “For… Next” loop, but you need to know some
more details to use it properly (covered on next handout). For now, try the
exercise overleaf.
Page 80 of 144 Paul Bolton 2012
For..Next Loops - Exercise 9.1 Beep exercise
Create a form with a button as shown below. We want the code to produce 5
“beeps” when the button is pressed. However, modern computers run so fast that
you will never hear the 5 beeps, so instead we will use a Message Box to produce the
beeps. (Message Boxes require user response, which “interrupts” the execution of
the code so you can see how the code in fact loops 5 times.)
Write the code below into the “Click event” sub-procedure of the button btnBeep:
Private Sub btnBeep_Click(...)
Dim intCounter As Integer
For intCounter = 1 To 5
MsgBox("Press to beep")
Next intCounter
End Sub
After pressing the “beep” button, you will find that a
MessageBox similar to this one appears, and after
clicking “OK” it will re-appear another 4 times.
Next, it would be good to make the Message Box tell us how many times the code
has looped.
To do this, we can include the name of the counter variable into the MsgBox
function. This will display the contents of the variable each time the code loops.
However, we will need to:
(1)convert the counter variable data from an integer into a string, and then
(2) “tack it on” to the existing message string (known as concatenation)
To convert the variable data into a string we use the conversion function CStr( )
and put the name of the variable into the brackets, i.e. CStr(intCounter). We then
“tack it on” to (concatenate it to) the original message using the “&” symbol:
MsgBox("Press to beep. Iteration no: " & CStr(intCounter))
Alter you code as above and see what effect this has.
Exercise 9.1
Page 81 of 144 Paul Bolton 2012
(Note: we will be looking in more detail at how to use Message Boxes later in the
course.)
Page 82 of 144 Paul Bolton 2012
For.. Next Loops - Underpinning knowledge (continued)
Counting in steps
By default, the “For… Next” loop counts upwards in steps of 1, unless you tell it
otherwise.
So, the value of the variable “intCounter” above became: 1, then 2, then 3, then
4, then 5, as the loop was repeated 5 times.
However, you can tell it to count upwards in increments other than 1, by adding
the word “step” to the line of code. You could make the loop count up to 10
in steps of 2, for example:
For intCounter = 1 To 10 Step 2
The result here would be that the loop is repeated 5 times. (The value of the
variable would be 1, 3, 5, 7, and 9.)
Counting backwards
There are times when you will want to count down instead of counting up. You
do this by using a negative “step” number. The example below again will run the
code 5 times.
For intCounter = 5 To 1 Step -1
In summary, the general structure of the “For… Next” loop is shown below.
(the code written in brackets [ ] is optional)
For countervariable = startnumber to endnumber [Step stepnumber]
Next [countervariable]
(3) Using variables for the start and end numbers.
Body of code
to be repeated
Background information
Page 83 of 144 Paul Bolton 2012
“For… Next” loops can become very useful by substituting variables for either the
start or end numbers (or both).
This method is used, for example, when the user puts in a number and you need
to get the code to repeat that same number of times. This is demonstrated in
the following exercise.
Page 84 of 144 Paul Bolton 2012
For.. Next loops - Exercise 9.2 - Mobile phone credits exercise
If we were crediting a mobile phone with £10 vouchers; rather than enter each value
we might want to be able to enter how many vouchers were being presented. We
could just multiply the two together but that would be too easy and wouldn’t show
the working of the iterative loop.
We will use a form like the one below. The form above should accept the value of
vouchers, their number and then calculate the total credit.
The user should enter the value of the vouchers and the number. When the calculate
button is depressed, a message box should appear and show the number of times a
credit voucher has been entered, as shown below:
When the user clicks “OK” on the message box, it keeps re-appearing until all the
vouchers have been entered. Create a form like the one above and see if you can
work out the code.
Extended Task
txtValue
txtNumber
txtCredit
btnCalculate btnClear
then… etc.
Exercise 9.2
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide
Visual Basic Programming Guide

More Related Content

What's hot

Ibm spss custom_tables
Ibm spss custom_tablesIbm spss custom_tables
Ibm spss custom_tablesDũ Lê Anh
 
Vic broquard c++ for computer science and engineering 2006
Vic broquard c++ for computer science and engineering 2006Vic broquard c++ for computer science and engineering 2006
Vic broquard c++ for computer science and engineering 2006Souvik Maity
 
Deployment guide series ibm tivoli identity manager 5.0 sg246477
Deployment guide series ibm tivoli identity manager 5.0 sg246477Deployment guide series ibm tivoli identity manager 5.0 sg246477
Deployment guide series ibm tivoli identity manager 5.0 sg246477Banking at Ho Chi Minh city
 
Extending your business to mobile devices with ibm worklight
Extending your business to mobile devices with ibm worklightExtending your business to mobile devices with ibm worklight
Extending your business to mobile devices with ibm worklightbupbechanhgmail
 
Excel vba visual basic (korol) (1)
Excel vba visual basic (korol) (1)Excel vba visual basic (korol) (1)
Excel vba visual basic (korol) (1)Liceth777
 
Uni fi controller_ug
Uni fi controller_ugUni fi controller_ug
Uni fi controller_ugjoko
 
The Readiness Plan A Spotlight on Customer Success
The Readiness Plan A Spotlight on Customer SuccessThe Readiness Plan A Spotlight on Customer Success
The Readiness Plan A Spotlight on Customer SuccessDav Hol
 
Managing Data Center Connectivity TechBook
Managing Data Center Connectivity TechBook Managing Data Center Connectivity TechBook
Managing Data Center Connectivity TechBook EMC
 
Certification guide series ibm tivoli netcool omn ibus v7.2 implementation sg...
Certification guide series ibm tivoli netcool omn ibus v7.2 implementation sg...Certification guide series ibm tivoli netcool omn ibus v7.2 implementation sg...
Certification guide series ibm tivoli netcool omn ibus v7.2 implementation sg...Banking at Ho Chi Minh city
 

What's hot (14)

Ibm spss custom_tables
Ibm spss custom_tablesIbm spss custom_tables
Ibm spss custom_tables
 
Ti ba-2-plus-rus
Ti ba-2-plus-rusTi ba-2-plus-rus
Ti ba-2-plus-rus
 
Corel draw learning file
Corel draw learning fileCorel draw learning file
Corel draw learning file
 
Red book Blueworks Live
Red book Blueworks LiveRed book Blueworks Live
Red book Blueworks Live
 
Vic broquard c++ for computer science and engineering 2006
Vic broquard c++ for computer science and engineering 2006Vic broquard c++ for computer science and engineering 2006
Vic broquard c++ for computer science and engineering 2006
 
Deployment guide series ibm tivoli identity manager 5.0 sg246477
Deployment guide series ibm tivoli identity manager 5.0 sg246477Deployment guide series ibm tivoli identity manager 5.0 sg246477
Deployment guide series ibm tivoli identity manager 5.0 sg246477
 
Extending your business to mobile devices with ibm worklight
Extending your business to mobile devices with ibm worklightExtending your business to mobile devices with ibm worklight
Extending your business to mobile devices with ibm worklight
 
Remedy
RemedyRemedy
Remedy
 
Sg246776
Sg246776Sg246776
Sg246776
 
Excel vba visual basic (korol) (1)
Excel vba visual basic (korol) (1)Excel vba visual basic (korol) (1)
Excel vba visual basic (korol) (1)
 
Uni fi controller_ug
Uni fi controller_ugUni fi controller_ug
Uni fi controller_ug
 
The Readiness Plan A Spotlight on Customer Success
The Readiness Plan A Spotlight on Customer SuccessThe Readiness Plan A Spotlight on Customer Success
The Readiness Plan A Spotlight on Customer Success
 
Managing Data Center Connectivity TechBook
Managing Data Center Connectivity TechBook Managing Data Center Connectivity TechBook
Managing Data Center Connectivity TechBook
 
Certification guide series ibm tivoli netcool omn ibus v7.2 implementation sg...
Certification guide series ibm tivoli netcool omn ibus v7.2 implementation sg...Certification guide series ibm tivoli netcool omn ibus v7.2 implementation sg...
Certification guide series ibm tivoli netcool omn ibus v7.2 implementation sg...
 

Viewers also liked

Financial consultants in Delhi | Financial services provider in Gurgaon
Financial consultants in Delhi | Financial services provider in GurgaonFinancial consultants in Delhi | Financial services provider in Gurgaon
Financial consultants in Delhi | Financial services provider in GurgaonFortune Finances
 
Triatlón en los juegos olímpicos
Triatlón en los juegos olímpicosTriatlón en los juegos olímpicos
Triatlón en los juegos olímpicoskatty salinas
 
Financial consultants in Delhi | Financial services provider in Gurgaon
Financial consultants in Delhi | Financial services provider in GurgaonFinancial consultants in Delhi | Financial services provider in Gurgaon
Financial consultants in Delhi | Financial services provider in GurgaonFortune Finances
 
Taller Hipervinculos
Taller HipervinculosTaller Hipervinculos
Taller HipervinculosLuisa Cuartas
 
COMPASS_COALITION_DECK
COMPASS_COALITION_DECKCOMPASS_COALITION_DECK
COMPASS_COALITION_DECKJosh Figgs
 
50 sombras-de-grey-final
50 sombras-de-grey-final50 sombras-de-grey-final
50 sombras-de-grey-finalJonathan Colago
 
Amali B E UFR first load out
Amali B E UFR first load outAmali B E UFR first load out
Amali B E UFR first load outBenedict Amali
 
Tecnicas de recoleccion de datos
Tecnicas de recoleccion de datosTecnicas de recoleccion de datos
Tecnicas de recoleccion de datosdiovilarboleda
 
Triatlón en los juegos olímpicos
Triatlón en los juegos olímpicosTriatlón en los juegos olímpicos
Triatlón en los juegos olímpicoskatty salinas
 
Flood and Gender-Gendered Vulnerability in Floods Plains of West Champaran, B...
Flood and Gender-Gendered Vulnerability in Floods Plains of West Champaran, B...Flood and Gender-Gendered Vulnerability in Floods Plains of West Champaran, B...
Flood and Gender-Gendered Vulnerability in Floods Plains of West Champaran, B...HI-AWARE
 
マーケティング・オートメーションとCMS
マーケティング・オートメーションとCMSマーケティング・オートメーションとCMS
マーケティング・オートメーションとCMSTAM inc.
 

Viewers also liked (14)

samer alhaj mahmoud cv
samer alhaj mahmoud cvsamer alhaj mahmoud cv
samer alhaj mahmoud cv
 
Trabajo diplomado
Trabajo diplomadoTrabajo diplomado
Trabajo diplomado
 
Steve Bailey CV
Steve Bailey CVSteve Bailey CV
Steve Bailey CV
 
Financial consultants in Delhi | Financial services provider in Gurgaon
Financial consultants in Delhi | Financial services provider in GurgaonFinancial consultants in Delhi | Financial services provider in Gurgaon
Financial consultants in Delhi | Financial services provider in Gurgaon
 
Triatlón en los juegos olímpicos
Triatlón en los juegos olímpicosTriatlón en los juegos olímpicos
Triatlón en los juegos olímpicos
 
Financial consultants in Delhi | Financial services provider in Gurgaon
Financial consultants in Delhi | Financial services provider in GurgaonFinancial consultants in Delhi | Financial services provider in Gurgaon
Financial consultants in Delhi | Financial services provider in Gurgaon
 
Taller Hipervinculos
Taller HipervinculosTaller Hipervinculos
Taller Hipervinculos
 
COMPASS_COALITION_DECK
COMPASS_COALITION_DECKCOMPASS_COALITION_DECK
COMPASS_COALITION_DECK
 
50 sombras-de-grey-final
50 sombras-de-grey-final50 sombras-de-grey-final
50 sombras-de-grey-final
 
Amali B E UFR first load out
Amali B E UFR first load outAmali B E UFR first load out
Amali B E UFR first load out
 
Tecnicas de recoleccion de datos
Tecnicas de recoleccion de datosTecnicas de recoleccion de datos
Tecnicas de recoleccion de datos
 
Triatlón en los juegos olímpicos
Triatlón en los juegos olímpicosTriatlón en los juegos olímpicos
Triatlón en los juegos olímpicos
 
Flood and Gender-Gendered Vulnerability in Floods Plains of West Champaran, B...
Flood and Gender-Gendered Vulnerability in Floods Plains of West Champaran, B...Flood and Gender-Gendered Vulnerability in Floods Plains of West Champaran, B...
Flood and Gender-Gendered Vulnerability in Floods Plains of West Champaran, B...
 
マーケティング・オートメーションとCMS
マーケティング・オートメーションとCMSマーケティング・オートメーションとCMS
マーケティング・オートメーションとCMS
 

Similar to Visual Basic Programming Guide

Openobject developer
Openobject developerOpenobject developer
Openobject developerAli Mashduqi
 
SAP_HANA_Modeling_Guide_for_SAP_HANA_Studio_en
SAP_HANA_Modeling_Guide_for_SAP_HANA_Studio_enSAP_HANA_Modeling_Guide_for_SAP_HANA_Studio_en
SAP_HANA_Modeling_Guide_for_SAP_HANA_Studio_enJim Miller, MBA
 
Openobject developer1
Openobject developer1Openobject developer1
Openobject developer1openerpwiki
 
Open erp openobject-developer
Open erp openobject-developerOpen erp openobject-developer
Open erp openobject-developeropenerpwiki
 
Openobject developer
Openobject developerOpenobject developer
Openobject developeropenerpwiki
 
Openobject developer (2)
Openobject developer (2)Openobject developer (2)
Openobject developer (2)openerpwiki
 
Solmanfocusedbuild
SolmanfocusedbuildSolmanfocusedbuild
SolmanfocusedbuildGhassen B
 
SAP MM Tutorial ds_42_tutorial_en.pdf
SAP MM Tutorial    ds_42_tutorial_en.pdfSAP MM Tutorial    ds_42_tutorial_en.pdf
SAP MM Tutorial ds_42_tutorial_en.pdfsjha120721
 
Salesforce creating on_demand_apps
Salesforce creating on_demand_appsSalesforce creating on_demand_apps
Salesforce creating on_demand_appswillsco
 
Python_Programming_and_Numerical_Methods_A_Guide_for_Engineers_and.pdf
Python_Programming_and_Numerical_Methods_A_Guide_for_Engineers_and.pdfPython_Programming_and_Numerical_Methods_A_Guide_for_Engineers_and.pdf
Python_Programming_and_Numerical_Methods_A_Guide_for_Engineers_and.pdfjankoabel2022
 
An Introduction to MATLAB for Geoscientists.pdf
An Introduction to MATLAB for Geoscientists.pdfAn Introduction to MATLAB for Geoscientists.pdf
An Introduction to MATLAB for Geoscientists.pdfvishnuraj764102
 
Certification guide series ibm tivoli usage and accounting manager v7.1 imple...
Certification guide series ibm tivoli usage and accounting manager v7.1 imple...Certification guide series ibm tivoli usage and accounting manager v7.1 imple...
Certification guide series ibm tivoli usage and accounting manager v7.1 imple...Banking at Ho Chi Minh city
 

Similar to Visual Basic Programming Guide (20)

Introduction to BIRT
Introduction to BIRTIntroduction to BIRT
Introduction to BIRT
 
Openobject developer
Openobject developerOpenobject developer
Openobject developer
 
SAP_HANA_Modeling_Guide_for_SAP_HANA_Studio_en
SAP_HANA_Modeling_Guide_for_SAP_HANA_Studio_enSAP_HANA_Modeling_Guide_for_SAP_HANA_Studio_en
SAP_HANA_Modeling_Guide_for_SAP_HANA_Studio_en
 
Openobject developer1
Openobject developer1Openobject developer1
Openobject developer1
 
Open erp openobject-developer
Open erp openobject-developerOpen erp openobject-developer
Open erp openobject-developer
 
Openobject developer
Openobject developerOpenobject developer
Openobject developer
 
Openobject developer (2)
Openobject developer (2)Openobject developer (2)
Openobject developer (2)
 
Solmanfocusedbuild
SolmanfocusedbuildSolmanfocusedbuild
Solmanfocusedbuild
 
SAP MM Tutorial ds_42_tutorial_en.pdf
SAP MM Tutorial    ds_42_tutorial_en.pdfSAP MM Tutorial    ds_42_tutorial_en.pdf
SAP MM Tutorial ds_42_tutorial_en.pdf
 
Salesforce creating on_demand_apps
Salesforce creating on_demand_appsSalesforce creating on_demand_apps
Salesforce creating on_demand_apps
 
GENESYS™ 10S UV-Vis (English)
GENESYS™ 10S UV-Vis (English)GENESYS™ 10S UV-Vis (English)
GENESYS™ 10S UV-Vis (English)
 
Struts Live
Struts LiveStruts Live
Struts Live
 
Jakarta strutslive
Jakarta strutsliveJakarta strutslive
Jakarta strutslive
 
Jakarta struts
Jakarta strutsJakarta struts
Jakarta struts
 
Bwl red book
Bwl red bookBwl red book
Bwl red book
 
2226 v3 rev_a
2226 v3 rev_a2226 v3 rev_a
2226 v3 rev_a
 
Python_Programming_and_Numerical_Methods_A_Guide_for_Engineers_and.pdf
Python_Programming_and_Numerical_Methods_A_Guide_for_Engineers_and.pdfPython_Programming_and_Numerical_Methods_A_Guide_for_Engineers_and.pdf
Python_Programming_and_Numerical_Methods_A_Guide_for_Engineers_and.pdf
 
An Introduction to MATLAB for Geoscientists.pdf
An Introduction to MATLAB for Geoscientists.pdfAn Introduction to MATLAB for Geoscientists.pdf
An Introduction to MATLAB for Geoscientists.pdf
 
Certification guide series ibm tivoli usage and accounting manager v7.1 imple...
Certification guide series ibm tivoli usage and accounting manager v7.1 imple...Certification guide series ibm tivoli usage and accounting manager v7.1 imple...
Certification guide series ibm tivoli usage and accounting manager v7.1 imple...
 
Calc Guide
Calc GuideCalc Guide
Calc Guide
 

Recently uploaded

"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 

Recently uploaded (20)

Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 

Visual Basic Programming Guide

  • 1.
  • 2. Page 2 of 144 Paul Bolton 2012 Table of Contents Part 1 - The Basics ...........................................................7 Introduction: Three Steps in Developing a Windows Application ............... 7 Exercise 1.1 - Changing the text in a label control .................................................9 Designing the Form .......................................................................................12 Coding .......................................................................................................13 Running the Program ....................................................................................14 Saving the Program ......................................................................................14 More on the VB Integrated Development Environment (IDE)................. 14 Menu Bar ...................................................................................................14 Toolbox......................................................................................................16 Solution Explorer Window ...............................................................................17 Standard naming conventions for controls ...........................................................19 The Visual Basic 2010 IDE – In depth.............................................. 21 Structure of a Visual Basic Windows Application..................................................22 Part 2 - Moving on from the Basics....................................23 Consolidation exercises introducing Visual Basic ................................... 23 Exercise 2.1 ...............................................................................................23 Exercise 2.2 ...............................................................................................24 Exercise 2.3 ...............................................................................................24 Exercise 2.4 ...............................................................................................25 Part 3 – Arithmetic & Variables.........................................26 Arithmetic Introductory Exercise 3.1............................................... 26 Introduction to data types ............................................................................26 Task 1 ....................................................................................................26 Task 2 ................................................................................................... 27 Task 3 ...................................................................................................28 Observations ............................................................................................28 Arithmetic & Variables: Underpinning Knowledge ................................ 29 Data Types ................................................................................................29 Arithmetic Exercise 3.2 Declaring variables & type casting.....................................30
  • 3. Page 3 of 144 Paul Bolton 2012 Task 1 ....................................................................................................30 Task 2 ...................................................................................................33 Task 3 ...................................................................................................33 Task 4 ...................................................................................................34 Arithmetic, Data-Types & Variables ................................................ 35 Converting data before storing it into variables (known as data “ Type Casting”) ........35 Part 4 - More on Arithmetic & Variables.............................36 Arithmetic Exercise 4.1................................................................ 36 Introducing the scrollbar control ......................................................................36 Scrollbar Setting scrollbar properties ............................................... 38 (1) Setting Max and Min properties ................................................................40 (2) Setting SmallCange and LargeChange properties.............................................40 (3) Setting Value property ............................................................................41 Arithmetic Exercise 4.2 – Wallpaper Estimator...................................................43 Data types, arithmetical operators & variables .................................................43 Part 5 - Making selections using If..Then..Else .................48 Program Control – making selections using “If..Then..Else”................... 48 Tax Calculator Program - Scenario ....................................................................51 Part (a) ..................................................................................................51 Part (b).................................................................................................52 Part (c) .................................................................................................52 If…Then…Else - Exercise 5.1 - Tax Calculator......................................................53 If…Then…Else - Exercise 5.2 Tax Calculator Enhancements .....................................58 (a) Using the TabIndex property ..................................................................58 (b) Providing a “Clear” button and improving navigation ....................................58 (c) Protecting data and improving navigation...................................................59 If…Then…Else – Exercise 5.3 Tax Calculator – adding a password form .....................60 Task 1 ....................................................................................................60 Task 2 ....................................................................................................61 Part 6 - More on making selections using If..Then..Else ...........64
  • 4. Page 4 of 144 Paul Bolton 2012 Sports Club Membership Fees Program - Scenario .............................. 64 Part (a) – creation of basic program ...............................................................64 Part (b) enhancing basic program to provide a password protection form .................64 Part (c) enhancing basic program to provide a printed receipt ...............................64 Part (d) enhancing basic program to work without a mouse ..................................65 If..Then..Else – Exercise 6.1 Using multiple criteria to make selections .....................65 If..Then..Else – Exercise 6.1 SOLUTION ............................................................66 Part 7 Creating menus using the MenuStrip Control ............... 67 MenuStrip Control.......................................................................67 Exercise 7.1 adding a menu to the Tax Calculator ................................................ 67 Part 8 Making selections using Select Case ........................ 70 Select Case................................................................................70 Exercise 8.1 Demonstration of advantage of Select Case construction........................ 70 Sports Club Membership Fees Program - Revisit of scenario: converting If..Then..Else to Select Case............................................................ 71 Select Case – Exercise 8.2 Membership fees program revisited ................................71 Select Case - Further theory ......................................................................... 74 Select Case Demonstration of advantage of If..Then..Else construction over Select Case construction .....................................................76 Select Case – Exercise 8.1 SOLUTION ............................................................... 77 Part 9 - Iterations (loops) using For..Next........................... 78 For…Next loops - underpinning knowledge..........................................78 Background................................................................................................. 78 Example .................................................................................................... 78 For..Next Loops - Exercise 9.1 Beep exercise ....................................................80 For.. Next Loops - Underpinning knowledge (continued) ...................... 82 Counting in steps ........................................................................................82 Counting backwards ......................................................................................82 For.. Next loops - Exercise 9.2 - Mobile phone credits exercise ..............................84 Extended Task ............................................................................................84 For… Next Loops - Quiz .............................................................................86 For… Next Loops - Quiz (Answers) ...............................................................88
  • 5. Page 5 of 144 Paul Bolton 2012 Coding solution to Exercise 9.2 For... Next loops - Mobile phone credits exercise SOLUTION.................................................................................................89 Part 10 - Iterations (loops) using Do..Loops .........................90 Conditional loops ........................................................................ 90 Exercise 10.1 “Do…” loops introductory exercise ..................................................90 Conditional loops continued ........................................................... 93 Exercise 10.2 “Do…” loops exercise: Moving a picture ..........................................93 Task 1 ....................................................................................................93 Task 2 ...................................................................................................94 Task 3 ...................................................................................................94 Part 11 - Debugging, Testing & Error Handling .......................95 Debugging ................................................................................. 95 Exercise 11.1 Sales Department Wage Calculator ..................................................95 Debugging – Exercise 11.1: Sales Department Wage Calculator code ........................... 97 How to write testing documentation .............................................. 99 Design-time errors .......................................................................................99 Run-time errors..........................................................................................99 How to write testing documentation (continued) ............................... 101 Sample Test Plan .......................................................................................103 How to write an Error Report ..................................................... 105 Error Report (action taken to correct errors)................................................... 107 Error Handling .......................................................................... 108 Exercise 11.2 Tax Calculator program revisited ...................................................108 Task 1 ...................................................................................................108 Task 2: Error Handling ............................................................................... 111 Task 2 (continued) – Further study ..............................................................113 Task 3: Exception Handling..........................................................................114 Task 3 (continued) – Further study ..............................................................116 Part 12 - File Handling: Using Sequential Data Files (Text Files)117 File handling.............................................................................. 117 Exercise 12.1: Storing student marks in a Data File .............................................117
  • 6. Page 6 of 144 Paul Bolton 2012 Task 1 – writing one record .........................................................................117 Task 2 – reading one record ........................................................................118 Task 3 – writing multiple records .................................................................118 Task 4 – reading multiple records ................................................................120 Part 13 Dialog Controls ................................................... 121 Dialog Controls .......................................................................... 121 Exercise 13.1: Adding the Color Dialog control to a program ..................................121 ColorDialog Customisation ...........................................................................122 Exercise 13.2: Adding Open / Save File Dialogs to the “Student Marks” program ......124 (1) Customising the dialog box display .............................................................126 (a) Setting the default filename .................................................................126 (b) Filtering the list of file types................................................................128 (c) Setting the default file location (folder) ..................................................128 (d) Setting the title................................................................................129 (2) Dealing with errors ...............................................................................129 (a) Errors when clicking the “Cancel” button .................................................129 Exercise 13.3: Adding Save File Dialog to the “Student Marks” program .................132 Code for the SaveFile dialog control:.............................................................134 Additional customisation ............................................................................134 Part 14 - Listbox & Combobox controls...............................136 List & Combo Box ..................................................................... 136 Exercise 14.1 Flight Seat Planner....................................................................136 List & Combo Box ..................................................................... 139 Exercise 14.2: Flight Seat Planner enhancement .................................................139 Task 1 ...................................................................................................139 Task 2 ..................................................................................................139 Task 3 ..................................................................................................139 Part 15 Multiple Event Handlers........................................ 141 Multiple Event Handlers............................................................... 141 Exercise 15.1: Colour Picker ............................................................................141
  • 7. Page 7 of 144 Paul Bolton 2012 Part 1 - The Basics Introduction: Three Steps in Developing a Windows Application The Visual Basic Integrated Development Environment (IDE) Makes building an application a straightforward process. There are three primary steps involved in building a Visual Basic application: 1. We draw the user interface by placing controls on a Windows form 2. We assign properties to controls 3. We write code for control events (and perhaps write other procedures) Example Example
  • 8. Page 8 of 144 Paul Bolton 2012 These same steps are followed whether you are building a very simple application or one involving many controls and many lines of code. The event-driven nature of Visual Basic applications allows you to build your application in stages and test it at each stage. You can build one procedure, or part of a procedure, at a time and try it until it works as desired. This minimises errors. Example
  • 9. Page 9 of 144 Paul Bolton 2012 Exercise 1.1 - Changing the text in a label control - Go to the Start Menu on the computer - Find Microsoft Visual Studio 2010 - Select Microsoft Visual Studio 2010 from the sub menu Once Visual Basic has opened select File / New Project from the menu Change the name of your application to LabelMessageYourName. So if your name is John Smith you would name your application LabelMessageJohnSmith Visual Studio will now load. This may take a few minutes, BE PATIENT. If you are asked which settings you would prefer, select Microsoft Visual Basic. Leave the template type selected as Windows Forms Application.
  • 10. Page 10 of 144 Paul Bolton 2012 (no spaces between the words). Click OK
  • 11. Page 11 of 144 Paul Bolton 2012 You should now see the Visual Basic design environment appear similar to the screen shown below. Take a few moments to familiarise yourself with the various features before continuing the exercise. If your screen does not look like the one shown below, tell your teacher. Tip: to make the windows stop disappearing, click the drawing pin symbol at the top of each window then becomes Click these two icons to alternate between the Form1 Design window and the Code window Solution Explorer windowControls Toolbox Menu Properties window Error List window Form Design window Exercise 1.1 (continued)
  • 12. Page 12 of 144 Paul Bolton 2012 The Form Designer Window is, as the name implies, where you design your visual interface. You can add controls from the Toolbox, on the left, onto your form. The title bar area shows you the name of your project and the name of the form currently displayed. Also shown in brackets is one of three words: Design, Run or Break. This shows the mode Visual Basic is operating in. Visual Basic operates in three modes.  Design mode - used to build application  Run mode - used to run the application  Break mode - application halted and debugger is available We focus here on the design mode. You should, however, always be aware of what mode you are working in. Now continue with Exercise 1. The finished program can be seen here: Designing the Form 1. Make sure Form 1 is selected and in the properties window change the Text property of the form to Change a message. lblMessage This button has been clicked to display the message above btnGoodMessage btnBadMessage How the program will work: When a button is clicked the message “I LIKE Visual Basic” appears. When a second button is clicked the message changes to “I HATE Visual Basic” Exercise 1.1 (continued) I LIKE Visual Basic
  • 13. Page 13 of 144 Paul Bolton 2012 2. Click on the Label control in the toolbox, and then with the mouse draw a rectangle in the upper part of the form (by holding down the left mouse button and dragging the mouse). 3. Find the label’s Name property in the Properties window and change it from Label1 to lblMessage, using the prefix ‘lbl’. Note that this prefix begins with the letter ‘l’for lion and not the number 1.(one) 4. Set the label’s Text property to blank by deleting the default value “Label1". 5. The default value for the label’s BorderStyle property is None, meaning that it has no border will be shown when the program runs. To get the sunken border effect in the illustration, change this to Fixed3D. 6. Set the label’s Font property to 14 Bold. 7. Set autosize to false 8. Set size width to 200 and height to 50 9. Drag a button from the Toolbox and draw a rectangle at the bottom left of the form. Set its Text property to Good Message. Change its Name property to btnGoodMessage. Now place a second button at the bottom right of the form. Set its Text property to Bad Message. Change its Name property to btnBadMessage. Coding 10.Double-click on the Good Message button and you’ll see the code template for its Click() event as shown below. The words after the brackets, Handles btnGoodMessage.Click, shows that the code you are about to write will be executed if the btnGoodMessage is clicked when the program is running. The code template plus any code that is written inside the template, is known as an event procedure. 11. Type the line of code below to set the Text property of the label to the message you wish to display in the label.
  • 14. Page 14 of 144 Paul Bolton 2012 12. Return to the form either by clicking the Form1.vb [Design] Page tab or the View Designer button in the Solution Explorer’s small toolbar (you will need to hover the mouse over the button to see its name. 13. Double-click the Bad Message button on the form. Type in a line of code similar to that in step 10 to display the “I do not like Visual Basic” message when the Bad Message button is clicked. Running the Program 14. Click the Start button on the toolbar or select Debug/Start from the menu. Click on each of the two buttons to check that the message changes. Close the program by clicking the red “X” in the top-right corner of the program window (i.e. the “form” you created) Saving the Program 15. Click the icon on the menu. In the Save Project window you should see LabelMessage automatically displayed as the application name. Don’t alter any of the entries. Just click the Save button. More on the VB Integrated Development Environment (IDE) Menu Bar Under the title bar is the Menu. This menu is dynamic, changing as you try to do different things in Visual Basic .NET. When you start working on a project, it should look like this: You will become familiar with each menu topic as you work through the course. Briefly, they are: File Use to open/close projects and files. Use to exit Visual Basic .NET Edit Used when writing code to do the usual editing tasks of cutting, pasting, copying and deleting text View Provides access to most of the windows in the Integrated Development Environment (IDE) Project Allows adding files and objects to your application Build Allows you to compile and run your completed application (go to Run mode) Debug Comes in handy to help track down errors in your code (works when Visual Basic .NET is in Break mode) Background information
  • 15. Page 15 of 144 Paul Bolton 2012 Team Ability to work in a Team Foundation Server Data Used when building database applications Format Useful for manipulating controls placed on your forms Tools Allows custom configuration of the IDE. Be particularly aware of the Options choice under this menu item. This choice allows you to modify the IDE to meet any personal requirements. Test Used for testing and debugging your applications Window Lets you change the layout of windows in the IDE Help Perhaps, the most important item in the Menu. Provides access to the Visual Basic on-line documentation via help contents, index or search. The View menu also allows you to choose from a myriad of toolbars available in the Visual Basic .NET IDE. Toolbars provide quick access to many features. The Standard (default) toolbar appears below the Menu: New project Open file Save all Undo, Re-do Move backward / forward Build configuration View Solution Explorer Window View Properties Window View Object Browser View Toolbox Team Explorer Window Start Page Extensions Command Window If you forget what a toolbar button does, hover your mouse cursor over the button until a descriptive tool tip appears. We will discuss most of these toolbar functions in the remainder of the IDE information.
  • 16. Page 16 of 144 Paul Bolton 2012 Toolbox The Toolbox is the selection menu for controls used in your application. It is active when a form is shown in the design window. The tools you will use most are found under the Windows Forms tab. Use the scroll arrows to scroll up and down the full list of controls. Many of these tools will look familiar to you. They are used in a wide variety of Windows applications you have used (the Visual Basic IDE even uses them!) We will soon look at how to move a control from the toolbox to a form. Background information (continued)
  • 17. Page 17 of 144 Paul Bolton 2012 Solution Explorer Window Two other windows (not illustrated) which are useful when running an application are the Task List Window and Output Window. The task list window highlights any errors encountered while trying to run an application. The window will direct you to the line(s) of code with identified errors. The output window outlines the steps followed as an application is compiled. Background information (continued) The Solution Explorer Window displays a list of all forms, modules and other files making up your application. To view a form in this window, simply double-click the file name. Or, highlight the file and press <Shift>-<F7>. Or, you can obtain a view of the Form or Code windows (window containing the actual Basic coding) from the Project window, using the toolbar near the top of the window. As we mentioned, there are many ways to do things using the Visual Basic IDE. The Properties Window is used to establish design mode (initial) property values for objects (controls). The drop-down box at the top of the window lists all objects in the current form. Two views are available: Alphabetic and Categorized (selection is made using menu bar under this box are the available properties for the active (currently selected) object. Help with any property can be obtained by highlighting the property of interest and pressing <F1>.
  • 18. Page 18 of 144 Paul Bolton 2012
  • 19. Page 19 of 144 Paul Bolton 2012 Standard naming conventions for controls List continued on next page lbl... btn... txt... mnu... chk... rad... grp... pic... pnl... dgd... lst... cbo... hsb... vsb... tmr... lblDisplay btnEnter txtInput mnuEditPaste chkBold radYellow grpFontSize picLogo pnlFontStyle dgdEmployees lstAge cboFavoriteFood hsbWidth vsbHeight tmrAnimate Type of control Prefix Example We name controls using the first 3 letters (the prefix) written in lowercase to represent what type of control it is. A list of prefixes is shown below. The rest of the name can be any meaningful word or combination of words representing what the control does. There must be no gaps in the name. We therefore start each word after the prefix with a capital letter. This is known as “camel-case”, because the middle of the name has taller (capital) letters, like the humps of a camel. For more information on Visual Basic naming conventions, go to: http://www.akadia.com/services/naming_conventions.html and scroll to the bottom of the page and find the heading: “12) Visual Control Type Notation” Background information (continued)
  • 20. Page 20 of 144 Paul Bolton 2012 We usually give dialogue controls these standard names rather than use different names for different applications – as we do with the other controls. This is because there is usually only one dialog control of each type on any of our forms. dlgOpenFile dlgSaveFile dlgFont dlgColor dlgPrint dlgPrintPreview Type of control Prefix AND Example (see explanation below) Background information (continued)
  • 21. Page 21 of 144 Paul Bolton 2012 The Visual Basic 2010 IDE – In depth Visual Basic is an integrated development environment within the Visual Studio. Net Framework. The visual environment is used to design, develop, debug and deploy Windows Forms and Web Forms applications. These applications can also be used to integrate database applications. The major advantage of this new environment is that multi-language applications can be used over the Internet, thus creating, in theory, a truly open application platform. In summary the visual studio has the following features: 1. Windows Forms Designer. A graphical design surface for creating GUI. You can drag & drop controls onto forms. 2. Tools for Windows Forms. A Windows Forms Designer, A Windows Application Template (e.g. windows or database application etc.), project references and generated starter code for the applications. 3. Tools for Web Forms. A Web Forms Designer, an ASP.Net Web Application template, project references and generated starter code. 4. Tools for XML (eXtendible Markup Language) Web Services. A generalised web language can be generated from your .net application solution file. 5. Multiple language Support. A range of language such as C# and VB.net can used in the same application or solution. The environment now has Object-Oriented Programming (OOP) capabilities. 6. Data Access. Components for creating applications that share data, visual database applications for accessing data using the ADO.NET classes. 7. Error handling. Has a range of debugging tools, classes and objects to find and fix errors within your application. 8. Wizards. Help you create common and complex tasks, by choosing options, configuring settings and customising projects. Background information (continued)
  • 22. Page 22 of 144 Paul Bolton 2012 Structure of a Visual Basic Windows Application We want to get started building our first Visual Basic Windows application. But, first we need to define some of the terminology we will be using. In Visual Basic .NET, a Windows application is defined as a solution. A solution is made up of one or more projects. Projects are groups of forms and code that make up some application. In most of our work in this course, our applications (solutions) will be made up of a single project. Because of this, we will usually use the terms application, solution and project synonymously. Thus an Application (Project) is made up of:  Forms - Windows that you create for user interface  Controls - Graphical features drawn on forms to allow user interaction (text boxes, labels, scroll bars, buttons, etc.) (Forms and Controls are objects.)  Properties - Every characteristic of a form or control is specified by a property. Example properties include names, captions, size, colour, position, and contents. Visual Background information (continued)
  • 23. Page 23 of 144 Paul Bolton 2012 Basic .NET applies default properties. You can change properties when designing the application or even when an application is executing.  Methods - Built-in procedures that can be invoked to impart some action to a particular object.  Event Procedures - Code related to some object or control. This is the code that is executed when a certain event occurs. In our applications, this code will be written in the BASIC language  General Procedures - Code not related to objects. This code must be invoked or called in the application.  Modules - Collection of general procedures, variable declarations, and constant definitions used by an application. Part 2 - Moving on from the Basics Consolidation exercises introducing Visual Basic Exercise 2.1  Start a new project.  Create a form with two labels. Exercises 2.1 to 2.4 Visual Basic uses a very specific directory structure for saving all of the components for a particular application. When you start a new project (solution), you will be asked for a Name and Location (folder / directory). A folder named Name will be established in the selected Location. That folder will be used to store all solution files, project files, form and module files (vb extension) and other files needed by the project. Two subfolders will be established within the Name folder: bin and obj. The bin folder contains your compiled application (the actual executable code or exe file). Later, you will see that this folder is considered the ‘application path’ when ancillary data, graphics and sound files are needed by an application. The obj folder contains files used for debugging your application as it is being developed.
  • 24. Page 24 of 144 Paul Bolton 2012  When the program runs display your name in label 1 and your address in label 2 by using the Form_Load() event. (Double-click on the grey area of the form at design time display the code window for this event.) Exercise 2.2  Start a new project.  Place a button on a form. When it is clicked the title bar of the form should display Welcome to Visual Basic .NET. Exercise 2.3  Start a new project. Public ClassForm1 Private SubForm1_Load(...) HandlesMyBase.Load lblName.Text = "MyName" lblAddress.Text = "MyAddress" End Sub End Class Public ClassForm1 Private SubbtnWelcome_Click(sender As System.Object, e As System.EventArgs) Handles btnWelcome.Click Me.Text = "Welcome to Visual Basic .NET" End Sub End Class
  • 25. Page 25 of 144 Paul Bolton 2012  Place two buttons on a form and set their Text properties to Show and Hide respectively using the Properties Window.  Place a label on the form and set its Visible property to False (which means it will be invisible when the program first runs).  Clicking the Show button should make the label visible and display the message Hello inside it. Clicking the Hide button should remove the label and its message. (Note: When you set the Visible property in code you do not need quotation marks around the True or False.) Exercise 2.4  Start a new project.  Write a program with a label and two buttons.Label width:200 height: 100  Clicking the ForeColour button displays the message shown in a blue colour. Clicking the BackColour button displays a different message and colours the rest of the label yellow. Note that the message is centred within the label. Use the label’s ForeColor and BackColor properties. To set these properties write Color.Blue or Color.Yellow to the right of the assignment statement ( = ). Public ClassForm1 Private SubbtnShow_Click(sender As System.Object, e As System.EventArgs) HandlesbtnShow.Click lblHello.Visible = True lblHello.Text = "Hello" End Sub Private SubbtnHide_Click(sender As System.Object, e As System.EventArgs) HandlesbtnHide.Click lblHello.Visible = False lblHello.Text = "Hello" End Sub End Class Public ClassForm1 Private SubbtnForeColour_Click(sender As System.Object, e As System.EventArgs) Handles btnForeColour.Click lblColour.Text = "MyForeColour propertyis set to blue" lblColour.ForeColor = Color.Blue End Sub Private SubbtnBackColour_Click(sender As System.Object, e As System.EventArgs)Handles btnBackColour.Click lblColour.Text = "MyBackColour propertyis set to yellow" lblColour.BackColor = Color.Yellow End Sub End Class
  • 26. Page 26 of 144 Paul Bolton 2012 Part 3 – Arithmetic & Variables Arithmetic Introductory Exercise 3.1 Introduction to data types We are going to look at how we can use the properties of controls to transfer information (data) from one control to another. The program we are about to create will enable us to: (1)assign a new BackColor property value (yellow) to a textbox on the left of the form by copying the existing BackColor property value from a textbox on the right (2) assign a new Text property value to a textbox on the left of the form by copying the existing Text property value from a textbox on the right (3) assign a new Text property value to a textbox on the left of the form by copying the existing Text property values from two textboxes on the right. We will see if we can get two numbers to add up using this technique (a simple maths calculation). Task 1 Open a new Windows Application project and create a form like the one illustrated: txtCopiedColour txtCopiedText txtResult btnCopyColour btnCopyText txtOriginalColour txtOriginalText Exercise 3.1
  • 27. Page 27 of 144 Paul Bolton 2012 At design-time, set the BackColor property of txtOriginalColour to yellow (select this from Custom on the BackColor property list). Double-click on the Copy Colour button. The code window should open revealing the template code for this button procedure ready for us to write code into. Write the following code shown in bold: Run your program, click the Copy Colour button an see if the yellow colour appears in the first textbox. If so, we have successfully assigned a new value to the BackColor property of the textbox on the left of the form by copying the existing BackColor property value from a textbox on the right. Task 2 Now see if you can complete the line of code for the next button, as shown below: Run your program again, write your name in the txtOriginalText textbox on the right, click the Copy Text button and see if your name appears in the txtCopiedText textbox on the left. Public ClassForm1 Private SubbtnCopyColour_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs)HandlesbtnCopyColour.Click txtCopiedColour.BackColor = txtOriginalColour.BackColor End Sub End Class btnAdd txtFirstNumber txtSecondNumber Private SubbtnCopyText_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs)HandlesbtnCopyText.Click txtCopiedText.Text = . End Sub Exercise 3.1
  • 28. Page 28 of 144 Paul Bolton 2012 Task 3 Repeat the process with the final button (“Add”). See if you can complete the line of code below: Run your program again, write your 2 whole numbers in the txtFirstNumber and txtSecondNumber textboxes on the right (e.g. 2 + 2), click the Add button and see if the correct answer appears in the txtResult textbox on the left. Observations Try to answer the following questions:  what result did you get in txtResult?  how do you think VB is processing the data you have input?  what data type do you think VB has assumed the number “2” is? Now look at the handouts / tutorials on data types and converting data types (“type-casting”) and see if you can work out what must be added to your code to cure the problem we are encountering. Private SubbtnAdd_Click(ByValsender As System.Object, _ ByVal e As System.EventArgs)HandlesbtnAdd.Click txtResult.Text = . End Sub
  • 29. Page 29 of 144 Paul Bolton 2012 Arithmetic & Variables: Underpinning Knowledge Data Types Data Type Usage Size (1 byte = 8 bits) To store numeric data Short (or Int16) (“Shortinteger”) Wholenumbersonly Can hold whole numbers(positiveor negative) between approx +32,000 to -32,000 2 bytes (i.e. 16 bits) Integer (or Int32) Can hold whole numbers(positiveor negative) between approx +2 billion to -2 billion (i.e. +2 followed by 9 zeros or -2 followed by 9 zeros) 4 bytes (i.e. 32 bits) Long(or Int64) (“Long integer”). Can hold whole numbers(positiveor negative) between approx +9 (followed by18 zeros) to -9 (followed by18 zeros) 8 bytes (i.e. 64 bits) Single (“Single-precisionfloating- point”) WholeORdecimalnumbers Can hold whole numbersORnumberscontaininga decimalpoint (positiveor negative) Therangeof values which can bestored forpositivenumbersis approximately:+3 (followed by38 zeros) for verylarge values, to +0.0 (followed by45 zerosand then 1) for very small values. For negativenumbers,therangeis approximately:-3 (followed by38 zeros) for verylarge values, to -0.0 (followed by45 zerosand then 1) for very small values. 4 bytes Double (“Double-precision floating- point”) Can hold whole numbersORnumberscontaininga decimalpoint (positiveor negative) Therangeof values which can bestored forpositivenumbersis approximately:+1 (followed by308 zeros) for verylarge values, to +0.0 (followed by324 zerosand then 4) for verysmallvalues. For negativenumbers,therangeis approximately:-1 (followed by308 zeros) for verylarge values, to -0.0 (followed by324 zerosand then 4) for verysmallvalues. 8 bytes Decimal Can hold numberscontainingadecimalpoint (positive or negative) between approx +7 (followed by28 zeros) to -7 (followed by28 zeros) 16 bytes To store other data Boolean Otherdata Used to hold True or False 2 bytes Date Can hold datesfromJanuary1,0001to December 31, 9999,and timefrom00:00:00to 23:59:59 8 bytes String Used to hold characters(e.g.all theletters & symbolson the keyboard and numbers 0-9,butNOTif thenumbers are to be used in calculations). Variable size Object An object variable holds a referenceto an object,notthe objectitself. Thereforethe variableonlyneeds a small amountof memory. In theory,any data typecan be stored in an objectvariable. 4 bytes Background information
  • 30. Page 30 of 144 Paul Bolton 2012 Arithmetic Exercise 3.2 Declaring variables & type casting Task 1 We are going to create a simple calculator. Open a new Windows Application project and create a form like the one illustrated: Give the buttons suitable names (e.g. btnAdd, btnSubtract etc.). Give the textboxes the names txtFirstNumber, txtSecondNumber and txtResult respectively. Double-click on the Add button. The code window should open revealing the template code for this button procedure ready for us to write code into: Move the cursor and insert it between the line: Public Class Form1 and the line: Private Sub btnAdd_Click(…) and then write the following code: Public ClassForm1 Private SubbtnAdd_Click(ByValsender As System.Object, _ ByVal e As System.EventArgs)HandlesbtnAdd.Click | End Sub End Class Cursor Public ClassForm1 'declare variables Dim intFirstNumber As Integer Dim intSecondNumber As Integer Dim intResult As Integer Private SubbtnAdd_Click(ByValsender As System.Object, _ ByVal e As System.EventArgs)HandlesbtnAdd.Click End Sub End Class Cursor Exercise 3.2
  • 31. Page 31 of 144 Paul Bolton 2012
  • 32. Page 32 of 144 Paul Bolton 2012 You will notice that the above process is in 3 main steps: (1) Input (where the numbers typed by the user are stored into variables) (2) Calculation (where we use the variables to do the arithmetic) (3) Output (where we display the result into a text box) This is a sequence we will use again and again in our programming projects. We have declared three variables of Integer type – intFirstNumber, intSecondNumber and intResult. We want the program to accept two whole numbers (integers) in txtFirstNumber and txtSecondNumber and then perform the calculations indicated by the buttons. In order to do this we need to: (1) store the two values which the user has typed into txtFirstNumber and txtSecondNumber into our variables intFirstNumber and intSecondNumber. (2) do the arithmetic and then store the result into the variable intResult. (3) display the result. For this we need to change the .Text property of txtResult to the value held in intResult. Add the code below to the _Click() event procedure of btnAdd: HINT Public ClassForm1 'declare variables Dim intFirstNumber As Integer Dim intSecondNumber As Integer Dim intResult As Integer Private SubbtnAdd_Click(ByValsender As System.Object, _ ByVal e As System.EventArgs)HandlesbtnAdd.Click 'INPUT 'load contents of 1st textbox into 1st variable intFirstNumber = txtFirstNumber.Text 'load contents of 2nd textbox into 2nd variable intSecondNumber = txtSecondNumber.Text 'CALCULATION 'add 2 variables and load result into 3rd variable intResult = intFirstNumber + intSecondNumber 'OUTPUT 'display contents of 3rd variable in 3rd text box txtResult.Text = intResult End Sub End Class Exercise 3.2
  • 33. Page 33 of 144 Paul Bolton 2012 Run you program, enter two numbers and click the add button. See if the correct answer appears in txtResult. Task 2 We have relied upon Visual Basic automatically converting data into the appropriate data types for us. For example, it took the text from the first textbox (a String data-type) and converted it into an Integer before adding it to the second number. This is data-type conversion is known as type casting. We are now going to do this with functions in our code. Add the following statement to the top of your code: You will immediately see parts of the code underlined in blue and errors appear in the Error List Window. To solve this problem we need to convert the data-type of the numbers from String to Integer in the first button (btnAdd) by including the conversion function CInt(). Amend you code as follows: Run your program, enter two numbers and click the add button. See if the correct answer appears in txtResult. Task 3 So far we have used the + operator to add the two numbers together. The other operators that we can use are: Option Strict On Public ClassForm1 'declare variables Dim intFirstNumber As Integer Dim intSecondNumber As Integer Dim intResult As Integer Private SubbtnAdd_Click(ByValsender As System.Object, _ ByVal e As System.EventArgs)HandlesbtnAdd.Click End Sub End Class Private SubbtnAdd_Click(ByValsender As System.Object, _ ByVal e As System.EventArgs)HandlesbtnAdd.Click 'INPUT 'load contents of 1st textbox into1st variable intFirstNumber = CInt(txtFirstNumber.Text) 'load contents of 2ndtextbox into2ndvariable intSecondNumber = CInt(txtSecondNumber.Text) Exercise 3.2
  • 34. Page 34 of 144 Paul Bolton 2012 + Add - Subtract / Divide * Multiply MOD Modulus ^ Raise to the power of Now add sections of code to perform the correct arithmetic for each of the buttons shown in the example. (Note: we cannot use the % symbol to calculate percentages. Instead we must divide the first number by the second number and then multiply by 100.) Task 4 Cint() is a function that converts text, provided it is a numeric, to Integer data format. There are other function like this. To find out about them read the Background Information on the next page. (If Online Help is available on your computer, you can also highlight CInt() and then press the F1 key.) Test your program with numbers like 350 and 260.You will get overflow. Now try using Long instead of Integer in your Dim statements. You will need to change the CInt() functions to CLng() Try dividing 13 by 2. You won’t get the right answer. Use Single instead of Long in your Dim Statements. (Again you will have to change the conversion function – use the help facility to look up what you need to use or read the next page on this subject.) Exercise 3.2
  • 35. Page 35 of 144 Paul Bolton 2012 Arithmetic, Data-Types & Variables Converting data before storing it into variables (known as data “Type Casting”) So far we have looked at how to declare a variable and store data into it. For example, suppose our user is going to type the number “123” into a text box called txtFirstNumber. We want to write code which will store this number into a variable called intFirstNumber and then do a maths calculation with it. To do this we would: (1)declare the variable: Dim intFirstNumber As Integer (2) then store the data into it by writing: intFirstNumber = txtFirstNumber.Text But this does not actually convert the string “123” into numbers which our program can use to do maths with. Remember that because the number is in a text box, Visual Basic does not automatically recognise that this is a number. It assumes the number is a series of characters (a “string”) like a telephone number or bank account number. If we try to get VB to add 1 to this string, we will probably get the answer 1231 instead of 124. VB will simply put the 1 on the end of 123 like a putting letter on the end of a word. Declaring a variable as an Integer type does not convert the data to an integer, it simply puts a “filter” over the variable so that it refuses to accept anything but an integer! So if we try to store the decimal number 0.75 into it we will simply get an error message. Therefore we need to use a function to convert the data in the text box into the correct data type before we try to store it into the variable. To do this we use one of the following data type conversion functions, for example: Numeric data types: CShort( ) to convert to Short data type CInt( ) to convert to Integer data type CLng( ) to convert to Long data type CSng( ) to convert to Single data type CDbl( ) to convert to Double data type CDec( ) to convert to Decimal data type (used especially for currency data) Otherdata types: Background information
  • 36. Page 36 of 144 Paul Bolton 2012 CBool( ) to convert to Boolean data type (True / False) CDate( ) to convert to Date / Time data type (e.g. #17/10/06 13:50:02#) CStr( ) to convert to String data type (e.g. "My name is John") For example, to convert the string “123” contained in text box txtFirstNumber into an integer and then store it into our variable, we would write: intFirstNumber = CInt(txtFirstNumber.Text) We need to be careful however, because if the data doesn’t exactly match the data type, VB will do its best to convert it anyway. For example, if we write the above code and the user writes the string 12.75 into the text box, the integer 13 will be stored in the variable intFirstNumber. In other words the 0.75 part of the number will simply be rounded up to the next whole number. (Note: if we actually wanted to store decimal numbers we would need to declare the data type of our variable as a single and use the conversion function CSng() instead.) Part 4 - More on Arithmetic & Variables Arithmetic Exercise 4.1 Introducing the scrollbar control Create a form like the one above. The aim of the program is to allow the user to convert temperatures from Farenheit into Celsius by moving the scroll bar. The Farenheit temperature values will range from –60 to +120. (Moving the scroll bar thumb upwards should increase the temperature values.) Set the initial Text property of txtTempF and txtTempC to 32 and 0 respectively, and the Value of the scroll bar to 32. txtTempF txtTempC vsbTemperature Exercise 4.1
  • 37. Page 37 of 144 Paul Bolton 2012 (a) From the above information work out what the Min and Max property values of the scroll bar should be. (Remember that for vertical scroll bars the Min property always corresponds to the topmost position of the thumb!) (b) Write code into the scrollbar _Scroll(...) event which will take the Farenheit value displayed in txtTempF, convert it to Celsius and display it in txtTempC. The conversion formula is: Celsius = (Farenheit – 32) x 5 /9 Public ClassForm1 Dim intTempF As Integer 'declare variables Dim intTempCAs Integer '---------------------------------------------------------------------------- Private SubvsbTemperature_Scroll(ByVal sender As System.Object, _ ByVal e As System.Windows.Forms.ScrollEventArgs)HandlesvsbTemperature.Scroll 'store value of scrollbar intoF variable intTempF= vsbTemperature.Value 'convert F value to stringanddisplayinF textbox txtTempF.Text = CStr(intTempF) 'calculate Cvalue, convert to integer and store inCvariable intTempC= CInt((intTempF - 32) * 5 / 9) 'convert Cvalue to string anddisplayin Ctextbox txtTempC.Text = CStr(intTempC) End Sub '------------------------------------------------------- End Class Scroll bar property settings required to achieve full temperature range displayed: Vertical scroll bar (vsbTemperature) Min:120 Max:-60 Small change:1 Large change:10 Value:32
  • 38. Page 38 of 144 Paul Bolton 2012 Scrollbar Setting scrollbar properties A scroll bar returns a numeric value depending on the position of the slider or (“thumb”). Scroll bars are quite complex because they have 5 main properties to set and 2 events to code in order for them to work properly. The 5 properties are listed below: Property Horizontal ScrollBar Vertical ScrollBar Max the value returned when the slider is at the right hand end of the ScrollBar The value returned when the slider is at the bottom of the ScrollBar Min the Value returned when the slider is at the left hand end of the ScrollBar The Value returned when the slider is at the top of the ScrollBar Large Change The amount by which the Value property is changed when the user clicks on the grey area between the slider and either end of the ScrollBar. Small Change The amount by which the Value property is changed when the user clicks on the arrows at either end of the ScrollBar Value This returns an integer which indicates the position of the slider in terms of the range set by Max and Min. slider or “thumb” clicking here affects SmallChange property clicking here affects SmallChange property clicking here affects LargeChange property Background information
  • 39. Page 39 of 144 Paul Bolton 2012
  • 40. Page 40 of 144 Paul Bolton 2012 (1) Setting Max and Min properties We set Max and Min to suit the application we are using. For example, if we wanted to use a scroll bar to input the temperature of a pan of water in degrees Celsius we would set the Min property to 0 and the Max property to 100 to correspond to the freezing and boiling point of water. When you first draw a scroll bar on your form the default value of Min is 10 and Max is 100. Note that with vertical scroll bars, the Min value is always returned when the thumb is at the top. Therefore it is quite common for the Min value to be set greater than the Max value when using vertical scroll bars. (2) Setting SmallCange and LargeChange properties There are no rules governing what values you should set the SmallChange and LargeChange properties to. However, by default the SmallChange property is set to 1 when you first draw the scroll bar, and the LargeChange property is set to 10. This means that if the range of the scrollbar (i.e. the Max value minus the Min value) is quite large the thumb will move incredibly slowly when the user clicks on the arrows. Therefore it is very important that you set these properties to values which will give reasonable travel of the thumb. As a rough guide, set the LargeChange property to one tenth of the range value, and set the SmallChange property to one tenth of the LargeChange property. Note: The ratio of LargeChange property to the range also affects the length of the thumb. The thumb is lengthened to restrict the distance it travels, as shown in the diagram below: In this example the Min property is set to 0 and the Max is 100, meaning that the range is 100. If the LargeChange property is left at the default value of 10, the thumb remains quite small. However, if the LargeChange property is increased to 50, the size of the thumb increases to one third the length of the scroll bar, since it only requires 2 clicks to move the thumb to its maximum value. (The value is taken from the position of the left edge of the thumb.) Size of the thumb when LargeChange property is set to 1:Min = 0 Max = 100 Background information
  • 41. Page 41 of 144 Paul Bolton 2012 Size of the thumb when LargeChange property is set to 50 on the same scroll bar: (3) Setting Value property This is the initial value of the scroll bar at run-time, and hence determines the initial position of the thumb. The Value property must be within the range of the Max and Min properties. Often the Value property will be the same as the Min property so as to put the thumb at one end of the scrollbar, but this is not always the case. Scrollbars Summary of features  The purpose of a scrollbar is to generate numbers which we can use elsewhere in our program  We can use these numbers to: o change the value of properties of other controls o perform calculations  We use the scrollbar’s value property as the source of these numbers  As the user clicks the scrollbar arrows (or drags the scrollbar slider) the value of the scrollbar changes  We control what range of values will be generated by setting the Max and Min properties of the scrollbar at design time  We can decide where the position of the slider is when the program first opens by setting the scrollbar’s value property at design time (but this initial value must lie somewhere between the Max and Min values) Min = 0 Max = 100 (position allows for width of thumb)
  • 42. Page 42 of 144 Paul Bolton 2012  We can decide how quickly the value of a scrollbar changes when the user clicks the scrollbar arrows (or drags the scrollbar slider). We do this by setting the: o SmallChange and o LargeChange properties  (As a guide, set the LargeChange property to 1/10th the value of the Max property, and set the SmallChange property to 1/10th the value of the LargeChange property)  when the user clicks the scrollbar arrows or drags the scrollbar slider it fires the _Scroll(...) event
  • 43. Page 43 of 144 Paul Bolton 2012 Arithmetic Exercise 4.2 – Wallpaper Estimator Data types, arithmetical operators & variables In this exercise we will be revising what we have covered so far on:  data types  converting data to different types (known as “type casting”)  declaring variables of appropriate data types  arithmetical operator precedence using the common operators: Your task is to estimate the amount of wallpaper required to cover the wall illustrated below which has one window. The wallpaper comes in rolls 0.7 metres wide and 10 metres long. Cost per roll is £8.00 Your task is to calculate and display: 4.5m 3m 4.5m2.5m 1.5m Area A Area B Area C Area D 0.5m Order of precedence: (1)( ) brackets (parentheses) (2) ^ exponentiation (“power of”) (3) + - positive & negative signs (4) * / multiplication & division (5) integer division (gives only whole number result of Exercise 4.2
  • 44. Page 44 of 144 Paul Bolton 2012  the number of rolls required  the total cost of wallpaper  the relative cost of wasted wallpaper left over from the last full roll (e.g. if half a roll was left over, we could say that £4.00 worth of wallpaper was wasted) Assume the wallpaper pieces can be pasted in any sequence / orientation irrespective of where the joins occur, and that there is no wastage due to overlap or off-cuts. In other words, assume the total area of one roll covers exactly the same amount of area of the wall.
  • 45. Page 45 of 144 Paul Bolton 2012 (1) Find total area of wall Here are some tips on how to calculate the total area of the wall. After reading the tips, try to create one line of code in your program which uses all the measurements and stores the answer in a variable sngWallArea. Area A: height * width 3m * 4.5m = 13.5 square meters Area B is the same, so multiply the area of A by 2 Area C: height * width 0.5m * 2.5m = 1.25 square meters Area D: We haven’t been told the height but we can work it out by subtracting the height of the window plus the height of Area C from the height of the room. Once we have found this we multiply height * width as usual to find the area of D. Finally, Total Area = Area A + Area B + Area C + Area D Here is the start of the code you will need. The figures calculating Areas A & B have been written for you already. See if you can finish off the line. Be careful to remember the rules about operator precedence and use parentheses (brackets) if necessary: sngWallArea = ((3 * 4.5)*2) + (2) Find area of one roll of wallpaper Area of one roll = length * width = 10 * 0.7 = 7 square meters Again, here is the start of the code you will need: Exercise 4.2 (continued)
  • 46. Page 46 of 144 Paul Bolton 2012 sngOneRollArea = (3) Find number of whole rolls needed (4) (a) Find area of wallpaper roll left over (4) (b) Find length of wallpaper roll left over (5) Find cost of total wallpaper rolls purchased (6) Find relative cost of fraction of wallpaper roll left over
  • 47. Page 47 of 144 Paul Bolton 2012 Public ClassForm1 Dim sngWallArea As Single Dim sngOneRollArea As Single Dim intNoOfRolls As Integer Dim sngRemainderAreaOfRoll As Single Dim sngRemainderLengthOfRoll As Single Dim decCostOfWallpaperPurchased As Decimal Dim decCostOfWallpaperWasted As Decimal Private SubbtnCalculate_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnCalculate.Click '(1) calculate total area of wall sngWallArea = ((3 * 4.5) * 2) + (0.5 * 2.5) + ((3 - (1.5 + 0.5)) * 2.5) MsgBox("Wall area is:" & sngWallArea & " square metres") '(2) calculate area ofone rollof wallpaper sngOneRollArea = 0.7 * 10 MsgBox("Area of one roll is:" & sngOneRollArea & " square metres") '(3) calculate number ofwhole rolls ofwallpaper needed intNoOfRolls = (sngWallArea sngOneRollArea)+ 1 MsgBox("Noof rollsneededis:" & intNoOfRolls) '(4)(a) calculate fractionarea ofroll left over sngRemainderAreaOfRoll = sngWallArea ModsngOneRollArea MsgBox("Area of roll left over is:" & sngRemainderAreaOfRoll & " sq m") '(4)(b) calculate length ofroll left over sngRemainderLengthOfRoll= sngRemainderAreaOfRoll / 0.7 MsgBox("Length ofroll left over is:" & sngRemainderLengthOfRoll & " m") '(5) calculate total cost ofwallpaper decCostOfWallpaperPurchased= intNoOfRolls * 8.0 MsgBox("Cost ofwallpaper purchased:£" & decCostOfWallpaperPurchased) '(6) calculate relative cost ofwallpaper wasted decCostOfWallpaperWasted = sngRemainderLengthOfRoll* 8.0 / 10 MsgBox("Relative cost ofwallpaper wasted:£" & decCostOfWallpaperWasted) End Sub Solution to Exercises 4.2
  • 48. Page 48 of 144 Paul Bolton 2012 Part 5 - Making selections using If..Then..Else Program Control – making selections using “If..Then..Else” So far we have only written code for a sequence of actions for any one event. However, in many programs we need to make selections according to certain criteria. In other words, make a decision. For example, imagine we were shopping for a new mobile phone, and we could spend up to £100. In our minds we would be performing the following test as we browsed the shops looking at all the different phones on offer: If the phone costs up to £100, then Ask the shop assistant for more details about the phone Else Look for a different phone End of decision We could write this process into Visual Basic code. If the cost of the mobile phone was stored in a variable called decCost, we could write: If decCost < 101 Then txtMessage.Text = "Make further enquiries" Else txtMessage.Text = "Look for a different phone" End If The general way this code structure works is: If a certain condition is true Then Do this action Else Do this other action End If The code written between “If” and “Then” is a condition. A condition is an expression which may be considered to be either “True” or “False”. If the condition is “True” then the code up to “Else” is carried out. If the Condition is false, then the code between “Else” and “End If” is carried out. Background information
  • 49. Page 49 of 144 Paul Bolton 2012 Notice that if the condition is False (that is, if the mobile phone does not cost up to £100), we don’t have to test the condition again. If the phone does not cost up to £100, then logically it must cost more than £100, and the code underneath the “Else” will run. Also, the Else is optional. Sometimes, depending on our program, we don’t need to write any code dealing with an Else condition. < less than > greater than = equal to <> not equal to >= greater than or equal to <= less than or equal to In our code have used the “ < “ symbol which means “less than”. This is known as a relational operator, because it compares one value with another. The full list of relational operators is:
  • 50. Page 50 of 144 Paul Bolton 2012 Going back to our example of buying a mobile phone, let’s suppose we wanted to avoid buying very cheap phones because they wouldn’t have all the features we are looking for. Suppose we didn’t want to look at any phones which cost less than £50. We could amend our code as follows: If decCost > 50 And decCost < 101 Then txtMessage.Text = "Make further enquiries" Else txtMessage.Text = "Look for a different phone" End If The And is known as a logical operator. The full list of logical operators is as follows: Finally, it is important to realise that in our programs we may be making decisions which have more than 2 outcomes. In the mobile phone example, we are either doing one thing or another. We are: either making further enquiries or looking for a different phone But often there will be more than 2 possible courses of action. Suppose we would consider placing a deposit on the phone if it was outside our price range but had an internet facility. (Perhaps we would save up and pay for the phone next month.) Our decision process would look like this: If the phone costs between £50 and £100, then Ask the shop assistant for more details about the phone ElseIf the phone has an internet facility, then Place a deposit Else Look for a different phone End of decision And This means both conditions must be True for the entire condition to be True Or This means if one or both conditions are True, the entire condition is True Not This reverses the condition so that a True condition will evaluate False, and vice versa. Background information (continued)
  • 51. Page 51 of 144 Paul Bolton 2012 The code for the above process could be written as follows. (The answer to whether the phone has an “internet facility” is stored in a “Yes/No” variable called “blnInternet”): If decCost > 50 And decCost < 101 Then txtMessage.Text = "Make further enquiries" ElseIf blnInternetFacility = True Then txtMessage.Text = "Place a deposit" Else txtMessage.Text = "Look for a different phone" End If We can write as many ElseIf tests as we want to, and each one can result in a different course of action. Tax Calculator Program - Scenario Read the scenario below and then try to carry out the exercises on the following pages. Part (a) A wages department wants you to create a program to help them calculate their employees’ pay. At the moment this calculation is done on a hand-held calculator. They want the program to run as follows: (1)The wages clerk will type in the Gross Pay and the Tax Allowance for an employee. (The clerk does not need to type in the employee’s name, just the figures.) (2) When the clerk clicks the “Calculate” button, the program will display the Tax Payable and the Net Pay. (3) The clerk will then write down the Net Pay for the employee and then type in figures for the next employee. The Rate of Tax is 25%. The Tax Payable is calculated by the following equation: Tax Payable = (Gross Pay – Tax Allowance) x Rate of Tax Exercises 5.1 – 5.3
  • 52. Page 52 of 144 Paul Bolton 2012 Because the wages need to be calculated quickly, the wages clerk does not want to have to use the mouse on the computer. So the program must run by using only the computer keyboard. You will therefore need to think about: - how to get the cursor to move about the screen in the right order, and - how to clear any text boxes after the wages clerk has processed the figures for one employee and wants to enter details for the next employee. Part (b) Once you have demonstrated that the program works to their satisfaction, the wages department want you to amend the program so that the wages clerk only has to use the numeric keypad on the keyboard. Part (c) Finally, the wages department will want you to restrict access to the program by creating a password system. When the program first opens there should be a Password Form which invites the wages clerk to enter a password into a text box. If the correct password is entered, the Tax Allowance Calculator form you created in Parts (a) and (b) should open. If an incorrect password is entered, the program should display a message stating that the password is incorrect, the text box on the password form should clear and the cursor return to the text box. If an incorrect password is entered for a total of 3 times, a message should be displayed that the program is shutting down, and the program should terminate.
  • 53. Page 53 of 144 Paul Bolton 2012 If…Then…Else - Exercise 5.1 - Tax Calculator In this exercise we will be looking at the following topics:  making selections using If…Then…Else statements  relational operators such as “>” (“greater than”)  declaring constants  drawing Group boxes  using data-type conversion function to convert String data to decimal Create a new project and draw group boxes, labels, text boxes and buttons on the form as shown below: The aim of the program is that the user should be able enter values into txtGrossPay and txtTaxAllowance. When the Calculate button is clicked, the program should calculate and display the Tax Payable and Net Pay. For this exercise we are assuming the Tax Rate is 25%. The Tax Payable is therefore calculated by subtracting the Tax Allowance from the Gross Pay, and then finding 25% of the remainder. txtGrossPay txtTaxAllowance txtTaxPayable txtNetPay grpInput grpOutput btnCalculate Exercise 5.1
  • 54. Page 54 of 144 Paul Bolton 2012 For example, if the Gross Pay is £200 and the Tax Allowance (the amount of wage which is free of tax) is £100, the Tax Payable would be £25 and the Net Pay would be £175.
  • 55. Page 55 of 144 Paul Bolton 2012 First, we need to declare 4 variables in which to store the input data (Gross Pay and Tax Allowance) and the output data (Tax Payable and Net Pay). The data- type Decimal is the best one to use for currency data. In the code window, declare the following variables as Decimal by writing: Note that when we declare variables in this place (just below the line Public Class Form1) they are available for use in any procedure in the form (e.g. code written behind any button). Because the form is technically known as a module, variables declared here are known as module-level variables. Since the Tax Rate is going to remain constant throughout our calculations, we can declare it as a constant. (A constant is similar to a variable, except that its value does not change during the life of the program.) We usually write the names of constants in CAPITAL letters, separated by an underscore if there is more than one word. Because Tax Rate is a decimal number it is best to store it in a variable of data-type: Single. We would therefore name the constant SNG_TAX_RATE and declare it follows: Note that when we declare constants we must assign a value to them in the same line of code. Writing 0.25 is the same as writing 25% or 25/100. Remember, we cannot write 25% in VB code. Public ClassForm1 Dim decGrossPay As Decimal 'declare variables Dim decTaxAllowance As Decimal Dim decTaxPayable As Decimal Dim decNetPay As Decimal Const SNG_TAX_RATE As Single = 0.25 'declare constant Point to note Exercise 5.1 (continued)
  • 56. Page 56 of 144 Paul Bolton 2012 Next we need to write code into btnCalculate which carries out the following steps: Input Gross Pay and Tax Allowance data from text boxes and store into 2 variables Calculate Tax Payable as follows: If Gross Payis greater thanTax Allowance Then Tax Payable = (Gross Pay – Tax Allowance)x Tax Rate whichis 25% Else Tax Payable = 0 Calculate Net Pay as follows: Net Pay= Gross Pay– Tax Payable Output Tax Payable by displaying in text box txtTaxPayable Output Net Pay by displaying in text box txtNetPay The “>” symbol means “greater than”, and it is one of the many relational operators we can use to compare values in the If…Then…Else statements. The full list of relational operators is as follows: < less than > greater than = equal to <> not equal to >= greater than or equal to Note: the code for calculating the Tax Payable is as follows: If decGrossPay > decTaxAllowance Then decTaxPayable= (decGrossPay - decTaxAllowance) * SNG_TAX_RATE Else decTaxPayable= 0 End If Exercise 5.1 (continued)
  • 57. Page 57 of 144 Paul Bolton 2012 Try to work out the rest of the code for btnCalculate yourself. Remember that when data is written in textboxes it is String data-type by default. We therefore need to convert this to Decimal data-type when it is input to the two variables using the CDec( ) function.
  • 58. Page 58 of 144 Paul Bolton 2012 If…Then…Else - Exercise 5.2 Tax Calculator Enhancements In this exercise we will be looking at the following topics which will protect the data to processed and make our program more user friendly:  Setting the TabIndex property  Using the .Focus() method to move focus to a textbox or button  Enabling / disabling textboxes using .Enabled = True / False  Formatting output textboxes by using Format(... ,"Currency") function  Re-formatting input textboxes by using this same function  Using the .Clear() method to clear a textbox  Using the _LostFocus(...) event to run code (a) Using the TabIndex property We want to make the program user friendly by arranging it to work without the user having to use the mouse. We can arrange that the Tab key on the keyboard will move the focus from one control to another in any order we choose. We do this by setting the TabIndex property of the controls at design time. Set the TabIndex of the following controls and check the results when running your program: Control name TabIndex Result value txtGrossPay 1 Puts cursor in text box when form loads txtTaxAllowance 2 Puts cursor in text box after pressing Tab key btnCalculate 3 Sets focus to command button after pressing Tab key so that user only needs to press Enter key to “Click” the command button (b) Providing a “Clear” button and improving navigation We want to make it easier for the user to re-set the form after they have performed one calculation. Draw another button on the form, set its Text property to “Clear” and name it btnClear. Double-click it and write the following code in its Click event procedure: PrivateSub btnClear_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnClear.Click txtGrossPay.Clear() 'clear textbox entries txtTaxAllowance.Clear() Exercise 5.2
  • 59. Page 59 of 144 Paul Bolton 2012 Run your program, enter some data in the first two textboxes and check that both buttons work as expected. (c) Protecting data and improving navigation There is an easy way to provide guidance to the user about which controls to use, and that is by disabling controls in a set order in response to the user’s actions. This technique can also be used to protect data. Double-click on the form itself and write the following code in the Form_Load() event procedure: Can you think of similar code you need to write in the btnCalculate_Click() and btnClear_Click() event procedures? PrivateSub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load txtTaxPayable.Enabled = False 'disabletextboxes txtNetPay.Enabled = False End Sub Exercise 5.2 (continued)
  • 60. Page 60 of 144 Paul Bolton 2012 If…Then…Else – Exercise 5.3 Tax Calculator – adding a password form In this exercise we will be looking at the following topics:  Making further selections using If…Then…ElseIf…Else statements  Incrementing counter variables using the += operator  Using .Show() and .Hide() methods with forms  Using .Clear() and .Focus() methods with controls We are going to enhance the program we created earlier to incorporate a password protection system. When the program first opens there should be a Password Form which invites the user to enter a password into a text box. Feature A: If the correct password is entered, the Tax Calculator form we created in Exercise 5.1 should open. If an incorrect password is entered, the program should display a message stating that the password is incorrect, the text box on the password form should clear and the cursor return to the text box. Feature B: If an incorrect password is entered for a total of 3 times, a message should be displayed that the program is shutting down, and the program execution should terminate. Task 1 Add a new form to your project by Clicking Project / Add Windows Form… on the top menu of the design window. Accept the name of the new form as Form2 Resize the form so that it resembles the size of a logon screen and draw the controls as illustrated: To create Feature A described above, add the following code to the OK button’s Click() event. Run your program and check if it works as expected by entering an incorrect password and clicking “OK”, then the correct password (“tax”) and clicking “OK”. Private SubbtnOK_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnOK.Click 'if password correct If txtPassword.Text = "tax" Then 'display message MsgBox("Access to Tax Calculator permitted.") 'show Tax Calculator form txtPassword btnOK Exercise 5.3
  • 61. Page 61 of 144 Paul Bolton 2012 Task 2 To create Feature B we need to amend the code we have just written so that if an incorrect password is entered for a total of 3 times, a message should be displayed that the program is shutting down, and the program execution should terminate. We need to create a variable which will keep a tally of the number of times the OK button has been clicked, then add an ElseIf statement to our If…Then…Else construction to add further conditions to the decision-making process. Add/amend the following code shown in bold and highlighted below. (Note: Be careful to declare the variable intAttemptNumber outside the btnOK_Click() procedure. If you declare it inside the procedure, it won’t hold its value between button clicks and won’t count up the number of incorrect password attempts.) Public ClassForm2 Dim intAttemptNumber As Integer Private SubbtnOK_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnOK.Click 'increment counter to store number of attempts intAttemptNumber += 1 'if passwordcorrect If txtPassword.Text = "tax" Then 'displaymessage MsgBox("Access to Tax Calculator permitted.") 'showTax Calculator form Form1.Show() 'and hide Passwordform Me.Hide() 'else if attempt number lessthan3 ElseIf intAttemptNumber < 3 Then 'displaymessage MsgBox("Password incorrect. Please re-type password.") 'clear text box txtPassword.Clear() 'and put cursor back in text box txtPassword.Focus() Else 'else display message Exercise 5.3 (continued)
  • 62. Page 62 of 144 Paul Bolton 2012 Further study Can you think how to incorporate the number of incorrect attempts into the message displayed to the user, like this:
  • 63. Page 63 of 144 Paul Bolton 2012 Public Class Form1 Dim decGrossPay As Decimal 'declare variables Dim decTaxAllowance As Decimal Dim decTaxPayable As Decimal Dim decNetPay As Decimal Const SNG_TAX_RATE As Single = 0.25 'declare constant '--------------------------------------------------------------------- Private Sub btnCalculate_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnCalculate.Click '(1) INPUT from textboxes into variables: '**************************************** decGrossPay = CDec(txtGrossPay.Text) 'store Gross Pay decTaxAllowance = CDec(txtTaxAllowance.Text) 'store Tax Allowance '(2) CALCULATE using only variables: '*********************************** '(a) calculate Gross Pay If decGrossPay > decTaxAllowance Then 'if Gross Pay > Tax Allowance decTaxPayable = _ (decGrossPay - decTaxAllowance) * SNG_TAX_RATE 'calculate Tax Payable Else decTaxPayable = 0 'else Tax Payable = 0 End If '(b) calculate Net Pay decNetPay = decGrossPay - decTaxPayable 'calculate Net Pay '(3) OUTPUT from variables to textboxes '************************************** txtTaxPayable.Text = decTaxPayable 'output Tax Payables txtNetPay.Text = decNetPay 'output Net Pay End Sub '--------------------------------------------------------------------- End Class Solution to Exercise 5.1
  • 64. Page 64 of 144 Paul Bolton 2012 Part 6 - More on making selections using If..Then..Else Sports Club Membership Fees Program - Scenario Part (a) – creation of basic program A newly-opened local sports club wants has ask you to create a program to help them display the difference subscription fees payable by new members. There are 3 rates:  Full rate (“F”) is £100  Senior rate (“S”) is £75  Junior rate (“J”) is £50 The club wants you to create a program to be used by the receptionist, to run as follows. The receptionist will enter one letter (either “F”, “S” or “J”) and the program will display a fee of either £100, £75 or £50 respectively. Part (b) enhancing basic program to provide a password protection form The Sports Club want you to restrict access to the program by creating a password system. When the program first opens there should be a Password Form which invites the user to enter a password into a text box If the correct password is entered, the Membership Fees form you created in Part (a) should open. If an incorrect password is entered, the program should display a message stating that the password is incorrect, the text box on the password form should clear and the cursor return to the text box. If an incorrect password is entered for a total of 3 times, a message should be displayed that the program is shutting down, and the program should terminate. Part (c) enhancing basic program to provide a printed receipt The Sports Club also want the program to provide a printed receipt for each member. The receipt show contains the following data:  member name  member type  fee paid  date Exercise 6.1
  • 65. Page 65 of 144 Paul Bolton 2012 Part (d) enhancing basic program to work without a mouse Once you have demonstrated that the program works to their satisfaction, the sports club wants you to amend the program so that the receptionist only has to use the keyboard to perform most of the repetitive operations. You will therefore need to think about:  how to get the cursor to move about the screen in the right order, and  how to clear any text boxes after the receptionist has processed the details for each member. If..Then..Else – Exercise 6.1 Using multiple criteria to make selections We can use an If… Then… ElseIf statement in the Click Event for btnCalculateFeeIfThenElse, (highlighted below): Private Sub btnCalculateFeeIfThenElse_Click(...) Dim strMemberType As String 'declare variables Dim decFee As Decimal 'INPUT data strMemberType = txtMemberType.Text 'load data into variable 'CALCULATE Membership Fee If strMemberType = "F" Then 'if Member Type is "F" decFee = 100 '.. load 100 into variable ElseIf Then 'if Member Type is "S" '.. load 75 into variable ElseIf Then 'if Member Type is "J" '.. load 50 into variable Else 'if Member Type is none of the above, MsgBox("YouNeedto input F, S or J in UpperCase") '..display message End If 'OUTPUT data txtDisplayFee.Text = FormatCurrency(decFee, 2) 'format output to currency '..& display into text box btnCalculateFeeIfThenElse txtMemberType txtDisplayFee Exercise 6.1 continued Create the Sports Club Membership Fees form shown here. In this exercise, the fee for a Full member is £100, that for a Senior is £75 and that for Junior is £50.
  • 66. Page 66 of 144 Paul Bolton 2012 End Sub See if you can complete the missing code listed above, copy all the code into your program and then check the program runs as expected. Further study In the above example, if the user types in a lowercase letter “f”, “s” or “j”, these letters are not recognised. See if you can amend your code so that the user can type in either uppercase or lowercase “F”, “f”, “S”, “s”, “J” or “j”. (HINT: you can use the Or operator to add criteria to each If / ElseIf statement. If..Then..Else – Exercise 6.1 SOLUTION Private Sub btnCalculateFeeIfThenElse_Click(...) Dim strMemberType As String 'declare variables Dim decFee As Decimal 'INPUT data strMemberType = txtMemberType.Text 'loaddata into variable 'CALCULATE Membership Fee If strMemberType = "F" OrstrMemberType = "f" Then 'if MemberType is "F" or "f" decFee = 100 '.. load 100 into variable ElseIf strMemberType = "S" OrstrMemberType = "s" Then'if MemberType is "S" or "s" decFee = 75 '.. load 75 into variable ElseIf strMemberType = "J" OrstrMemberType = "j" Then'if MemberType is "J" or "j" decFee = 50 '.. load 50 into variable Else 'if Member Type is none of the above, MsgBox("YouNeed to input F, f, S, s, J or j") '..display message End If 'OUTPUT data txtDisplayFee.Text = FormatCurrency(decFee, 2) 'format output to currency '.. & display into text box End Sub Exercise 6.1 continued
  • 67. Page 67 of 144 Paul Bolton 2012 Part 7 Creating menus using the MenuStrip Control MenuStrip Control Exercise 7.1 adding a menu to the Tax Calculator Open your Tax Calculator program which you completed in Exercise 5.2 Exercise 7.1 Drag a MenuStrip Control onto the form. An icon will appear in the grey Component Tray below the form, and a blue menu bar will appear on the top part of the form containing he words “Type Here”.
  • 68. Page 68 of 144 Paul Bolton 2012 Double-click on the word “Exit” on the top-level menu and the following event procedure should open in the code window. Type in the code Application.Exit() as shown Private SubExitToolStripMenuItem_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click 'exit program Application.Exit() End Sub Run your program and check that when you click the menu items File / Exit with your mouse, the program exits. Further study Add a second top-level menu item “Options”. Add two sub- menu items beneath this: “Calculate” and “Clear”: Double-click on the “Calculate” menu item and write the following code in the event procedure: Private SubCalculateToolStripMenuItem_Click(ByValsender As System.Object, _ ByVal e As System.EventArgs) Handles CalculateToolStripMenuItem.Click 'click Calculate button remotely(evoke PerformClickmethod) btnCalculate.PerformClick() End Sub
  • 69. Page 69 of 144 Paul Bolton 2012 Run your program and see if the Calculate menu item performs the calculation in the same way as when you click the Calculate button. See if you can work out how to add code to the Clear menu item to clear all the textboxes and place the cursor back in the Gross Pay textbox. Can you think of any other menu items and sub-menus you may want to add to enhance your program?
  • 70. Page 70 of 144 Paul Bolton 2012 Part 8 Making selections using Select Case Select Case Exercise 8.1 Demonstration of advantage of Select Case construction Complete the following code (and include a message which responds to the user entering any number not between 1 and 12): Private Sub btnMonth_Click(...) Handles btnMonth.Click Dim intMonthNumber As Integer 'input month number intovariable intMonthNumber = CInt(txtNumber.Text) 'output monthbasedonmonth number Select Case intMonthNumber Case 1 MsgBox("Youhave selectedJanuary") Case 2 MsgBox("Youhave selectedFebruary") '** continue coding from this point onwards ** End select End Sub txtNumber btnMonth Exercise 8.1
  • 71. Page 71 of 144 Paul Bolton 2012 Sports Club Membership Fees Program - Revisit of scenario: converting If..Then..Else to Select Case Select Case – Exercise 8.2 Membership fees program revisited We have looked at two program control structures so far: (1) A straight sequence of commands, which are executed one after the other. (2) A selection using “If ... Then... ElseIf… Else… End If” There is an alternative to the If statement, which is the Select Case structure. We have already used an If… Then… ElseIf statement in the Click Event for btnCalculateFeeIfThenElse, (highlighted below): Private Sub btnCalculateFeeIfThenElse_Click(...) Dim strMemberType As String 'declare variables Dim decFee As Decimal 'INPUT data strMemberType = txtMemberType.Text 'loaddata into variable 'CALCULATE Membership Fee If strMemberType = "F" Then 'if Member Type is "F" decFee = 100 '.. load 100 into variable ElseIf strMemberType = "S" Then 'if Member Type is "S" decFee = 75 '.. load 75 into variable ElseIf strMemberType = "J" Then 'if Member Type is "J" decFee = 50 '.. load 50 into variable Else 'if Member Type is none of the above, MsgBox("YouNeedto input F, S or J in UpperCase") '..display message btnCalculateFeeIfThenElse txtMemberType txtDisplayFee btnCalculateFeeSelectCase Exercise 8.2 Existing code Open (or create) the Sports Club Membership Fees form shown here. In this exercise, the fee for a Full member is £100, that for a Senior is £75 and that for Junior is £50. Run your program and check that the first button works as expected before coding the second button (see next page).
  • 72. Page 72 of 144 Paul Bolton 2012 End If 'OUTPUT data txtDisplayFee.Text = FormatCurrency(decFee, 2) 'format output to currency & display into text box End Sub Using the Select Case structure as an alternative to the If…Then…Else structure. Code the btnCalculateFeeSelectCase button as follows and check the program runs with this alternative code. Compare the two constructions. 'CALCULATE Membership Fee Select Case strMemberType Case "F" 'if Member Type is "F" decFee = 100 '..load 100 into variable Case "S" 'if Member Type is "S" decFee = 75 '.. load 75 into variable Case "J" 'if Member Type is "J" decFee = 50 '.. load 50 into variable Case Else 'if Member Type is none of the above, MsgBox("You Needto input F, S or J in UpperCase") 'display message End Select Each Case acts like an If / ElseIf Statement. The instructions after an individual Case are carried out if the variable being tested matches it. Further study: Multiple tests within one “case” using a comma to separate tests. In the above example, if the user types in a lower case letter “f”, “s” or “j”, these letters are not recognised. We can get round this by the following construction: Select Case strMemberType Case "F", "f" 'if Member Type is "F"or "f" decFee = 100 '..load 100 into variable Case "S", "s" 'if Member Type is "S" or "s" decFee = 75 '.. load 75 into variable Case "J", "j" 'if Member Type is "J" or "j" decFee = 50 '.. load 50 into variable Case Else 'if Member Type is none of the above, display message MsgBox("You Needto input F, S or J in Upper or LowerCase") End Select Try amending your code and check if it works. Exercise 8.2 (continued)
  • 73. Page 73 of 144 Paul Bolton 2012
  • 74. Page 74 of 144 Paul Bolton 2012 Select Case - Further theory Testing for a range using the “To” keyword. You may wish to display exam grades according to a range of marks obtained by students. You would use the keyword “To” and the code would look something like this: Select Case txtExamGrade.Text Case 90 To 100 strGrade = “A” Case 60 To 89 strGrade = “B” Case 40 To 59 strGrade = “C” Case 0 To 39 strGrade = “FAIL” Case Else MsgBox ("You Need to input a number between 0 and 100") End Select Using “Case Is” followed by “relational operators” You can also test how the input value compares to another value by using the optional keyword “Is" followed by a relational operator in this way: Select Case decSales Case Is > 2000 decCommission = (decSales * 10 / 100) + 100 Case Is > 1750 decCommission = (decSales * 10 / 100) Case Is > 1000 decCommission = (decSales * 7 / 100) Case Is > 750 decCommission = (decSales * 5 / 100) Case Is > 500 Background information < less than > greater than = equal to <> not equal to >= greater than or equal to
  • 75. Page 75 of 144 Paul Bolton 2012 decCommission = (decSales * 2 / 100) Case Else decCommission = 0 End Select
  • 76. Page 76 of 144 Paul Bolton 2012 Select Case Demonstration of advantage of If..Then..Else construction over Select Case construction Private Sub btnOK_Click(...)HandlesbtnOk.Click Dim intAge As Integer Dim strGender As String 'input age and gender strGender = CStr(txtInputGender.Text) intAge = CInt(txtInputAge.Text) 'process data and displayappropriate message If strGender = "M" And intAge < 21 Then MsgBox("Premium is £500") ElseIf strGender = "M" And intAge >= 21 Then MsgBox("Premium is £250") ElseIf strGender = "F" And intAge < 21 Then MsgBox("Premium is £300") ElseIf strGender = "F" And intAge >= 21 Then MsgBox("Premium is £150") Else MsgBox("Youhave entered invaliddata") End If End Sub We cannot test 2 conditions at once using Select Case Background information
  • 77. Page 77 of 144 Paul Bolton 2012 Select Case – Exercise 8.1 SOLUTION Solution to Exercise 8.1 Private Sub btnMonth_Click(...) Handles btnMonth.Click Dim intMonthNumber As Integer 'input month number intovariable intMonthNumber = CInt(txtNumber.Text) 'output monthbasedonmonth number Select Case intMonthNumber Case 1 MsgBox("Youhave selectedJanuary") Case 2 MsgBox("Youhave selectedFebruary") Case 3 MsgBox("Youhave selectedMarch") Case 4 MsgBox("Youhave selectedApril") Case 5 MsgBox("Youhave selectedMay") Case 6 MsgBox("Youhave selectedJune") Case 7 MsgBox("Youhave selectedJuly") Case 8 MsgBox("Youhave selectedAugust") Case 9 MsgBox("Youhave selectedSeptember") Case 10 MsgBox("Youhave selectedOctober") Case 11 MsgBox("Youhave selectedNovember") Case 12 MsgBox("Youhave selectedDecember") Case Else MsgBox("Youhave not entereda number between1 and12") End Select 'clear textbox txtNumber.Clear() 'put cursor backintextbox txtNumber.Focus() End Sub
  • 78. Page 78 of 144 Paul Bolton 2012 Part 9 - Iterations (loops) using For..Next For…Next loops - underpinning knowledge Background There are 3 program control structures covered by this course. We have already looked at the first two: - sequences (one instruction after another) - selections (such as “If… Then… Else” or “Select Case” statements) The third program control structure introduces the concept of iteration (meaning “repeat the process”) using loops. There are two types of loop: the counter loop, and the conditional loop (such as “Do… While” ). Here we are only going to deal with the counter loop (otherwise known as the “For… Next” loop). Example Suppose we wanted to make the computer beep 5 times. (By the way, there is a simple line of code which makes the computer beep, namely: “beep”!) You could put this line of code behind a command button, and press the button 5 times: Private Sub btnBeep_Click(...) Beep End Sub However, what if we wanted to only click the command button once, and then make the code run automatically 5 times? The answer is to use a counter loop (known as a “For…Next” loop). For… Next loops need to have a variable in which to store the number of times the code should be run. In this example, let us name the variable “intCounter” and declare it as an integer. The code would be written as follows: Private Sub btnBeep_Click(...) Dim intCounter As Integer For intCounter = 1 To 5 Beep Next intCounter End Sub This code means: “Increment the value of the “intCounter” variable from 1 to 5, Background information
  • 79. Page 79 of 144 Paul Bolton 2012 and every time you increment it, execute the code below”. This is the simplest way of using the “For… Next” loop, but you need to know some more details to use it properly (covered on next handout). For now, try the exercise overleaf.
  • 80. Page 80 of 144 Paul Bolton 2012 For..Next Loops - Exercise 9.1 Beep exercise Create a form with a button as shown below. We want the code to produce 5 “beeps” when the button is pressed. However, modern computers run so fast that you will never hear the 5 beeps, so instead we will use a Message Box to produce the beeps. (Message Boxes require user response, which “interrupts” the execution of the code so you can see how the code in fact loops 5 times.) Write the code below into the “Click event” sub-procedure of the button btnBeep: Private Sub btnBeep_Click(...) Dim intCounter As Integer For intCounter = 1 To 5 MsgBox("Press to beep") Next intCounter End Sub After pressing the “beep” button, you will find that a MessageBox similar to this one appears, and after clicking “OK” it will re-appear another 4 times. Next, it would be good to make the Message Box tell us how many times the code has looped. To do this, we can include the name of the counter variable into the MsgBox function. This will display the contents of the variable each time the code loops. However, we will need to: (1)convert the counter variable data from an integer into a string, and then (2) “tack it on” to the existing message string (known as concatenation) To convert the variable data into a string we use the conversion function CStr( ) and put the name of the variable into the brackets, i.e. CStr(intCounter). We then “tack it on” to (concatenate it to) the original message using the “&” symbol: MsgBox("Press to beep. Iteration no: " & CStr(intCounter)) Alter you code as above and see what effect this has. Exercise 9.1
  • 81. Page 81 of 144 Paul Bolton 2012 (Note: we will be looking in more detail at how to use Message Boxes later in the course.)
  • 82. Page 82 of 144 Paul Bolton 2012 For.. Next Loops - Underpinning knowledge (continued) Counting in steps By default, the “For… Next” loop counts upwards in steps of 1, unless you tell it otherwise. So, the value of the variable “intCounter” above became: 1, then 2, then 3, then 4, then 5, as the loop was repeated 5 times. However, you can tell it to count upwards in increments other than 1, by adding the word “step” to the line of code. You could make the loop count up to 10 in steps of 2, for example: For intCounter = 1 To 10 Step 2 The result here would be that the loop is repeated 5 times. (The value of the variable would be 1, 3, 5, 7, and 9.) Counting backwards There are times when you will want to count down instead of counting up. You do this by using a negative “step” number. The example below again will run the code 5 times. For intCounter = 5 To 1 Step -1 In summary, the general structure of the “For… Next” loop is shown below. (the code written in brackets [ ] is optional) For countervariable = startnumber to endnumber [Step stepnumber] Next [countervariable] (3) Using variables for the start and end numbers. Body of code to be repeated Background information
  • 83. Page 83 of 144 Paul Bolton 2012 “For… Next” loops can become very useful by substituting variables for either the start or end numbers (or both). This method is used, for example, when the user puts in a number and you need to get the code to repeat that same number of times. This is demonstrated in the following exercise.
  • 84. Page 84 of 144 Paul Bolton 2012 For.. Next loops - Exercise 9.2 - Mobile phone credits exercise If we were crediting a mobile phone with £10 vouchers; rather than enter each value we might want to be able to enter how many vouchers were being presented. We could just multiply the two together but that would be too easy and wouldn’t show the working of the iterative loop. We will use a form like the one below. The form above should accept the value of vouchers, their number and then calculate the total credit. The user should enter the value of the vouchers and the number. When the calculate button is depressed, a message box should appear and show the number of times a credit voucher has been entered, as shown below: When the user clicks “OK” on the message box, it keeps re-appearing until all the vouchers have been entered. Create a form like the one above and see if you can work out the code. Extended Task txtValue txtNumber txtCredit btnCalculate btnClear then… etc. Exercise 9.2