0% found this document useful (0 votes)
41 views

VB Net Booklet

This document provides an overview of Visual Basic .Net (VB.Net) and includes examples and exercises for learning VB.Net. It covers topics such as the VB.Net integrated development environment, common controls like labels, text boxes and buttons, properties, events, variables, selection statements, loops, procedures, functions, arrays, files and more. Each chapter includes sample code and exercises for the reader to practice and learn VB.Net concepts and skills.

Uploaded by

Olivia Alex
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views

VB Net Booklet

This document provides an overview of Visual Basic .Net (VB.Net) and includes examples and exercises for learning VB.Net. It covers topics such as the VB.Net integrated development environment, common controls like labels, text boxes and buttons, properties, events, variables, selection statements, loops, procedures, functions, arrays, files and more. Each chapter includes sample code and exercises for the reader to practice and learn VB.Net concepts and skills.

Uploaded by

Olivia Alex
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

VB.

Net Guide Danny Fellows

Page : 1
VB.Net Guide Danny Fellows

Microsoft Visual Basic .Net


This booklet is designed to accompany a taught class in VB.net Programming. It
is not intended for use as an independent study guide…..Enjoy….

Contents
1. Visual Basic Integrated Development Environment 4
Creating A Visual Basic Project 4
VB Controls – Label, Text Box, Button 5
Naming Controls & Saving a Visual Basic Project 6
Saving a Visual Basic Project 6
First Project – Greeting ( lbl, txt, btn, MsgBox ) 7
Second Project – Adding Numbers 8
Exercises – Input / Calculation / Output 9
Solutions – Bank Balance Calculator & Discount Calculator 11
2. Changing Properties At Run-Time 12
Exercises – Changing properties At Run-Time 12
Exercise Solution – North South East West 13
3. More VB Controls 14
Picture Box, List Box, Combo Box, Radio Button, 14
Check Box, Group Box, Timer, Scroll Bars 15
Exercises – VB Controls 16
Exercise 2 Solution – Christmas Card List 18
Exercise 3 Solution – Band Names 19
Exercise 4 Solution – VW Price Calculator 20
Exercise 5 Solution – Stopwatch 21
Exercise 6 Solution – Mega Colours - Colour Editor 22
4. Selections – The IF Statement 23
Sample Projects – Security Access 24
Sample Projects – Ski! 25
Exercises – The IF Statement 26
5. Selection – The CASE Statement 27
Exercises – The CASE Statement 28
6. Variables 29
VB.Net Data Types 30
Variable Scope, Arithmetic, Rounding, Random Numbers 31

Page : 2
VB.Net Guide Danny Fellows

Format Function 32
Message Box and Input Box Functions 33
Example Program – Variables - Snowboard Speed Dude!! 34
Exercises – Using Variables 35
Solution - Exercise 1 – Tax Calculations 36
Solution - Exercise 3 – The GuessIt Game 37
7. A Summary Of Useful Functions 38
8. VB Project – Toptastic Snowboarding 39
9. VB Project - Smiley 41
10. Loops - For….Next Loops & Do….Loops 42
Exercises - For….Next Loops 43
Solution – Exercise 1 – 7 Times Table 44
Solution – Exercise 3 – Vowel Language 45
Do….Loop – Using While & Until 46
Exercises – Do…. Loops 47
Solution - Exercise 2 – Password Program 48
Solution - Exercise 3 – Lottery Program 49
11. Procedures 50
Exercises – Procedures 51
12. Functions 52
13. Using Arrays 53
14. Multiple Forms & Modules 55
15. Files 56
Setting up the Record Structure 56
The Record 56
Opening the File 57
Put a Record into the File 57
Get a Record from the File 57
Closing and Deleting a File 57
Example Project – Footballers Database – Basic Solution 58
Creating a Report in a ListBox 61
Deleting Records from a File in VB.Net 62
Printing a Report from a ListBox 63
Hashing Algorithms 65

Page : 3
VB.Net Guide Danny Fellows

1. VISUAL BASIC INTEGRATED


DEVELOPMENT ENVIRONMENT
Menu Bar ToolBar
Run

The Form
Project
Explorer

Properties
Window

Toolbox

Fig 1 The Visual Basic .Net 2015 Integrated Development Environment

Creating A Visual Basic Project


A Visual Basic Project is created by placing controls from the Toolbox (for example
TextBox, Label or Button) onto the Form. Each control has a set of properties
which can be changed by the programmer to alter the appearance, position and
function of the control.

Program commands can be added to a control by double clicking on the control.


The commands are entered into the code window. Each control has a number of
events associated with it, such as Click and Mouse Move. The code is attached
to a specific event for the control. For example : code could be attached to the
Click Event of a Button. When the user clicks on that button, the associated code
will be run.

Page : 4
VB.Net Guide Danny Fellows

VB Controls - Label, Text Box, Button

Label

Labels are used to display information on a VB form.

Some properties of a label :

Text, Font, ForeColor, BackColor, Visible

Text Box
A Text Box is used to display information, but also the user can enter data into a
Text Box.

Some Properties of a Text Box :

Text, ReadOnly, BorderStyle, Font, ForeColor, BackColor, Visible

Button
Buttons are used to add some function to a VB form. Code can be attached to a
Button which will be run when the user clicks on the button.

Some Properties of a Button :

Text, Font, Size, BackColor, Visible

Page : 5
VB.Net Guide Danny Fellows

Naming Controls
The first thing the programmer should do after adding a control to a form is to give
the control a representative name. Each control type has a name prefix.

For example a Text Box which holds an address could be called : txtAddress

Control Prefixes

Form frm Picture pct


Label lbl Text Box txt
Button btn GroupBox grp
Check Box chk Radio Button rdb
Combo Box cmb List Box lst
Horz Scroll Bar hsb Vert Scroll Bar vsb
Timer tmr

Saving a VB.Net Project

To save a VB project use the Save All button

A Visual Basic Project consists of a group of files. The files will be saved in a
folder created by VB in the following location :

Document > Visual Studio XXXX > Projects

For Example : If you save a project called Greetings, the files for that project will
be saved in the following folder :

Documents > Visual Studio XXXX > Projects > Greetings

To open the project run the Microsoft Visual Studio Solution file :

Page : 6
VB.Net Guide Danny Fellows

First Project – Greeting (txt,lbl,btn)

1) Open a new Visual Basic project and set up the form as indicated below :
Form : frmGreetings

Label : lblInstruction

TextBox : txtName

Button : btnHello

2) Double-Click on the ‘Click Me’ button and complete the following code by
adding the lines indicated by the arrows.

'DISPLAY A GREETING TO THE USER INCLUDING THEIR NAME

Public Class frmHello

Private Sub btnHello_Click(sender As Object, e As EventArgs)_


Handles btnHello.Click

MsgBox("Hello " + txtName.Text)

End Sub

End Class

3) Save the project as Greetings

4) Run the Project and it should look something like this :

Page : 7
VB.Net Guide Danny Fellows

Second Project – Adding Numbers


This project will allow the user to enter two numbers. When the user clicks on a
button the two numbers will be added and the result displayed.

1) Open a new Visual Basic project and set up the form as indicated below :

txtNum1

txtNum2

btnAdd

txtResult

2) Complete the following code in Add Button

'ADD TWO NUMBERS TOGETHER


Public Class frmAdding
Private Sub btnAdd_Click(sender As Object, e As EventArgs)_
Handles btnAdd.Click
txtResult.Text = Val(txtNum1.Text) + Val(txtNum2.Text)
End Sub
End Class

Note The val( ) function tells VB that the text box contents is numeric.

3) Save the project as Adding

4) Run the Project and it should look something like this :

Note : Set the


ReadOnly
property of the
result textbox
to True. This
will stop the
user editing the
result.

Page : 8
VB.Net Guide Danny Fellows

Exercises - Input / Calculation / Output

These exercises involve creating a Visual Basic Project to solve a problem. The
screen must be well designed. All controls must have representative names,
including the relevant three letter prefix. Any program code must be well laid out,
using blank lines, indentation and comments to aid readability. Start a new project
for each exercise and save each with a representative name.

1. ADDING - Write a program which will allow the user to enter three numbers.
When the calculation button is pressed the result of these three numbers
added, multiplied, and subtracted should then be displayed.

2. BANK BALANCE - Write a program which will calculate the user's bank
balance after a withdrawal. The user should enter their original balance and
the amount withdrawn. The new balance will then be displayed when a
button is pressed.

3. EXAM RESULTS - Write a program to calculate the average of five exam


results. The user enters the five exam results. The average is calculated
and the result displayed to the user.

4. DISCOUNT - Write a program to calculate the discount in a shop. The shop


keeper will enter the price of a product and the discount rate (as a
percentage). The program will display the amount of discount and the price
to pay.

5. CONVERSIONS - Write a program to convert a person’s height and weight to


metric. The user enters their name, their height in inches and their weight in
stone.

1 inch = 2.5 cm 1 stone = 6.364 kg.

The user’s converted details will then be displayed in the following format :

John Sparrow. Your weight is 94kg. Your height is 167cm.

6. TEMPERATURE - Write a program which will convert temperature values


from fahrenheit to centigrade.

Centigrade = ( Fahrenheit - 31 ) * ( 5 / 9 )

Page : 9
VB.Net Guide Danny Fellows

7. TURF - Write a program to calculate the amount and cost of turf needed for a
garden. The garden has a border flower bed and a square fish pond. The
user will enter the overall length of the garden, the overall width of the
garden, the width of the border flower bed, and the width of the fish pond.
All data is entered in metres. The cost of turf is £0.75 per square metre. The
program will output the amount and cost of the turf required.

8. SWIMMING POOL - Write a program to calculate the volume of water in a


