VB Net Booklet
VB Net Booklet
Page : 1
VB.Net Guide Danny Fellows
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
The Form
Project
Explorer
Properties
Window
Toolbox
Page : 4
VB.Net Guide Danny Fellows
Label
Text Box
A Text Box is used to display information, but also the user can enter data into a
Text Box.
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.
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
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 :
For Example : If you save a project called Greetings, the files for that project will
be saved in the following folder :
To open the project run the Microsoft Visual Studio Solution file :
Page : 6
VB.Net Guide Danny Fellows
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.
End Sub
End Class
Page : 7
VB.Net Guide Danny Fellows
1) Open a new Visual Basic project and set up the form as indicated below :
txtNum1
txtNum2
btnAdd
txtResult
Note The val( ) function tells VB that the text box contents is numeric.
Page : 8
VB.Net Guide Danny Fellows
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.
The user’s converted details will then be displayed in the following format :
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.
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
Page : 11
VB.Net Guide Danny Fellows
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.
Use the visible property to make the statements appear and disappear…
Eg. txtStatement1.visible = true
Page : 12
VB.Net Guide Danny Fellows
Page : 13
VB.Net Guide Danny Fellows
Picture Box
A Picture Box is used to display pictures on the Form.
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.
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.
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.
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.
Page : 15
VB.Net Guide Danny Fellows
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.
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.
Page : 16
VB.Net Guide Danny Fellows
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))
Page : 17
VB.Net Guide Danny Fellows
Page : 18
VB.Net Guide Danny Fellows
End Class
Page : 19
VB.Net Guide Danny Fellows
Page : 20
VB.Net Guide Danny Fellows
End Class
Page : 21
VB.Net Guide Danny Fellows
End Class
Page : 22
VB.Net Guide Danny Fellows
A user enters their age to gain access to a night club. They have to be over 18..
Else
End If
Conditions
More than one condition can be used with AND and OR operators.....
End If
End If
Page : 23
VB.Net Guide Danny Fellows
1) Open a new Visual Basic project and set up the form as indicated below :
txtPassword.Text = UCase(txtPassword.Text)
End Sub
End Class
Page : 24
VB.Net Guide Danny Fellows
1) Open a new Visual Basic project and set up the form as indicated below :
Picture :
pctWine
Buttons
btnUp
btnLeft
btnRight Picture :
btnDown pctSkier
3) The code attached to the remaining Buttons will be similar to this but line:
pctSkier.Top = pctSkier.Top – 50 will change slightly.
Page : 25
VB.Net Guide Danny Fellows
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.
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
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
This is the program code for the Cinema Exercise on the previous page using first
the IF statement and then the CASE 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
Case 1
lblFilm.text = “Local Hero”
Case 2
lblFilm.text = “Warriors”
Case 3
lblFilm.text = “Blues Brothers”
Case Else
lblFilm.text = “Error”
End Select
Page : 27
VB.Net Guide Danny Fellows
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.
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.
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.
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
Page : 29
VB.Net Guide Danny Fellows
Page : 30
VB.Net Guide Danny Fellows
Variable Scope
Local Variables declared in a procedure can only be used in that procedure.
Constants
Constants are declared with a value and keep that value throughout the program.
To generate a Random Number between Min and Max we use the code:
RandomNumber = Int ( rnd() * ( Max – Min + 1 )) + Min
Page : 31
VB.Net Guide Danny Fellows
User-defined formats.
Page : 32
VB.Net Guide Danny Fellows
Page : 33
VB.Net Guide Danny Fellows
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.
Page : 34
VB.Net Guide Danny Fellows
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.
Use a variable to store the random number and the users guess.
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.
Page : 35
VB.Net Guide Danny Fellows
Page : 36
VB.Net Guide Danny Fellows
Page : 37
VB.Net Guide Danny Fellows
InputBox ( “prompt” ) - Returns a value entered by the user into a dialog box.
Page : 38
VB.Net Guide Danny Fellows
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 :
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
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.
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:
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
FOR…NEXT
Use a FOR…NEXT loop when you know the number of times a loop will be
performed…
Dim i As Integer
For i = 10 to 16 Step 2
Next i
Hello 10
Hello 12
Hello 14
Hello 16
Page : 42
VB.Net Guide Danny Fellows
7
14
::::::
84
1*6=6
2 * 6 = 12
::::::
15 * 6 = 90
Page : 43
VB.Net Guide Danny Fellows
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
Option Explicit On
Dim i As Integer
Dim Letter As Char
For i = 1 To Len(txtSentence.Text)
Letter = Mid(txtSentence.Text, i, 1)
Letter = UCase(Letter)
Next i
End Sub
lblVowels.Text = 0
txtSentence.Text = ""
txtSentence.Focus()
End Sub
End Class
Page : 45
VB.Net Guide Danny Fellows
DO…LOOP
This piece of code will loop UNTIL the user enters ELEPHANT for the password.
Do
This piece of code will loop WHILE the total donations are less than 1000.
Total = 0
Loop
Page : 46
VB.Net Guide Danny Fellows
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'.
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
Attempts = 0
Do
Attempts = Attempts + 1
If Password <> "CHEESE" And Attempts < 3 And Password <> "" Then
MsgBox(Str(Attempts) & ". Wrong....Try again")
End If
End Sub
End Class
Page : 48
VB.Net Guide Danny Fellows
Call it lvwNum
Page : 49
VB.Net Guide Danny Fellows
Using a Procedure
End Class
Page : 50
VB.Net Guide Danny Fellows
Exercises – Procedures
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.
Page : 51
VB.Net Guide Danny Fellows
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’:
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’.
Page : 52
VB.Net Guide Danny Fellows
Etc….
For i = 0 To 10
lstTeam.Items.Add(Player(i))
Next i
Etc….
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
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
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 :
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.
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
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.
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:
Page : 56
VB.Net Guide Danny Fellows
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.
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
FileClose(1)
Kill(PlayerFilePath)
Page : 57
VB.Net Guide Danny Fellows
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.
Module Module1
End Module
Page : 58
VB.Net Guide Danny Fellows
Page : 59
VB.Net Guide Danny Fellows
End Class
Page : 60
VB.Net Guide Danny Fellows
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
Page : 62
VB.Net Guide Danny Fellows
PRINTING
To print you first have to add two Printer Controls to the project:
• PrintDialog
• PrintDocument
Page : 63
VB.Net Guide Danny Fellows
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
End Sub
e.Graphics.DrawString(item, lstReport.Font, _
New SolidBrush(lstReport.ForeColor), xMargin, yMargin)
yMargin += lstReport.Font.Size + 10
itemProgress += 1
End If
currentpageItemProgress += 1
Next
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.
RecordNo = 0
For i = 1 To Len(RecordID)
RecordNo = RecordNo + i * (Asc(Mid(RecordID, i, 1)))
Next i
This Hashing Algoirthm takes RecordID and turns it into RecordNo. It will produce record
numbers between 1 and 50. Here are some examples :
* 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