Program Examples
Program Examples
To input data in Visual Basic there are lots of different form controls that you can use to do this, the
most common ones are text boxes and combo boxes.
The second part to it is creating the code to make the user interface do/display something.
When creating an interface, there are different types of form controls. Some of those that you will
use are:
In Visual Studio on the left hand side you have the toolbox, this is where you can drag and drop
your form controls. It looks like this:
頁
:
When you have dragged your form controls onto your form, you need to name them. You should
add a prefix to any form control, the common ones are:
Labels - lbl
Text Boxes - txt
Combo Boxes - cmb
List Boxes - lst
Buttons - btn
If you had a text box where the user enters their name a suitable name would be txtName.
Difference between naming a control and changing the text You must always name controls,
this can be done in the properties next to the option name, as shown below:
頁
:
If you want to change what the form control says on it, you change the option text, as shown
below:
Interface
頁
:
Code when btnRun clicked
The text “You entered the word” is joined with the text box txtWord. As the user entered the word
Hello it takes what it is in the text box and adds it into the message box.
Interface
頁
:
Code when btnBirthday clicked
MessageBox.Show("Hello " & txtName.Text & vbNewLine & "Your birthday month is
" & lstMonth.Text &
" and the day of the birthday this year is " & cmbDay.Text)
Interface
MessageBox.Show("Address Details" & vbNewLine & "Street: " & txtNumber.Text &
" " &
txtStreet.Text & vbNewLine & "Town/City: " & txtTown.Text & vbNewLine &
"County: " & txtCounty.Text & vbNewLine & "Postcode: " & txtPostcode.Text)
To add data to a list box you need to use the following code:
You can add multiple rows of data to a list box. You can simply change the information in the text
boxes and click the button again. vbTab is used to put a tab space between the two pieces of data.
Sometimes when you use list boxes it makes it difficult to make the formatting look neat, this is
shown in the screenshot above where the data is not lined up. To overcome this problem you can
use a list view.
With a list view box you can add columns and headings to make it look like a table, like the
example shown below:
頁
:
When you add a list view control, you have to change a property to get it to work. Change the view
from Large Icon to Details, like shown below:
The code for when the button is clicked needs to follow the following format:
This is because there are only two pieces of information, therefore you only need to fill in the
information you want in two of the columns.
頁
:
As well as adding code for when the button is pressed, you also need to add the column headings
when the form loads. You should double click on the form itself and add the code in this subroutine.
The format of the code for the column headings is:
In this example as there are two headings the code would be:
Interface
頁
:
Private Sub btnAdd_Click(sender As System.Object, e As System.EventArgs) Hand
les btnAdd.Click
lstOutput.Items.Add(New ListViewItem({txtName.Text, txtScore1.Text, txtSc
ore2.Text, txtScore3.Text}))
End Sub
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handle
s MyBase.Load
lstOutput.Columns.Add("Name", 150, HorizontalAlignment.Left)
lstOutput.Columns.Add("Score 1", 75, HorizontalAlignment.Center)
lstOutput.Columns.Add("Score 2", 75, HorizontalAlignment.Center)
lstOutput.Columns.Add("Score 3", 75, HorizontalAlignment.Center)
End Sub
Variables
A variable is used to temporarily store a piece of data.
For example:
In the code above the variable is called number1 and the value it is storing is 10. Variables can
hold any type of data. Using variables makes it easier for people to understand what is going on. In
Visual Basic you need to define a variable before you can use it. To do this you type Dim before the
variable name the first time you use it. You should then say what type of data you think it is. In this
example number1 is an integer therefore the code to define a variable called number1 as an
integer is Dim number1 as Integer
For example:
頁
:
Dim cost As Decimal = 15.5
Dim VAT As Decimal = 3.1
Dim total_cost As Decimal = cost + VAT
Interface
'three variables that store the text box inputs from the interface as a decim
al
Dim height As Decimal = txtHeight.Text
Dim width As Decimal = txtWidth.Text
Dim depth As Decimal = txtDepth.Text
'calculation to work out the capacity
Dim capacity As Decimal = (height * width * depth) / 1000
'outputs the capacity of the water tank
MessageBox.Show("The tank holds " & Decimal.Round(capacity, 2).ToString & " l
itres of water")
Interface
For example: IF you wake up in the morning and it is raining THEN you will take a coat to school
OTHERWISE you wont.
IF the day is a Saturday AND the alarm clock goes off THEN you might turn it off and stay in bed
OTHERWISE you might get up.
Life is full of decisions that you will make depending on certain conditions, computers are no
different.
if-else
For a computer to make decisions based on a condition, you must use an IF statement, it has the
following structure:
頁
:
If condition Then
true
several instructions that are executed
if the calcualation evaluates to True
Else
false
several instructions that are exectued
if the condition evaluates to False
End If
after the if is the condition age >= 18 , this is checking to see if the age variable is more
than or equal to 18.
after that line is code is the code that will only be run if that condition is True . If it is true it
will display a message box that says You are an adult .
the word else then follows. The instructions underneath this are what will be run only if that
condition is False . If it is false it will display a message box that says You are still a
child .
if-elseif-else
An IF statement with an else will only allow you to check a single condition, however if you have
more than one condition to check you can use if..elseif..else
NOTE: It doesn’t need to use Elseif to see if the colour is Green as if it isn’t Red or Amber it
must be Green , therefore you can just use else if there are not other options to consider.
Interface
'stores the user selection from the combo box in the variable city
Dim city As String = cmbCity.Text
'checks if the city variable has London stored in it
If city = "London" Then
'displays correct if the condition is true
MessageBox.Show("Correct, the capital city of England is: " & city)
Else
'displays wrong if they have entered something else
MessageBox.Show("Wrong, try again!")
End If
Interface
NOTE: When ElseIf is used it will only check the next condition If the previous condition is
false.
Interface
there is no Else on this If , you do not need to have one. An if can just check a condition
and do something if it is True and nothing if it is False
in the MessageBox.Show() command the cost is formatted to currency, this is done by
writing FormatCurrency(variable)
There are some simple ways in which you can validate programs, these are:
Interface
IsNumeric will return a value either True or False after checking to see if a variable or form
control is a number. You can then use an If to determine what to do.
Number
entered
頁
:
Text entered
Interface
If Len(txtNumber.Text) = 0 Then
MessageBox.Show("Please enter a number")
Return
Else
MessageBox.Show("Welcome to the program")
End If
The len() function will return the length of the data stored in a variable/control. If the length is 0
this means nothing has been entered. Return can be used in a program as it will prevent any
further code being executed. It stops the program running.
Something entered
Interface
To perform a range check you can simply use an If and then use And to connect two conditions
together.
Entered out of
range
Below are some examples of Regular Expressions patterns as well as what they mean:
頁
:
The program below will check if an email meets the right format requirements. For the purpose of
this task the requirements are:
^[A-Za-z0-9]+\@[A-Za-z0-9]+\.[A-Za-z0-9]+$
At the top of your code above Public Class you need to import the regular expressions library, to
do this enter the following code:
Imports System.Text.RegularExpressions
Interface
頁
:
Code when btnValidate is clicked
How it works
Invalid
FOR Loops
A for loop is known as a count controlled loop, you should use it when you want to repeat a block
of code for a set number of times.
頁
:
Code without a loop Code using a loop
How the for loop works
a for loop will repeat for a set number of times and it will repeat between two ranges. for
x = 0 to 4 will repeat between the bottom and the top value.
for x = 0 to 4 will repeat 5 times, 0,1,2,3 and 4.
x is just a variable that is a counter and stores the number in the loop, this is useful if you
need to use it in calculations.
Interface
Interface
頁
:
Code when btnCalculate is clicked
Interface
頁
:
Code when btnAdd is clicked
Interface
This program gives the average of 9 based on the values in the scores array. This is because 10 +
12 + 7 + 6 + 10 = 45. This is then divided by the size of the list (5) to give 9.
WHILE Loops
A while loop is known as a condition controlled loop, you should use it when you do not know
how many times the code needs to repeat as you can say repeat while a condition is True .
頁
:
Dim userentry As String = "y"
While userentry <> "n"
userentry = InputBox("Play again? y/n")
End While
MessageBox.Show("Game over")
there is a condition after the word while , it works like an if condition. while the variable
userentry is not equal to n the code inside the loop (that is indented) will repeat
when n is entered by the user, the loop will end and it will continue with the code after the
loop. In this case it will display a message box saying “Game Over”.
File Reading
Sometimes you will need to read data from a file to find information and then depending on what
you find do something with it.
頁
:
The process of reading from a file is always the same. The only thing that changes is what file you
are using and what you are looking for in that file.
CSV Files
When reading data from a file, the easiest file type to use is a CSV file, this stands for comma
separated values.
Consider the file below that contains a list of games for different consoles
This means you can then refer to elements of the list to extract single pieces of information. Imagine
the array you have is called games , the second image above shows how you would reference the
information. If you wanted the name of the game it would be games(1) , if you wanted to the rating
it would be games(3)
頁
:
Worked example - File Reading - Speeding
Cars
Before creating a program to read data from a file you need to understand what data is in the file. In
this example it will use a file called cars.csv , which is shown below:
In this file there are two pieces of data, these are the car registration and the speed. When the data
is split into a list, they can be referred to as element 0 for the registration and element 1 for the
speed.
Step 1 - Creating the Interface Like any Visual Basic program the first thing you must do is create
the interface. In this program the user will select a speed limit from a combo box and then it will
output speeding cars to a list box. The interface could look something like this:
頁
:
Step 2 - Creating a Connection to the file
Imports System.IO
First you must import the input/output library. This code must go at the very top of your code
above Public Class
This code will create a connection to the file cars.csv . It can then be referred to as the variable
name which is filereader . NOTE: You must put the full path of the file, not just the name.
Step 3 - Storing Input from the User In this program we need to find out the speed limit so we
can compare it to the speed that the car is travelling to see if it is speeding, therefore the speed
limit selected from the combo box needs to be stored.
Step 4 - Reading through the file Now each line of the file needs to be checked, you will need to
use a loop to do this.
This will create a loop that will repeat while the end of stream (end of the file) of the filereader
variable has not been reached.
Step 5 - Read a line from the file and split the data up Now we have a loop that will read each
line in the file, we need to read one line at a time, and split the information up. We know it is a csv
file and therefore each piece of data is separated by a comma. When it splits the line from the file it
needs to store it in a list, the list below is called details .
details = filereader.ReadLine.Split(",")
NOTE: Don’t forget to declare the array before you use the details array in the loop
Step 6 - Checking the Data The next stage is to check the data that we have read from the file. In
this case we want to see if the speed is greater than (>) the speed limit. The speed is stored in
element 1 of the details array.
Step 7 - If the condition is met If the condition is met and in this case the car is speeding then you
can type the code you want to run like you would for a normal if statement. In this example we
want to add the information of the speeding cars to the list box
details(0) is the car registration plate and details(1) is the speed travelling from the file.
At the moment when you enter a speed limit where there are no cars speeding, the program looks
like nothing happens:
頁
:
What it should do is display a message something like There are no speeding cars , as shown
below:
頁
:
How to do this
1. Create a boolean variable at the start of the program called found and set it to False . This
is because at the start of the program no matches have been found.
2. When a match has been found (inside the IF statement) add a line of code to change that
variable to True .
3. After the while loop create an if that checks if found=False . If found is still False and it
has been through the loop and read the whole file and it is still False this means that the
information you have been looking for in the file has not been found.
If found=False Then
4. Finally code what you want to happen if there are no matches inside the if .
If found=False Then
MessageBox.Show("There are no speeding cars")
End If
NOTE: You must use a variable to do this rather than adding an Else to the If as otherwise it
could display the message multiple times. This is because everytime it reads a line from the file and
doesn’t find the match it would display the message box, rather than just doing it once.
Interface
Interface
File Writing
Sometimes you will need to write data to a file.
The process of writing to a file is always the same. The only thing that changes is what file you are
writing to and what you write to the file.
Write modes
When you read from a file you would use the cost Dim filereader As New
StreamReader("filename.csv") . When you want to write to a file it is very similar, but instead of
StreamReader it is StreamWriter . Therefore the code to create a connection to write to the file is
Dim filewriter As New StreamWriter("filename.csv") . If you do this it will create a
頁
:
connection to overwrite what is already in the file which you do not always want. Sometimes you
just want to add information to the file, this is known as appending. To append to a file in Visual
Basic you open a connection but add ,True after the file name like so:
NOTE: you can call the variable filewriter whatever you want.
Step 1 - Creating the Interface The interface for this program will need them to be able to enter
the gift name, the cost and their priority, it would look like this:
Before you can write to the file you need to store the information entered by the user that you want
to add to the file.
This code will create a connection to the file filename.csv in append mode, the ,True after the
file name is what puts the write connection in append mode. It can then be referred to as the
variable name which is filewriter
頁
:
Step 3 - Write the Information to the File As you are writing to a csv file you need to separate
each piece of data that you want to add with a comma.
NOTE: the any variables that are not a string data type need to be converted by using .ToString .
Step 4 - Closing the Connection Once you have written to the file you need to close the
connection to the file. This means it can be used by other parts of the program if needed.
filewriter.close()
At the moment the program above will always write the information entered to a file. Consider this
new requirement:
Santa is running out of money, it should only write to the file gifts that cost
less than £150, otherwise say they cost too much
How to do this
1. After the information has been entered create an if that checks if the cost is less than
150.
1. if the cost is less than £150, then the lines of code that write to a file should be run.
1. if the cost is not less than £150, add an else and add code to say that the gift is too
expensive.
Else
MessageBox.Show("That gift is too expensive, Santa doesn't have enough mo
ney")
This program asks the user to enter their names, email address and the number of years they have
been teaching. It then looks in the file to see if the email address already exists. If it doesn’t it will
write the information entered to a file, if it does it will say that person already exists.
Interface
頁
:
Code when btnAdd is clicked
lstStudents.Items.Clear()
lstStudents.Columns.Add("Name", 150, HorizontalAlignment.Center)
lstStudents.Columns.Add("Class", 75, HorizontalAlignment.Center)
lstStudents.Columns.Add("Average", 75, HorizontalAlignment.Center)
File Updating
Unfortunately, when you want to update information in a file when programming you cannot simply
find the information and say what you want to change, you have to recreate the whole file changing
the single piece of information you want to update, these are the steps you must go through:
1. Read through each line of the original file that contains the information you want to update.
2. If the line of the file has the information you want to update, then you can change the
information, you then write this information to an updated file
3. If the line of the file doesn’t have the information you want to update, then you write this
information (unchanged) to the updated file
4. Once the entire original file has been checked, the updated file should have the same
number of lines in, but with the updated information. Then you must delete the original file
and rename the updated file to the name of the original file.
NOTE: There are no new programming skills here, however you will need to combine the skills for
reading and writing to a file together and program it in a logical order.
Read a line from the file and compare the email address
If it is a match ask the user to enter the new information and then write the new information
to the update file.
If it isn’t a match write the information that has been read into the list to the update file
unchanged.
After every line in the whole file has been checked, delete the original file, rename the
updated file to the name of the original file.
Interface
So far this program will ask the user to enter an email address. It will then open the staff file and
check each line in the file for that email address. If it finds it then it will ask the user to enter the new
information, but not do anything with it.
After the loop has finished it will check to see if the found variable is True and if it is say details
updated and if not say the staff member cannot be found.
The code once it updates the file, this happens when btnUpdate is clicked:
頁
:
Dim firstname As String = txtFirstName.Text
Dim surname As String = txtSurname.Text
Dim email As String = txtEmail.Text
Dim years As Integer = txtYears.Text
Dim filereader As New StreamReader("D:\staff.csv")
Dim details As Array
Dim found As Boolean = False
While filereader.EndOfStream = False
details = filereader.ReadLine.Split(",")
Dim filewriter As New StreamWriter("D:\staffupdated.csv", True) 'new line
1
If details(2) = email Then
found = True
filewriter.WriteLine(firstname & "," & surname & "," & email & "," &
years.ToString) 'new line 2
Else 'new line 3
filewriter.WriteLine(details(0) + "," + details(1) + "," + details(2)
+ "," + details(3)) 'new line 4
End If
filewriter.Close() 'new line 5
End While
filereader.Close() 'new line 6
My.Computer.FileSystem.DeleteFile("D:\staff.csv") 'new line 7
My.Computer.FileSystem.RenameFile("D:\staffupdated.csv", "staff.csv") 'new li
ne 8
If found = True Then
MessageBox.Show("Details Updated")
Else
MessageBox.Show("That staff member's email cannot be found in the file, n
o changes made")
End If
New Line 1 - opens a connection to a new temporary file called staffupdated.csv in append
mode. This will be the new file with the updated information in.
New Line 2 - if the email address is found, it will write to the file all the new updated
information from the form.
New Line 3 - an else is added so that if a line of the file has been read and it isn’t a match
it must write the information unchanged to the temporary file.
New Line 4 - it will write the information that has been read into the list to the temporary file
unchanged.
New Line 5 - closes the connection to the file you are writing to. This should be done after
the if but inside the while loop.
New Line 6 - closes the connection to the file you are reading from. This should be done
after the while loop.
New Line 7 - this will remove the original file, in this case staff.csv
New Line 8 - this will rename the temporary file staffupdated.csv to staff.csv which
頁
:
will mean the updated information now appears in the original file.
When the program is run and the staff member exists in the file:
When the program is run and the staff member doesn’t exist in the file:
頁
:
Example Program 1 - Updating a File - Zoo
Animals
This program looks through a file that contains a list of animals and how many of them there are in
the zoo. When run it should ask the user the animal that they are looking for and if it finds it then
ask for the new number of that animals at the zoo and update the file.
Arrays/ArrayLists
What is an Array or ArrayList?
An array is a variable that can store multiple pieces of data under a single name. An array list can
do exactly the same, so what is the difference?
Array – an array is a set size that cannot change when the program is running.
ArrayList – an ArrayList is dynamic and the size of it can change when the programming is
running as there are different operations that can be performed.
This example creates an array called sentence that has 5 elements to it.
If you wanted to display the word grey in a message box you would type:
MessageBox.Show(sentence(2))
NOTE: although grey is the third element in the list it is retrieved by saying sentence(2) , this is
because the elements start at 0.
If you wanted to output the entire contents of the array, you could use a list box and use the
following code:
Interface
Interface
Removing
Functions
What are Procedures / Functions?
When producing large programs you can end up with a lot of code. Procedures and functions
allow for programs to be broken up into smaller pieces.
This makes them easier to read and easier to follow. It also means that if you work in a team,
people can create different procedures/functions and combine them together.
Procedures/Functions can take values from the main program and do something with them
e.g. add numbers together etc.
Function functionname(parameters)
CODE INSIDE THE FUNCTION
End Function
Calling
functionname(parameters)
Function - this lets Visual Basic know you are defining a function
calculate - this is the name of the function
(ByVal price As Integer) - this is a parameter. This is what is passed from the main program
into the function. You refer to the value passed into the function by price. As you are passing
in a value you must add ByVal before the name of the parameter and then just like you
would when defining a variable say what data type it is, in this case As Integer
頁
:
Once the function is defined you can write whatever code you want to execute inside of it. In this
case we need to work out the VAT, this is 20% of the price.
The final step is to return the VAT value back to the main program, therefore you need to add the
code:
return vat
In this program the user enters the price, therefore this will need to be stored:
Now you have the input stored from the user you need to display the VAT. To do this you will need
to use the a message box like you normally would but inside of it call the function you created
earlier. Add the following code:
The first part of the message box command works like it always would, but then it called the
function calculate and passes the amount that was entered into the function. Once the amount is
in the function it is referred to as price. This is known as a local variable that can only be used
within that function.
Interface
Interface