swimming pool. The pool is rectangular in shape and has a deep end and a
shallow end. The user will enter the length, width, depth at the deep end
and depth at the shallow end. All entries will be in metres and the volume of
water will be displayed in metres cubed.

9. POWERS - Write a program that, given a number as input, prints its square,
cube, and fourth power without doing any unnecessary calculations.

10. PAY RISE - A pay rise of 9.9% has been awarded to a companies
employees. Write a program to which an employee can supply as input his
previous annual salary and which will inform him of his new annual, monthly
and weekly rates of pay. Assume that there are exactly 52 weeks in a year.

11. INVEST IT - A sum of money has been invested at an annual rate of interest
of 14.75%. Interest is calculated and added to the account at the end of each
complete year. Write a program which reads the initial amount invested and
which displays the interest and balance in the account at the end of each
year.

12. CAR HIRE - A car hire company calculates the charge for the hire of a car
using a standard rate for each mile travelled together with a 'wear and tear'
surcharge for each complete 1000 miles travelled. Write a program which
accepts as input the mileometer readings at the start and finish of a hire, the
rate per mile and the 'wear and tear' surcharge, and calculates the total
charge for the hire.

13. ON THE TILES - The floor of a room is to be covered with tiles of dimensions
15cm square. There is to be a gap of 2mm between tiles when laid. Write a
program that given the room dimensions (in metres) will work out the number
of whole tiles required.

Page : 10
VB.Net Guide Danny Fellows

Exercise Solution 2 – Bank Balance Calculator

'CALCULATE BANK BALANCE AFTER A WITHDRAWL


Public Class frmBank
Private Sub btnCalc_Click(sender As Object, e As EventArgs)_
Handles btnCalc.Click
txtNewBalance.Text = txtOldBalance.Text - txtWithdrawl.Text
End Sub
End Class

Exercise Solution 4 – Discount Calculator

'CALCULATE DISCOUNT ON A SALE FROM THE PRICE AND A DISCOUNT RATE


Public Class frmBank
Private Sub btnCalc_Click(sender As Object, e As EventArgs)_
Handles btnCalc.Click
txtDiscount.Text = txtPrice.Text * txtDiscountRate.Text/100
txtPriceToPay.Text = txtPrice.Text - txtDiscountAmount.Text
End Sub
End Class

Page : 11
VB.Net Guide Danny Fellows

2. CHANGE PROPERTIES AT RUN-TIME


The Properties of VB controls can be changed at Design-Time (by changing
values in the Properties Window) or at Run-Time (using program code). To
change a property use the name of the control followed by a dot and then the
name of the property. For example :

lblName.BackColor = Color.Red will change the BackColor property


of the label lblName to Red.

Some More Examples


txtName.Text = “Fred” lblMessage.Left = 200
lblResult.BackColor = lblAns.BackColor btnCalculate.Top = 1500
lblMes.Location = New Point(100, 100) lblMessage.Visible = True
btnCalculate.Top = btnCalculate.Top + 120 lblMessage.Visible = False

Exercises - Changing Properties At Run-Time

1. COLOURS - Write a program with a Text Box and three Buttons (Red, Blue
and Green). When the user clicks on a button the Text Box changes to the
selected colour. Use : txtDisplay.Backcolor = Color.Red

2. WOW - Create a program to allow the user to move a Label containing the
text ‘WOW’, around the screen using eight direction buttons :
N NW W SW S SE E NE
The ‘WOW’ text will change colour each time it changes direction.

3. MOUSEY - Write a program to test the user’s mouse skills. There will be ten
Text Boxes of various sizes scattered around on the form. When the user
clicks on a Text Box it will disappear.

4. PLAINS OF WISDOM - Create An Adventure Quiz Program : ‘THE PLAINS


OF WISDOM’. The user will initially see two statements, one true and one
false. They have to click on the true statement to see the next pair of
statements. Each time they get it right they move on to the next pair of
statements. If they get it wrong they move back one level. After five levels
they reach the Plain Of Wisdom!!!! The number of guesses will be added up
in a text box as they play.

Use the visible property to make the statements appear and disappear…
Eg. txtStatement1.visible = true

Page : 12
VB.Net Guide Danny Fellows

Exercise Solution 2 – North South East West

'WOW MOVER BY DANNY FELLOWS 14/9


'MOVE A MESSAGE AROUND THE SCREEN, CHANGING IT’S COLOUR.
Public Class frmWow
Private Sub btnNorth_Click(sender As Object, e As EventArgs)_
Handles btnNorth.Click
lblWow.Top = lblWow.Top - 10
lblWow.ForeColor = Color.Plum
End Sub
Private Sub btnNorthEast_Click(sender As Object,_
e As EventArgs)Handles btnNorthEast.Click
lblWow.Top = lblWow.Top - 10
lblWow.Left = lblWow.Left + 10
lblWow.ForeColor = Color.Pink
End Sub
Private Sub btnEast_Click(sender As Object, e As EventArgs)_
Handles btnEast.Click
lblWow.Left = lblWow.Left + 10
lblWow.ForeColor = Color.Red
End Sub
Private Sub btnSouthEast_Click(sender As Object,_
e As EventArgs)Handles btnSouthEast.Click
lblWow.Top = lblWow.Top + 10
lblWow.Left = lblWow.Left + 10
lblWow.ForeColor = Color.SaddleBrown
End Sub
Private Sub btnSouth.........ETC......
Private Sub btnSouthWest.....ETC......
Private Sub btnWest..........ETC......
Private Sub btnNorthWest.....ETC......
End Class

Page : 13
VB.Net Guide Danny Fellows

3. MORE VB CONTROLS - PICTURE BOX,


LIST BOX, COMBO BOX, RADIO BUTTON,
CHECK BOX, GROUP BOX, TIMER AND
SCROLL BARS

Picture Box
A Picture Box is used to display pictures on the Form.

Properties : Image Allows the programmer to select the picture.


SizeMode Allow the picture to stretch or be fixed size.

List Box

List Boxes are used to store and display a list of information on a VB form. Each
item in the List has an Index number. The first Index number is zero.

Properties : Items Contains all items in the list.


Sorted Sets whether the list will be sorted or not.

Methods : .Items.Add Add item to the list. lstXmas.Items.Add (“Fred”)


.Items.Remove Removes items lstXmas.Items.Remove(“Fred”)
.Items.Clear Clear the list lstXmas.Items.Clear
.Items.Count Counts the number of items in the list.

Combo Box
A Combo Box combines a Text Box and a List Box. The list will drop down when
selected by the user.

Radio Button

Radio Buttons allow the user to select just one option from a set of options. Use a
Frame to group Option Buttons together.

Properties : Checked True if selected and False if not.

Page : 14
VB.Net Guide Danny Fellows

Check Box
Similar to an Option Button, but more than one option can be selected from a
group of options. Use a Frame to group Check Boxes together.

Properties : Checked True if selected and False if not.

Group Box
A Group Box is used to group Option Buttons and Check Boxes together. Draw
the Group Box first and then add buttons to it.

Timer
The Timer is used to trigger regular events at specified time intervals. It will not
appear on the form at Run-Time.

Properties : Enabled Used to turn the timer on (True) and off (False).
Interval Sets the interval at which the attached code will be run.
Set in 1/1000ths of a second. Eg 1000 = 1Sec.

Scroll Bars
Horizontal and Vertical Scroll Bars work in the same way. They are used to allow
the user to select a value.

Properties : Value Current value of the Scroll Bar.


Maximum The Maximum value of the Scroll Bar.
Minimum The Minimum value of the Scroll Bar.
LargeChange Amount of change after click on the bar.
SmallChange Amount of change after click on the arrow.

Page : 15
VB.Net Guide Danny Fellows

Exercises - Picture Box, List Box, Combo Box,


Option Button, Check Box, Frame, Timer, Scroll
Bars

These exercises involve creating a Visual Basic Project to solve a problem. The
screen must be well designed. All controls must have representative names,
including the relevant three letter prefix. Any program code must be well laid out,
using blank lines, indentation and comments to aid readability. Start a new project
for each exercise and save each with a representative name.

1. PICTURE QUIZ – (Picture Box) - Create a Children’s Quiz with three


pictures. There will be an instruction displayed on the form Eg. CLICK ON
THE HORSE. If the child clicks on the horse then a ‘WELL DONE’ message
is displayed, otherwise another message is displayed Eg. ‘NO THAT IS A
COW’.

2. CHRISTMAS CARDS – (List Box) – Write a program to create and maintain


a Christmas Card list. The user will enter a name into a text box. When they
click on the Add button the name will be added to a List Box. There will also
be a Remove button to remove one entry from the list and a Clear button to
clear the entire list.

3. BAND NAMES – (Combo Box) – Write a project to help the user select Band
Names. There will be two combo boxes each containing a list of words. The
user will select one word from each combo box, for example ‘Red’ and ‘Trees’
and the names will be displayed as a complete band name ‘The Red Trees’.
The user will have the option to store the selected band name in a favourites
list box.

Project Extension : Give the user the option of adding and removing words
from the two Combo Boxes while the program is running.

4. VW BEETLE – (Check Boxes, Radio Buttons & Group Boxes) – Write a


program to calculate the cost of a new VW Beetle. The user will click on
check boxes and radio buttons to select the options for the car :

Engine Size : 1600cc £10000 1800cc £12000 2000cc £14500

Options : Sun Roof £250 CD Player £270


Air Con £340 Tow Bar £160
Roof Rack £120 Baby Seat £78

Page : 16
VB.Net Guide Danny Fellows

5. STOPWATCH – (Timer) - Write a program using a Timer to control a


stopwatch. The time will be displayed to one decimal point, for example 12.9
There will be three buttons : Start, Stop and Reset..

6. MEGA COLOURS – (Scroll Bars) – Colours on the screen in VB are made up


of three elements : Red, Green and Blue. This program will allow the user to
set a value between 0 and 255 for each of these elements.

Write a program to use three scroll bars to select the values for these three
colour elements. Use the RGB function to set the background colour of the
form. The RGB function has three parameters for Red, Green, Blue (each 0
to 255). For example...
Me.BackColor = System.Drawing.ColorTranslator.FromOle _
(RGB(hsbRed.Value, hsbGreen.Value, hsbBlue.Value))

7. SNOWBOARD - Write a program to calculate the cost of a Snowboarding


Holiday. The user will select the number of adults and the number of children
using two Scroll Bars (for selection) and two read-only Text Boxes (to display
the numbers). They will select the resort using Radio Buttons, and they will
select Board Hire, Boot Hire and Lift Pass using Check Boxes. The Prices :

Resort Adult Child Board Boots Lift Pass


Homewood 450 350 40 40 89
Northstar 400 300 45 45 65
Rose Bowl 425 325 42 43 70

Sample Screen Design:

Page : 17
VB.Net Guide Danny Fellows

Solution – Exercise 2 – Christmas Card List

'MAINTAIN A CHRISTMAS CARD LIST. ALLOW THE USER TO ADD


'REMOVE ITEMS AND CLEAR THE LIST. BY DANNY FELLOWS
Public Class frmXmasCardList
'ADD AN ITEM TO THE LIST, SET CURSOR BACK TO TEXT BOX
Private Sub btnAdd_Click(sender As Object, e As EventArgs)_
Handles btnAdd.Click
lstXmas.Items.Add(txtName.Text)
txtName.Text = ""
txtName.Focus()
End Sub
'REMOVE AN ITEM FROM THE LIST
Private Sub btnRemove_Click(sender As Object, e As EventArgs)_
Handles btnRemove.Click
lstXmas.Items.Remove(lstXmas.Text)
End Sub
'REMOVE ALL THE ITMES FROM THE LIST - CLEAR
Private Sub btnClear_Click(sender As Object, e As EventArgs)_
Handles btnClear.Click
lstXmas.Items.Clear()
End Sub
'EXIT THE PROGRAM
Private Sub btnQuit_Click(sender As Object, e As EventArgs)_
Handles btnQuit.Click
End
End Sub
End Class

Page : 18
VB.Net Guide Danny Fellows

Solution – Exercise 3 – Band Names

'BAND NAMES - HELPS A USER TO CHOOSE BAND NAMES.

Public Class frmBandNames

Private Sub btnSave_Click(sender As Object, e As EventArgs)_


Handles btnSave.Click
lstFavs.Items.Add _
("The " + cmbWord1.Text + " " + cmbWord2.Text)
End Sub

End Class

Page : 19
VB.Net Guide Danny Fellows

Solution - Exercise 4 - VW Beetle Price Calculator

'VW PRICE DANNY FELLOWS


Private Sub btnReset_Click
Public Class frmVWPriceCalculator rdb1600.Checked = True
chkSunRoof.Checked = False
Private Sub Rdb1600_CheckedChanged chkAirCon.Checked = False
txtBasic.Text = 10000 chkRoofRack.Checked = False
End Sub chkCDPlayer.Checked = False
chkTowBar.Checked = False
Private Sub rdb1800_CheckedChanged chkBabySeat.Checked = False
txtBasic.Text = 12000 End Sub
End Sub
Private Sub btnQuit_Click
Private Sub rdb2000_CheckedChanged End
txtBasic.Text = 14500 End Sub
End Sub
'CALCULATE THE TOTAL COST.
'ADD UP THE EXTRAS 'THIS CODE IS ON THE
'TEXTCHANGED EVENT OF THE
Private Sub chkSunRoof_CheckedCh~d 'TEXTBOXS SO THAT IT HAPPENS
txtExtras.Text = _ 'WHENEVER THE BASIC COST OR
chkSunRoof.Checked * 250 + _ 'EXTRAS TOTALS CHANGE.
chkAirCon.Checked * 340 + _
chkRoofRack.Checked * 120 + _ Private Sub txtBasic_TextChang~
chkCDPlayer.Checked * 270 + _ txtTotal.Text = _
chkTowBar.Checked * 160 + _ Val(txtBasic.Text) _
chkBabySeat.Checked * 78 + Val(txtExtras.Text)
End Sub End Sub

Private Sub txtExtras_TextCang~


txtTotal.Text = _
Repeat the above block of code Val(txtBasicCost.Text) _
for the CheckedChanged event + Val(txtExtras.Text)
of each of the Optional Extra End Sub
check boxes. This will ensure End Class
the extras total is continually re-
calculated.

Page : 20
VB.Net Guide Danny Fellows

Solution – Exercise 5 – Stopwatch

The Timer control is not


visible on the form when the
program runs.

Set the Interval Property of


Timer to 100. This means
the Timer code will activate
every 1/10th of a second.

'STOPWATCH - START, STOP AND RESET A STOPWATCH


'WHICH COUNTS AT .1 SEC DANNY FELLOWS

Public Class frmStopwatch

Private Sub tmrStopwatch_Tick(sender As Object,_


e As EventArgs) Handles tmrStopwatch.Tick
txtStopWatch.Text = txtStopWatch.Text + 0.1
End Sub

Private Sub btnStart_Click(sender As Object,_


e As EventArgs) Handles btnStart.Click
tmrStopwatch.Enabled = True
End Sub

Private Sub btnStop_Click(sender As Object,_


e As EventArgs) Handles btnStop.Click
tmrStopwatch.Enabled = False
End Sub

Private Sub btnReset_Click((sender As Object,_


e As EventArgs) Handles btnReset.Click
txtStopWatch.Text = 0
End Sub

End Class

Page : 21
VB.Net Guide Danny Fellows

Solution – Exercise 6 – MEGA COLOURS

Set Scroll Bar Properties :


Min 0
Max 255

Notice that the code is


attached to the Scroll Event
of the Scroll Bar. This
means that the colour of
the label will change as the
user slides the Scroll Bar.

'COLOUR EDITOR - THE USER SELECTS COLOURS BY SLIDING


'THREE SCROLL BARS - RED, GREEN, BLUE - BY DANNY FELLOWS

Public Class frmColours

Private Sub hsbRed_Scroll(sender As Object,_


e As ScrollEventArgs) Handles hsbRed.Scroll
txtRed.Text = hsbRed.Value
Me.BackColor = System.Drawing.ColorTranslator. _
FromOle(RGB(hsbRed.Value, hsbGreen.Value, hsbBlue.Value))
End Sub

Private Sub hsbGreen_Scroll(sender As Object,_


e As ScrollEventArgs) Handles hsbGreen.Scroll
txtGreen.Text = hsbGreen.Value
Me.BackColor = System.Drawing.ColorTranslator. _
FromOle(RGB(hsbRed.Value, hsbGreen.Value, hsbBlue.Value))
End Sub

Private Sub hsbBlue_Scroll(sender As Object,_


e As ScrollEventArgs) Handles hsbBlue.Scroll
txtBlue.Text = hsbBlue.Value
Me.BackColor = System.Drawing.ColorTranslator. _
FromOle(RGB(hsbRed.Value, hsbGreen.Value, hsbBlue.Value))
End Sub

End Class

Page : 22
VB.Net Guide Danny Fellows

4. SELECTIONS – THE IF STATEMENT

The IF statement allows decisions to be made in VB programs. For example :-

A user enters their age to gain access to a night club. They have to be over 18..

If txtAge.text > 18 then

lblMessage.text = (“You can come in”)

Else

lblMessage.text = (“Go home!”)

End If

Note : The Else part is optional.

Conditions

a=b a equals b a >= b a is greater than or equal to b

a>b a is greater than b a <= b a is less than or equal to b

a<b a is less than b a <> b a is not equal to b

Multiple Conditions with AND and OR

More than one condition can be used with AND and OR operators.....

If txtAge.text >= 5 and txtAge.text <=16 THEN

lblMessage.text = (“You are school age.”)

End If

If txtAge.text < 5 or txtAge.text > 16 THEN

lblMessage.text = (“You are not school age.”)

End If

Page : 23
VB.Net Guide Danny Fellows

Sample Project – Security Access (IF)


This project will allow the user to enter a password. When the user clicks on a
button a message will be displayed to say if they have access.

1) Open a new Visual Basic project and set up the form as indicated below :

2) Add the following code to the Click event of Button : btnAccess

'CHECK A PASSWORD ENTERED BY THE USER AND GIVE A MESSAGE

Public Class frmPassword

Private Sub btnAccess_Click(sender As Object,_


e As EventArgs) Handles btnAccess.Click

txtPassword.Text = UCase(txtPassword.Text)

If txtPassword.Text = "ELEPHANT" Then


MsgBox("Come In")
Else
MsgBox("No Access")
End If

End Sub

End Class

3) Save the Project.

4) Run the Project and it should look something like this :

Page : 24
VB.Net Guide Danny Fellows

Sample Project – Ski!


In SKI! The user will guide the Skier back to the lodge for a nice glass of wine.

1) Open a new Visual Basic project and set up the form as indicated below :

Picture :
pctWine
Buttons
btnUp
btnLeft
btnRight Picture :
btnDown pctSkier

Set the location property of the pictures to multiples of 50. Eg 350,50

2) Add the following code to the Click event of Button : btnUp


'SKI! DANNY FELLOWS 17/9
'GUIDE A SKIER BACK TO THE LODGE FOR A NICE GLASS OF WINE
Public Class frmSkier
Private Sub btnUp_Click(~~~~~) Handles btnUp.Click
pctSkier.Top = pctSkier.Top - 50
If pctSkier.Location = pctWine.Location Then
MsgBox("You made it home - enjoy the wine!")
End If
End Sub
End Class

3) The code attached to the remaining Buttons will be similar to this but line:
pctSkier.Top = pctSkier.Top – 50 will change slightly.

4) Run the Project and it should look something like this :

Page : 25
VB.Net Guide Danny Fellows

Exercises – The IF Statement

These exercises involve creating a Visual Basic Project to solve a problem. The
screen must be well designed. All controls must have representative names,
including the relevant three letter prefix. Any program code must be well laid out,
using blank lines, indentation and comments to aid readability. Start a new
project for each exercise and save each with a representative name.

1. JURY SERVICE - Write a program which will allow the user to enter their
age. A message will then be displayed to indicate whether or not the user is
eligible for jury service. They must be between 18 and 65 years old
inclusive to be eligible.

2. DOUBLE DISCOUNT - Write a program which will calculate the discount, if


any, on a sale. Sales of £100 and over are eligible for a discount of 10%.
The program should display the original sales amount, any discount, and
the price to pay.

3. CINEMA - Write a program to allow the user to enter the screen number.
The film showing on that screen will be displayed :

Screen 1 2 3
Film Local Hero Warriors Blues Brothers

4. COMMISSION - Write a program to calculate a salesman’s commission on


his days sales. The user enters the value of the days sales and the
commission is calculated as follows :

Value of Sales Commission

below £1000 10%


£1000 to £5000 15%
over £5000 20%

5. QUIZ - Write a quiz program with five questions. As the user answers the
questions their current score will be displayed. The five questions should
relate to a common theme, for example : Astronomy.

Page : 26
VB.Net Guide Danny Fellows

5. SELECTIONS – CASE STATEMENT

The CASE statement allows decisions to be made in VB programs. It can be


used to replace certain coding structures which use the IF statement.. For
example :-

This is the program code for the Cinema Exercise on the previous page using first
the IF statement and then the CASE statement.....

Using the IF Statement

If txtScreen.text = 1 then
lblFilm.text = “Local Hero”
Else
If txtScreen.text = 2 then
lblFilm.text = “Warriors”
Else
If txtScreen.text = 3 then
lblFilm.text = “Blues Brothers”
Else
lblFilm.text = “Error”
End If
End If
End If

Using the CASE Statement

Select Case txtScreen.text

Case 1
lblFilm.text = “Local Hero”
Case 2
lblFilm.text = “Warriors”
Case 3
lblFilm.text = “Blues Brothers”
Case Else
lblFilm.text = “Error”

End Select

Some Valid CASE conditions


Case 4,5,7,9 Case Is > 10 Case 41 to 65 Case “Fred”, “Tom”

Page : 27
VB.Net Guide Danny Fellows

Exercises – The CASE Statement

1. FOOTBALL - Write a program which will allow the user to enter the initials of
a football team. The name of the team will be displayed.

PFC – Portsmouth Football Club PAFC – Plymouth Argyle Football Club


LFC – Liverpool Football Club MUFC – Man United Football Club
CFC – Chelsea Football Club BCFC – Bristol City Football Club

2. ROMAN NUMERALS - In this program the user will enter one character of a
Roman Numeral, for example I, V, X, L. The program will display the
decimal equivalent, for example 1, 5, 10, 50.

3. SEASONS - Write a program which allows you to type in a month number


and displays the appropriate season. e.g. For the month number 8 the
program should display a message saying: 'The Season Is Summer'

4. EXAM GRADES - Write a program which will allow the user to enter their
exam percentage. A message will then be displayed to indicate what grade
they have achieved.

F – 0 to 39 C – 40 to 59 B – 60 to 79 A – 80 to 100

5. RESULTS - Write a program which will let a student type in his grade and
which will print out the appropriate message ‘DISTINCTION’ for grades A
and B, 'CREDIT' for grades C and D, 'PASS' for grade E, and 'FAIL' for
grade F.

6. COMMISSION - Write a program to calculate a salesman’s commission on


his days sales. The user enters the value of the days sales and the
commission is calculated as follows :

Value of Sales below £1000 £1000 to £5000 over £5000


Commission 10% 15% 20%

7. FLIGHTS - An airline company charges for flights depending on the time of


year as shown below. Write a program to allow the user to input a month
number and the number of passengers. The total cost will be displayed.

Month Jan-Mar Apr Jun July August Sept-Nov Dec


Charge £100 £120 £130 £160 £120 £90 £80

Page : 28
VB.Net Guide Danny Fellows

6. USING VARIABLES
Data can be stored in Text Boxes and Labels in a VB Project, but this can
become cumbersome when the programs get more complex. In this case a
VARIABLE can be used to store the data. Variables are defined using the Dim
statement, and given a name (identifier) and a data type. Data can then be
stored in variables and used in the program….

Declaring Variables

Dim identifier As datatype

Identifier / Variable Name


Use a representative name and start with a capital letter.

For Example : Age

Main Data Types (The full list is on the next page)

Data Type Storage Range

Integer 4 bytes -2,147,483,648 to +2,147,483,647

Single 4 bytes Decimal Number

String 1 byte/char Any number of characters

Date 8 bytes 0:00:00 1/1/0001 to 11:59:59 31/12/9999

Boolean 1 byte True or False

Example Variable Declarations

Dim Age as Integer Dim Salary as Decimal


Dim Surname as String Dim Married as Boolean

Assigning Values to Variables

Use = to assign values. Eg

Age = 41 Salary = 21890.50


Surname = “Smith” Married = True

Page : 29
VB.Net Guide Danny Fellows

Visual Basic Data Types

Data Type Storage Range

Byte 1 byte 0 through 255 (unsigned)

Short 2 bytes Short Integer -32,768 to 32,767

Integer 4 bytes -2,147,483,648 to +2,147,483,647

Long 8 bytes Integer -9 billion billion to +9 billion billion

Single 4 bytes Big Decimal Number

Double 8 bytes Very Big Decimal Number

Decimal 16 bytes Very Very Big Decimal Number

Char 2 bytes Single Character

String 1 byte/char Any number of characters

Boolean 1 byte True or False

Date 8 bytes 0:00:00 1/1/0001 to 11:59:59 31/12/9999

Object 4 or 8 bytes Any type can be stored in a variable of type


Object

SByte 1 byte -128 through 127 (signed)

UInteger 4 bytes Unsigned Integer 0 to 4,294,967,295

ULong 8 bytes Unsigned Long Integer


0 to 18,446,744,073,709,551,615

UShort 2 bytes Unsigned Short Integer 0 to 65,535

Page : 30
VB.Net Guide Danny Fellows

Variable Scope
Local Variables declared in a procedure can only be used in that procedure.

Global Variables declared in the general part of the program code of a


form can be used anywhere in that form.

To be global to a program with more than one form a variable must be


declared in a Module using the identifier Public instead of Dim.

Constants
Constants are declared with a value and keep that value throughout the program.

Eg Public Const TaxRate as single = 0.25

Arithmetic Operations in Order of Mathematical Precedence


Power ^ A=A^2
Multiplication * A=A*5
Division / A=A/2
Integer Division \ A=A\2
Modulus (Remainder) Mod A = A Mod B
Addition + A=A+1
Subtraction - A=A–1

The Round Function Math.Round ( Identifier , Decimal Places )

Used to round numbers to a given number of decimal places.

Eg Assuming the variable Number contains 52478.3296


LblResult.text = Math.Round ( Number , 2 ) lblResult.text is 52478.33

Generating Random Numbers – Using the rnd() function

It is often useful to be able to generate a random number. These can be used in


games, to generate graphics effects etc… The rnd() function generates a
Random Number between 0 and 0.99999. This can be converted into our
required range:

To generate a Random Number between Min and Max we use the code:
RandomNumber = Int ( rnd() * ( Max – Min + 1 )) + Min

Eg. To generate a random number between 1 and 20 we could use:


Random Number = Int ( rnd() * ( 20 – 1 + 1 ) ) + 1

Page : 31
VB.Net Guide Danny Fellows

The Format Function Format ( Identifier , Format )


Used to format numbers using a string mask.
For Example : Assuming the variable Number contains 52478.3296

LblResult.text = Format ( Number , “0” ) lblResult is 52478


LblResult.text = Format ( Number , “0.00” ) lblResult is 52478.33
LblResult.text = Format ( Number , “0000000.00” ) lblResult is 0052478.33
LblResult.text = Format ( Number , “0.000000” ) lblResult is 52478.3300
LblResult.text = Format ( Number , “###.0” ) lblResult is 52478.3
LblResult.text = Format ( Number , “#,##0.0” ) lblResult is 52,478.3
LblResult.text = Format ( Number , “###.00” ) lblResult is 52478.33
LblResult.text = Format ( Number , “£ #,##0.00” ) lblResult is £ 52,478.33
LblResult.text = Format ( 0.175 , “0.0 %” ) lblResult is 17.5 %

More Examples with Dates, Times and Strings

Dim MyTime, MyDate, MyStr


MyTime = #17:04:23#
MyDate = #January 27, 1993#

Returns current system time in the system-defined long time format.

MyStr = Format(Time, "Long Time")

Returns current system date in the system-defined long date format.

MyStr = Format(Date, "Long Date")

MyStr = Format(MyTime, "h:m:s") - Returns "17:4:23".


MyStr = Format(MyTime, "hh:mm:ss am/pm") - Returns "05:04:23 pm".
MyStr = Format(MyTime, "hh:mm:ss AM/PM") - Returns "05:04:23 PM".
MyStr = Format(MyDate, "dddd, mmm d yyyy") - Returns "Wednesday, Jan 27
1993".

If format is not supplied, a string is returned.

MyStr = Format(23) ' Returns "23".

User-defined formats.

MyStr = Format(5459.4, "##,##0.00") ' Returns "5,459.40".


MyStr = Format(334.9, "###0.00") ' Returns "334.90".
MyStr = Format(5, "0.00%") ' Returns "500.00%".
MyStr = Format("HELLO", "<") ' Returns "hello".
MyStr = Format("This is it", ">") ' Returns "THIS IS IT".

Page : 32
VB.Net Guide Danny Fellows

Message Box – MsgBox ( )


A Message Box can be used to display a message to the user, and also to allow
the user to select a response.

A simple Message Box example :

MsgBox ( “Bye Bye” )

A more complex Message Box returns a value…..

Dim Response As Integer

Response = MsgBox ( “Quit ?” , MsgBoxStyle.YesNo , “Car System” )

If Response = vbYes then MsgBox ( “Bye Then”)

If the User clicks YES then Response will equal vbYes


If the User clicks NO then Response will equal vbNo

Input Box – InputBox ( )


An Input Box is similar to a message box but allows the user to enter a value. Eg

Dim Surname As String


Surname = InputBox ( “Please Enter Your Name” )

Page : 33
VB.Net Guide Danny Fellows

Example Program – Using Variables


Write a program to calculate a running average of the speed of snowboarders.
Declare variables to store the number of speeds (n), total and average.

Note:
To set up a
default button on
the form, so the
user can just
press Enter rather
than having to
click, use the
AcceptButton
property of the
form.

' SNOWBOARD SPEED DUDE!!! DANNY FELLOWS


' CALCULATE THE AVERAGE SPEED OF SNOWBOARDERS
Option Explicit On
Public Class frmSnowboard
Dim n As Integer
Dim Total As Decimal
Dim Average As Decimal
Private Sub btnEnterSpeed_Click(~~~~
n = n + 1
Total = Total + txtSpeed.Text
Average = Total / n
lblAverageSpeed.Text = Format(Average, "0.00")
txtSpeed.Text = ""
txtSpeed.Focus()
End Sub
Private Sub btnReset_Click(~~~~
n = 0
Total = 0
lblAverageSpeed.Text = 0
txtSpeed.Text = ""
txtSpeed.Focus()
End Sub
End Class

Page : 34
VB.Net Guide Danny Fellows

Exercises – Using Variables

1. TAX CALCULATOR - Write a program which will calculate a user’s tax


bill. The gross pay will be entered in a Text Box. Pension
contributions at 9% of the gross and National Insurance contributions
at 7% of gross are deducted. The user’s tax allowance of £5000 is
then deducted. Income tax is calculated on remaining money at 20%
for those earning a gross of less than £25,000, 30% for those earning
over £50,000 and 25% for everyone else.

Uses variables to store Pension Contributions, NI Contributions, Tax


Rate, and Net Pay. The form should look like this :

2. JUDO - Write a program which uses three Input Boxes to enter the
ratings of three judo players. To qualify to enter a competition the
three ratings have to add up to 20 or less. Display a message to say if
the team qualifies for the competition.

Use variables to store the judo player’s ratings and the total.

3. GUESS IT - Write a Number Guessing Program. A random number


between 1 and 20 will be generated and the user will have four
attempts to try and guess the number. After each guess the user will
be told if their guess was too high, too low or spot on.

Use a variable to store the random number and the users guess.

4. BAND NAMES - Write a Random Band Name Generator program.


The name will always be in the format : “THE Word1 Word2” For
example “The Smashing Pumpkins”.

There will be two lists (one for Word 1 and one for Word 2). There will
be a button to generate the random name. The user will also be able
edit the two list.

Use variables as appropriate.

5. LEARN IT - Write an interactive program to demonstrate to a student


the Useful Functions in Section 7 of this booklet.

Page : 35
VB.Net Guide Danny Fellows

Solution - Exercise 1 – Tax Calculations

'TAX CALCULATOR DANNY FELLOWS


'CALCULATE TAX FROM GROSS PAY, DEDUCTIONS AND ALLOWANCE
Option Explicit On
Public Class frmTax
Dim Pension As Decimal
Dim NI As Decimal
Dim TaxRate As Decimal
Dim NetPay As Decimal
Private Sub btnCalculateTax_Click(~~~~
txtGrossPay.Text = Format(txtGrossPay.Text, "currency")
Pension = txtGrossPay.Text * 0.09
NI = txtGrossPay.Text * 0.07
NetPay = txtGrossPay.Text - Pension - NI - 5000
If txtGrossPay.Text < 25000 Then
TaxRate = 20
Else
If txtGrossPay.Text > 50000 Then
TaxRate = 30
Else
TaxRate = 25
End If
End If
lblTax.Text = NetPay * TaxRate / 100
lblTax.Text = Format(lblTax.Text, "currency")
Me.AcceptButton = btnReset
End Sub
Private Sub btnReset_Click(~~~~
lblTax.Text = ""
txtGrossPay.Text = ""
txtGrossPay.Focus()
Me.AcceptButton = btnCalculateTax
End Sub
End Class

Page : 36
VB.Net Guide Danny Fellows

Solution – Exercise 3 – The Guess It Game

' GUESSIT DANNY FELLOWS


Option Explicit On
Public Class frmGuessIt
Dim RandomNumber As Integer
Dim Guess As String
Private Sub btnStart_Click(~~~~
Randomize()
RandomNumber = Int(Rnd() * 20) + 1
lblGuesses.Text = 0
txtGuess.Enabled = True
btnGuess.Enabled = True
txtGuess.Text = ""
txtGuess.Focus()
End Sub
Private Sub btnGuess_Click(~~~~
lblGuesses.Text = lblGuesses.Text + 1
Guess = txtGuess.Text
If Val(Guess) = RandomNumber Then
MsgBox("You Got It In " & lblGuesses.Text & " Goes")
txtGuess.Enabled = False
btnGuess.Enabled = False
Else
If lblGuesses.Text = 4 Then
MsgBox("You Ran Out Of Guesses. It Was " & RandomNumber)
txtGuess.Enabled = False
btnGuess.Enabled = False
Else
txtGuess.Text = ""
txtGuess.Focus()
If Val(Guess) < RandomNumber Then
MsgBox("Too Low")
Else
MsgBox("Too High")
End If
End If
End If
End Sub
End Class

Page : 37
VB.Net Guide Danny Fellows

7. A SUMMARY OF USEFUL FUNCTIONS

Val ( string ) - Converts a string value to numeric.

Str ( number ) - Converts a number value to a string.

Int ( number ) - Converts a number to an integer.

UCase ( string ) - Converts text to upper case.

LCase ( string ) - Converts text to lower case.

MsgBox ( ”string” ) - Displays a message in a dialog box.

InputBox ( “prompt” ) - Returns a value entered by the user into a dialog box.

Math.Abs ( number ) - Converts a number to an absolute (positive) value.

Len ( string ) - Returns the length of a string.

Rnd() - Generates a Random number between 0 and 0.9999

Math.Sqrt ( number ) - Returns the Square Root of a number.

IsNumeric ( string ) - Returns true if string is numeric or false if not.

Mid ( string , start , chars ) - Returns a specified number of


characters (chars ) from the middle
of the string.

Format ( string or number , mask ) - Formats a number or string to a mask:


Format ( txtPrice.text , “currency” )

Math.Round ( number, decimal places ) - Rounds a number to specified number


of decimal places.

Page : 38
VB.Net Guide Danny Fellows

8. VB Project - Toptastic Snowboarding

Toptastic Snowboarding is a snowboarder’s collective that has bought hostels in


top resorts around the world to provide affordable snowboarding holidays. Write a
Visual Basic application to calculate the overall price of a Toptastic Snowboarding
holiday.

The program will be used by travel agents. It must be user-friendly and fool proof.
The user will select from one of the resorts below :

Basic Holiday Price


Adult Price Child Price
1st Extra 1st Extra
Week Week Week Week

Pas De La Casa, Andorra £ 145 £ 105 £ 87 £ 67


Lake Tahoe, USA £ 556 £ 321 £ 318 £ 205
Tignes, France £ 250 £ 200 £ 187 £ 165
Whistler, Canada £ 378 £ 298 £ 378 £ 298
Sierra Nevada, Spain £ 276 £ 189 £ 230 £ 190
Picos Grande, Chile £ 678 £ 345 £ 456 £ 232
Churchill, New Zealand £ 1145 £ 245 £ 985 £ 203

The prices above include flights, transfers and accommodation. There is a


discount offered of one free place for the first ten members of the party and then

Page : 39
VB.Net Guide Danny Fellows

another free place for each five members after that. Children count as half
members. The discount applies only to the basic holiday price.

Additional Items

Board Boot Board Lift Insu- Lessons


Hire Hire Carriage Pass rance

Pas De La Casa £ 37 £ 15 £ 12 £ 85 £ 25 £ 50
Lake Tahoe £ 50 £ 20 £0 £ 155 £ 37 £ 89
Tignes £ 78 £ 29 £ 12 £ 120 £ 25 £ 65
Whistler £ 55 £ 27 £0 £ 145 £ 37 £ 123
Sierra Nevada £ 38 £ 20 £ 14 £ 100 £ 25 £ 90
Picos Grande £ 21 £9 £0 £ 54 £ 37 £ 34
Churchill £ 29 £ 11 £ 19 £ 78 £ 37 £ 45

The prices above are for one week. None of the items above are required, but
none of them can exceed the total number of members in the group.

The user will select the number of adults, children, weeks, snowboard hires, boot
hires, snowboard carriages, lift passes, insurances and lessons. All this
information will displayed on the screen along with the price of the additional
items, sub-totals for each additional item, any discounts, and the grand total.

There will be a calculation button which the user will press to calculate the grand
total for the party.

If the party is larger than 20 (adults and children) the whole party gets free
insurance.

Children are not permitted to travel alone.

If the user makes a mistake a warning message will appear and the entry cell will
be coloured red. It will revert to the normal colour when corrected.

Page : 40
VB.Net Guide Danny Fellows

9. VB Project - Smiley

Project Outline
Create a game in Visual Basic as specified below. The game will be user-friendly,
well designed and easy to play. Ensure the code is well commented and uses
representative variable and control names.

Project Specification
Smiley is our hero. He has to run across the screen from left to right without being
zapped by the lasers. Smiley will be a Picture Box loaded with the picture of the
smiley face. The three lasers will be vertical lines which will flash at regular but
different intervals. This flashing will be controlled by three timers.

Smiley will be moved to the right by clicking a control button. If Smiley is in the
way of a laser when it is on he gets zapped! If this happens he will stop smiling
and the movement button will be disabled. If Smiley reaches the right hand side of
the screen a message saying that he is home safely will be displayed. Also
Smiley’s time for the crossing will be displayed.

Variations
You may change the subject of the project as long as it still satisfies the following
criteria:

The user moves the target image across the screen.


There are at least three flashing or moving obstacles.
If the image touches an obstacle the user loses.
The time taken to reach home is recorded.
The game is user-friendly and has suitable instructions.

Project Contents
1. Front Cover.
2. Brief Explanation.
3. Design - User Interface Design (hand drawn)
- Flowchart for the RUN button
4. Printout of the Form.
5. Printout of the Code.

Page : 41
VB.Net Guide Danny Fellows

10. LOOPS – For…Next Do…Loop

Looping statements allow a block of code to be repeated.

FOR…NEXT

Use a FOR…NEXT loop when you know the number of times a loop will be
performed…

Using the FOR…NEXT Loop

Dim i As Integer

For i = 10 to 16 Step 2

MsgBox( “Hello “ & i )

Next i

Will Produce Message Boxes saying :

Hello 10
Hello 12
Hello 14
Hello 16

Notes : The Step part is optional


For…Next loops can be nested.

Page : 42
VB.Net Guide Danny Fellows

Exercises – For … Next Loops

1. 7 TIMES TABLES - Write a program to display the 7 times table in a


ListBox. When the user clicks on the ‘7 Times Table’ button the results will
be displayed in the ListBox up to 12 * 7 like this :

7
14
::::::
84

2. SUPER DOOPER TIMES TABLES – Update the program from exercise 1


so that the user can enter the value to be used for the times table and the
number of multiples. If, for example, the user entered value 6 up to 15 *,
the results should look like this :

1*6=6
2 * 6 = 12
::::::
15 * 6 = 90

3. VOWEL LANGUAGE - Write a program to count the number of vowels in a


sentence. The user will enter the sentence in a textbox. A loop will be
used to look at each letter in the sentence using the len and mid functions.
A label will be used to display a running count of the number of vowels in
the word.

4. POPULATION SURVEY - Write a program to calculate the results of a


population survey. The user will first enter the number of results they have,
and then that number of input boxes will appear and allow the user to enter
the population values. When the results have been entered the total and
average of the values will be displayed.

Page : 43
VB.Net Guide Danny Fellows

Solution - Exercise 1 - Seven Times Table

'SEVEN TIMES TABLE DANNY FELLOWS


'DISPLAY 7 TIMES TABLE IN A LISTBOX USING A FOR LOOP

Public Class frmSevenTimesTable

Private Sub btnSevenTimesTable_Click(~~~~~~

Dim i As Integer
Dim Result As Integer

For i = 1 To 12

Result = i * 7

lstTimesTable.Items.Add(Result)

Next

End Sub

End Class

Page : 44
VB.Net Guide Danny Fellows

Solution - Exercise 3 – Vowel Language

'VOWEL LANGUAGE DANNY FELLOWS


'COUNT THE NUMBER OF VOWELS IN A SENTENCE

Option Explicit On

Public Class frmVowels

Private Sub btnCountVowels_Click(~~~~~

Dim i As Integer
Dim Letter As Char

For i = 1 To Len(txtSentence.Text)

Letter = Mid(txtSentence.Text, i, 1)
Letter = UCase(Letter)

If Letter Like "[AEIOU]" Then


lblVowels.Text = lblVowels.Text + 1
End If

Next i

End Sub

Private Sub btnReset_Click(~~~~~

lblVowels.Text = 0
txtSentence.Text = ""
txtSentence.Focus()

End Sub

End Class

Page : 45
VB.Net Guide Danny Fellows

DO…LOOP

The code in a DO…LOOP will continue to be performed UNTIL or WHILE a


condition is true…

Using the DO…LOOP UNTIL

This piece of code will loop UNTIL the user enters ELEPHANT for the password.

Dim Password As String

Do

Password = InputBox(“Enter Password”)

Loop Until Password = “ELEPHANT”

Using the DO WHILE…LOOP

This piece of code will loop WHILE the total donations are less than 1000.

Dim Donation As Single


Dim Total As Single

Total = 0

Do While Total < 1000

Donation = InputBox(“Enter Donation”)

Total = Total + Val(Donation)

Loop

Page : 46
VB.Net Guide Danny Fellows

Exercises - Do ... Loop

1. AGE – This program will have a button which when clicked will display an
InputBox. The user will enter their age into the InputBox. Their age must be
between 10 and 120 inclusive. The user should re-enter until the value is in
the correct range. When a correct age is entered a MessageBox will display
the message 'Thank you'.

2. PASSWORD - Write a password program. The user will enter a password,


using an InputBox. A secret picture will appear when they enter the correct
password. The user will have three attempts to enter the password correctly
otherwise the program will display the message “Too Many Attempts” and the
program will close. The user will be able to exit without penalty by pressing
the Cancel button on the InputBox.

3. LOTTERY - Write a program to generate Lottery Numbers. The numbers will


be generated when the user click a button and will appear in a ListBox. Each
of the six numbers should be randomly generated and be between 1 and 49.
You need to ensure that numbers cannot be repeated.

4. EXPENSES - Write a program which lets a doughnut salesman calculate his


weekly mileage expense claim. The program should let him enter the
number of trips he has made this week. This entry should be validated,
correct values will be between zero and seven. If the entry is invalid, he
must re-enter until he gets it right. The salesman should then enter his
mileage for the number of journeys he has specified (one journey at a time )
into a series of InputBoxes and the program will display his total mileage
expense claim based on 8p per mile.

5. QUIZ - Write a quiz program with four questions. The user should be able to
have three tries at answering each question. At the end of the quiz the score
should be displayed as well as an option to run the test again. Keep a record
of the highest score. Answers will be entered using InputBoxes.

Page : 47
VB.Net Guide Danny Fellows

Solution – Exercise 2 - Password

'PASSWORD DANNY FELLOWS


'PASSWORD PROGRAM - 3 ATTEMPTS

Public Class frmPassword

Private Sub btnPassword_Click(~~~~~

Dim Attempts As Integer


Dim Password As String

Attempts = 0

Do

Password = UCase(InputBox("Enter Password"))

Attempts = Attempts + 1

If Password <> "CHEESE" And Attempts < 3 And Password <> "" Then
MsgBox(Str(Attempts) & ". Wrong....Try again")
End If

Loop Until Password = "CHEESE" Or Attempts = 3 Or Password = ""

If Password = "CHEESE" Then


pctsecret.Visible = True
Else
If Password = "" Then
MsgBox("You're Out...No Penalty")
Else
MsgBox("3. Too Many Attempts - Bye Bye")
End
End If
End If

End Sub

End Class

Page : 48
VB.Net Guide Danny Fellows

Solution – Exercise 3 - Lottery

Use a ListView box here.

A ListView Box has columns.

Call it lvwNum

'LOTTERY DANNY FELLOWS


'GENERATE 6 LOTTERY NUMBERS AND CHECK FOR DUPLICATES
Option Explicit On
Public Class frmLottery
Private Sub btnGenerateLotteryNumbers_Click(~~~~~
Dim i As Integer
Dim j As Integer
Dim Duplicate As Boolean
Randomize()
Do
'GENERATE 6 LOTTERY NUMBERS 1-49
lvwNum.Items.Clear()
For i = 0 To 5
lvwNum.Items.Add(Int(Rnd() * 49) + 1)
Next i
'CHECK FOR DUPLICATES
Duplicate = False
For i = 0 To 5
For j = 0 To 5
If i <> j And lvwNum.Items(j).text = lvwNum.Items(i).text Then
Duplicate = True
End If
Next j
Next i
Loop Until Not Duplicate
End Sub
End Class

Page : 49
VB.Net Guide Danny Fellows

11. USING PROCEDURES


A procedure is a block of code that can be called from anywhere in the program.
When a procedure is called the procedure is processed and then control passes to
the next line after the procedure call. Procedures are used to reduce the need for
repeating code and also to help in the design and layout of code.

To Create A Procedure – Simply add the appropriate code to the program...

Using a Procedure

'BARGAIN BIKES DANNY FELLOWS


'USE A PROCEDURE TO CALCULATE THE DISCOUNT ON A BIKE SALE
Public Class frmPriceCalculator
Private Sub txtPrice_TextChanged(~~~~~
CalculatePrice()
End Sub
Private Sub txtQuantity_TextChanged(~~~~~
CalculatePrice()
End Sub
Private Sub txtDiscountP_TextChanged(~~~~~
CalculatePrice()
End Sub

Public Sub CalculatePrice()


txtDiscount.Text = Val(txtPrice.Text) * Val(txtDiscountP.Text) / 100
txtTotal.Text = (Val(txtPrice.Text) - Val(txtDiscount.Text)) * _
Val(txtQuantity.Text)
txtDiscount.Text = Format(txtDiscount.Text, "currency")
txtTotal.Text = Format(txtTotal.Text, "currency")
End Sub

End Class

Page : 50
VB.Net Guide Danny Fellows

Exercises – Procedures

1. VW PRICE CALCULATOR (WITH PROCEDURE) - The VW Price


Calculator program (solution on page 20) repeats the following code six
times.
txtExtras.Text =
chkSunRoof.Checked * 250 + chkAirCon.Checked * 340 + _
chkRoofRack.Checked * 120 + chkCDPlayer.Checked * 270 + _
chkTowBar.Checked * 160 + chkBabySeat.Checked * 78

Add a procedure to eliminate this code repetition.

2. COLOUR EDITOR (WITH PROCEDURE) - The Colour Editor program


(solution on page 22) repeats the following code six times.
Me.BackColor = System.Drawing.ColorTranslator. _
FromOle(RGB(hsbRed.Value, hsbGreen.Value, hsbBlue.Value))

Add a procedure to eliminate this code repetition.

3. SPACE SHUTTLE - Write a program to calculate the total weight that the
space shuttle will carry on its next flight. The user should enter the weight
of each of the four crew, the fuel load, food, water, and scientific
experiments. The crew will enter their weights in pounds. These will be
converted to kgs (2.2 pounds to a kg). All the other items will be entered in
kgs. Use a procedure to continually calculate the total weight in kgs. If
the weight exceeds 2000kgs a warning message will appear.

4. RECURSION / ITERATION - Write two programs to display the ten times


table in a ListBox. One will use a procedure with a normal iterative loop (i.e
a For…Next Loop). The other will use a recursive procedure. Recursion is
when a procedure calls itself....

Public Sub TimesTable()


lstTimesTable.Items.Add (Table * Counter)
Counter = Counter + 1
If Counter <= 10 Then
TimesTable
End If
End Sub

Page : 51
VB.Net Guide Danny Fellows

12. USING FUNCTIONS


A function is a block of code that can be called from anywhere in the program.
When a function is called parameters are usually passed and a resultant value is
returned.

In the program below a function (Largest) is used to work out the largest of two
numbers in two text boxes. The result of the function is returned as ‘Largest’:

Public Class frmFunctions


Private Sub btnLargest_Click(~~~~~~~~~~) Handles btnLargest.Click
lblResult.Text = Largest(txtNumber1.Text, txtNumber2.Text)
End Sub
Function Largest(ByVal Number1 As Decimal, ByVal Number2 As Decimal) As Decimal
If Number1 = Number2 Then
Largest = 0
Else
If Number1 > Number2 Then
Largest = Number1
Else
Largest = Number2
End If
End If
End Function
End Class

Programming Exercises - Functions

Copy this program and then add more buttons to this program to calculate other
useful values from these two numbers such as ‘Sum of the Squares’, ‘Area of
Rectangle with these sides’, ‘Average of the two numbers’.

Use a new function each time.

Page : 52
VB.Net Guide Danny Fellows

13. USING ARRAYS


An Array is a variable in Visual Basic which can have more than one element. The
index number for an array starts from 0. For example:

Dim Player(10) As String

Player(0) = “David Seaman”


Player(1) = “Stuart Pearce”
Player(2) = “Tony Adams”

Etc….

To Add the Players to a ListBox the code would be:

For i = 0 To 10
lstTeam.Items.Add(Player(i))
Next i

Two Dimensional Arrays


You can declare arrays with two, or more dimensions. For example, a football
tournament with five teams:

Dim Player(4,10) As String

Player(0,0) = “David Seaman”


Player(0,1) = “Stuart Pearce”
Player(0,2) = “Tony Adams”

Etc….

To Add the Players to a ListBox the code would be:

For i = 0 To 4
For j = 0 To 10
lstTeam.Items.Add(Player(i,j))
Next j
Next i

Page : 53
VB.Net Guide Danny Fellows

Noughts & Crosses – Two-Dimensional Arrays Example


Copy this code into a VB Project. Try and improve the game so it is more playable.

Public Class frmBoard


Dim Board(2, 2) As Char '### DECLARE A 3x3 ARRAY ###
Dim Goes As Integer
Private Sub frmBoard_Load(sender As Object, e As EventArgs) Handles MyBase.Load
SetUpBoard()
End Sub
Private Sub SetUpBoard()

For x = 0 To 2
For y = 0 To 2
Board(x, y) = "-"
Next y
Next x
DrawBoard()
Goes = 0
End Sub
Private Sub DrawBoard()
lstBoard.Items.Clear()
For x = 0 To 2
lstBoard.Items.Add(Board(x, 0) & " " & Board(x, 1) & " " & Board(x, 2))
Next x
End Sub
Private Sub btnGo_Click(sender As Object, e As EventArgs) Handles btnGo.Click
Dim Column As Integer
Dim Row As Integer
Do
Row = InputBox("Your Go - Enter Row 0-2") '###### PLAYER'S GO ######
Column = InputBox("Enter Column 0-2")
Board(Row, Column) = "X"
DrawBoard()
Goes = Goes + 1
If Goes < 5 Then '###### COMPUTER'S GO ######
MsgBox("Computer's Go")
Do
Row = Int(Rnd() * 3)
Column = Int(Rnd() * 3)
Loop Until Board(Row, Column) = "-"
Board(Row, Column) = "O"
DrawBoard()
End If
Loop Until Goes = 5
MsgBox("That's It. Play Again?")
SetUpBoard()
End Sub

End Class

Page : 54
VB.Net Guide Danny Fellows

14. USING MULTIPLE FORMS


A Visual Basic Project can include one or more forms. To add forms to a project
select ‘Add Windows Form’ from the Project Menu in Visual Basic. Each form will
be saved as a separate file.

There are a number of commands which can be used to move between forms.
You must use Me as the name of the current form :

frmFootball.Show() - will display the form frmFootball (loading it if necessary).

Me.Hide() - will hide the current form (not unloading it)


Me.Close() - will close the current form.

If you Hide a form and then Show it again, the Form_Load code will not run. If you
want the Form_Load code to run when you reload the form use Me.Close().

USING A MODULE
A Module is used to declare global variables, procedures and record types when
you have a project with more than one form. To add a Module to the project select
the ‘Add Module’ option from the Project Menu. The Module will be saved as a
separate file.

An Example of the contents of a Module :

Module modShopping

Public i As Integer
Public j As Integer
Public TotalPrice As Single
Public Surname As String

End Module

Page : 55
VB.Net Guide Danny Fellows

15. FILE HANDLING

Random (or Direct) files are made up of records, just like a database. The record structure
is setup in the module. Records are directly accessed using a record number and can be
updated and written back to the file.

Below is the code needed for Random file processing in VB.net. The example used is a
database of footballers storing Name, Team, Games and Goals.

Setting up the Record Structure


Declare the record structure (Player) in the module and declare a record (PlayerRecord)
with that structure:

Module Module1
Public Structure Player
<VBFixedString(15)> Dim Name As String
<VBFixedString(15)> Dim Team As String
Dim Games As Integer
Dim Goals As Integer
End Structure
Public PlayerRecord As Player
End Module

The Record
When data is read in from a file it is first read into the record. It can then be moved into
TextBoxes for display, or used in any other way:

The File (on Hard Disk) VB.net Form


Rec Name Team Games Goals Name Hal...
1 Bob Pompey 62 18 Team Pompey
2 Tom Chelsea 78 19 Games 18....
3 Hal Pompey 18 11
4 Kim Hull 99 10 Goals 11....

The Record Example:


PlayerRecord.Name = txtName.text
FilePut Player
.Name Hal Example:
FileGet .Team Pompey txtName.text = PlayerRecord.Name
.Games 18
.Goals 11

Page : 56
VB.Net Guide Danny Fellows

Opening the File


Before a file can be used it must be opened with a unique file number (eg 1) :

PlayerFilePath = CurDir() & "\PlayerFile.dat"


FileOpen(1, PlayerFilePath, OpenMode.Random, , , Len(PlayerRecord) )

FileOpen( File Number , File Path , File Type , , ,Record Length )

Put a Record into the File


To save data from TextBoxes on a VB.net form into a file on the hard disk: First the data is
copied from the TextBoxes to the Record :

PlayerRecord.Name = txtName.Text
PlayerRecord.Team = txtTeam.Text
PlayerRecord.Games = txtGames.Text
PlayerRecord.Goals = txtGoals.Text

The FilePut command is then used to save the record to the file.

FilePut(1, PlayerRecord, CInt(lblRecordNumber.Text))

FilePut( File Number , Record Name , Record Number)

Get a Record from the File


The FileGet command is used to read a record from the file.

FileGet(1, PlayerRecord, CInt(lblRecordNumber.Text))

FileGet( File Number , Record Name , Record Number )

The data from the record would then be copied into textboxes :

txtName.Text = PlayerRecord.Name
txtTeam.Text = PlayerRecord.Team
txtGames.Text = PlayerRecord.Games
txtGoals.Text = PlayerRecord.Goals

Closing and Deleting a File


The Kill command is delete the entire file. You must close the file before it is deleted:

FileClose(1)
Kill(PlayerFilePath)

Page : 57
VB.Net Guide Danny Fellows

Example Project – Footballers Database


This program will be used to maintain a database of footballers. Sample data:

Record Name Team Games Goals


Number
1 Peter Beardsley Newcastle 129 46
2 Kevin Keegan Liverpool 230 68
3 Nwankwo Kanu Portsmouth 71 19
4 Paul Gascoigne Newcastle 92 21
5 Paul Walsh Portsmouth 94 19

Note : This program is a simplified version which contains no input validation. The user
must enter a number for Games and Goals or the program will crash. The user must click
Save Record to save the data. There is no Delete Record option.

'FOOTBALLERS DATABASE - BASIC VERSION DANNY FELLOWS


'MODULE - CREATES THE FILE STRUCTURE AND SETS UP GLOBAL VARIABLES

Module Module1

Public Structure Player


<VBFixedString(15)> Dim Name As String
<VBFixedString(15)> Dim Team As String
Dim Games As Integer
Dim Goals As Integer
End Structure

Public PlayerRecord As Player

Public PlayerFilePath As String


Public TempFilePath As String

End Module

Page : 58
VB.Net Guide Danny Fellows

'FOOTBALLERS DATABASE - BASIC VERSION DANNY FELLOWS


'KEEP A DATABASE OF FOOTBALLERS NAME, TEAM, GAMES AND GOALS
Option Explicit On
Public Class frmPlayers

Private Sub frmPlayers_Load(~~~~~~


PlayerFilePath = CurDir() & "\PlayerFile.dat"
FileOpen(1, PlayerFilePath, OpenMode.Random, , , Len(PlayerRecord))
lblNumberOfRecords.Text = LOF(1) / Len(PlayerRecord)
If lblNumberOfRecords.Text > 0 Then ReadRecord()
End Sub

Private Sub btnSave_Click(~~~~~


SaveRecord()
End Sub

Private Sub SaveRecord()


PlayerRecord.Name = txtName.Text
PlayerRecord.Team = txtTeam.Text
PlayerRecord.Games = txtGames.Text
PlayerRecord.Goals = txtGoals.Text
FilePut(1, PlayerRecord, CInt(lblRecordNumber.Text))
lblNumberOfRecords.Text = LOF(1) / Len(PlayerRecord)
End Sub

Public Sub ReadRecord()


FileGet(1, PlayerRecord, CInt(lblRecordNumber.Text))
txtName.Text = PlayerRecord.Name
txtTeam.Text = PlayerRecord.Team
txtGames.Text = PlayerRecord.Games
txtGoals.Text = PlayerRecord.Goals
End Sub

Private Sub btnAddRecord_Click(~~~~~~


lblRecordNumber.Text = lblNumberOfRecords.Text + 1
txtName.Text = ""
txtTeam.Text = ""
txtGames.Text = ""
txtGoals.Text = ""
txtName.Focus()
End Sub

Page : 59
VB.Net Guide Danny Fellows

Private Sub btnNextRecord_Click(~~~~~~


SaveRecord()
lblRecordNumber.Text = lblRecordNumber.Text + 1
If Val(lblRecordNumber.Text) > Val(lblNumberOfRecords.Text) Then
lblRecordNumber.Text = lblNumberOfRecords.Text
End If
ReadRecord()
End Sub

Private Sub btnPreviousRecord_Click(~~~~~


SaveRecord()
lblRecordNumber.Text = lblRecordNumber.Text - 1
If lblRecordNumber.Text < 1 Then
lblRecordNumber.Text = 1
End If
ReadRecord()
End Sub

Private Sub btnDeleteFile_Click(~~~~~


DeleteFile()
End Sub

Private Sub DeleteFile()


If lblNumberOfRecords.Text > 0 Then
FileClose(1)
Kill(PlayerFilePath)
FileOpen(1,PlayerFilePath,OpenMode.Random,,,Len(PlayerRecord))
lblRecordNumber.Text = 1
lblNumberOfRecords.Text = 0
End If
txtName.Text = ""
txtTeam.Text = ""
txtGames.Text = ""
txtGoals.Text = ""
txtName.Focus()
End Sub

Private Sub btnQuit_Click(~~~~~


End
End Sub

End Class

Page : 60
VB.Net Guide Danny Fellows

Creating a Report in a ListBox


The best way to print a report is to first create it in a ListBox. This means that the user can
view it and only print it if required. This also cuts down on wasted printouts during
program development. Add a form to the Footballers Database program containing a
ListBox to show the report:

The Following code will first allow the user to enter the required team and then display a
list of the players who played for that team and the goals that they scored:
'TEAM GOALS REPORT DANNY FELLOWS
'PRODUCE A REPORT FOR A CHOSEN TEAM SHOWING NAME AND GOALS
Public Class frmReports
Private Sub btnTeamGoalsReport_Click(~~~~~
Dim i As Integer
Dim ChosenTeam As String
ChosenTeam = InputBox("Enter Team Name", "Team Report")
ChosenTeam = UCase(ChosenTeam)
lstReport.Items.Clear()
lstReport.Items.Add("TEAM GOALS REPORT : " & ChosenTeam)
lstReport.Items.Add("==================================")
lstReport.Items.Add("")
lstReport.Items.Add("Name" & Space(25) & "Goals")
lstReport.Items.Add("----" & Space(25) & "-----")
For i = 1 To (LOF(1) / Len(PlayerRecord))
FileGet(1, PlayerRecord, i)
If UCase(PlayerRecord.Team) = ChosenTeam Then
lstReport.Items.Add(PlayerRecord.Name & " " & PlayerRecord.Goals)
End If
Next
End Sub
End Class

Page : 61
VB.Net Guide Danny Fellows

Deleting Records from a File in VB.net


To delete records from a random access file (for example in the Player File) in Visual
Basic you will have to go through the following steps :

1. Set the Name to “DELETE” and Save the record.


2. Open a Temporary File.
3. Loop through the Player File and copy those records that are to be kept (ie
Name <> “DELETE”) into the Temporary File.
4. Delete the Player File.
5. Rename the Temporary File to the name of the Player File.

This example goes with the Footballers Database Example :

Private Sub cmdDeleteRecord_Click(~~~~


If lblNumberOfRecords.Text > 1 Then
txtName.Text = "DELETE"
SaveRecord()
Dim i As Integer
Dim NumOfNewRecords As Integer
TempFilePath = CurDir() & "\Temp.dat"
FileOpen(2, TempFilePath, OpenMode.Random,,,len(PlayerRecord))
NumOfNewRecords = 1
For i = 1 To lblNumberOfRecords.Text
FileGet(1, PlayerRecord, i)
If PlayerRecord.Name <> "DELETE" Then
FilePut(2, PlayerRecord, NumOfNewRecords)
NumOfNewRecords = NumOfNewRecords + 1
End If
Next i
FileClose(1)
FileClose(2)
Kill(PlayerFilePath)
FileCopy(TempFilePath, PlayerFilePath)
Kill(TempFilePath)
FileOpen(1, PlayerFilePath, OpenMode.Random,,,Len(PlayerRecord))
lblRecordNumber.Text = 1
lblNumberOfRecords.Text = lblNumberOfRecords.Text - 1
ReadRecord()
Else
DeleteFile()
End If
End Sub

Page : 62
VB.Net Guide Danny Fellows

PRINTING

Printing the Contents of a ListBox


The best way to print a Report form VB.net is to first build the report in a ListBox, and then
when you are happy with the layout and structure of the report send it to the printer.

To print you first have to add two Printer Controls to the project:

• PrintDialog
• PrintDocument

Note : You need to set the Document property of PrintDialog to PrintDocument:

Page : 63
VB.Net Guide Danny Fellows

Code to Print the Contents of a ListBox

Add the following code to your program. When the user clicks on the Print Button the
Printer Dialog Box will open and the contents of the ListBox will be printed.

'PRINT REPORT
'PRINT THE CONTENTS OF THE LISTBOX TO THE PRINTER

Public Class frmPrint

Public itemProgress As Integer = 0

Private Sub btnPrint_Click(~~~~~

If (PrintDialog.ShowDialog() = Windows.Forms.DialogResult.OK) Then


PrintDialog.Document.Print()
End If

End Sub

Private Sub PrintDocument_PrintPage(~~~~~

Dim yMargin As Integer = e.MarginBounds.Y


Dim xMargin As Integer = e.MarginBounds.X
Dim currentpageItemProgress As Integer = 0

For Each item As String In lstReport.Items

If (currentpageItemProgress >= itemProgress) Then

e.Graphics.DrawString(item, lstReport.Font, _
New SolidBrush(lstReport.ForeColor), xMargin, yMargin)
yMargin += lstReport.Font.Size + 10
itemProgress += 1

If (yMargin >= e.MarginBounds.Y + e.MarginBounds.Height And _


itemProgress <= lstReport.Items.Count) Then
e.HasMorePages = True
currentpageItemProgress = 0
End If

End If
currentpageItemProgress += 1
Next
End Sub

Private Sub PrintDoc_EndPrint(~~~~~


itemProgress = 0
End Sub

End Class

Page : 64
VB.Net Guide Danny Fellows

Hashing Algorithms
Record numbers in a Random Access File start with 1 and increment for each record. So
far we have ensured that a record identifier in our data matches the Record Number in the
file, but what if the record identifier is for example DF101. We need to be able to turn this
record identifier into a numeric record address. This is important because we want to be
able to access each record directly without having to search through the file. To turn the
record identifier into an address we use a Hashing Algorithm…

The Hashing Algorithm will produce a sensible Record Number from any Record Identifier.
A good hashing algorithm will avoid producing too many clashes and will also ensure that
record numbers produced are not spread too much.

Example Hashing Algorithm

RecordNo = 0

For i = 1 To Len(RecordID)
RecordNo = RecordNo + i * (Asc(Mid(RecordID, i, 1)))
Next i

RecordNo = RecordNo Mod 50 + 1

This Hashing Algoirthm takes RecordID and turns it into RecordNo. It will produce record
numbers between 1 and 50. Here are some examples :

Record ID Record Number


DF101 * 43 *
AA999 30
AA998 25
D45 32
F67 44
FB561 23
FB562 28
FB563 33
FB519 * 43 *

* It can be seen that the first and last Record IDs (DF101 and FB519) produce the same
record number (43). A check for clashes would need to be made to ensure an existing
record is not overwritten. The new record would take the next available spare record
number.

Page : 65

You might also like