Program Examples
Program Examples
Program Examples
When creating an interface, there are different types of form controls. Some of those that you will use are: Variables
Back to top
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
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
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)
You can concatenate (join together) controls with strings in a MessageBox.Show() command. In the address example
MessageBox.Show("Street: " & txtnumber.Text & " " & txtStreet.Text & vbNewLine & "Town/City: " + txtTown.Text) will
combine the strings “Street” and “Town/City” with the form controls txtNumber, txtStreet and txtTown.
To add data to a list box you need to use the following code:
To add the name entered and the email address entered to the list box when the button is clicked you need 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
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:
Interface
'three variables that store the text box inputs from the interface as a decimal
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 & " litres of water")
The code above rounds the variable capacity, to round a variable you use the Decimal.Round() function. You write the name of the
variable followed by the number of decimal places e.g. Decimal.Round(capacity,2) . Also note that it has .ToString after it, this is
because any variable that is not a string data type much be converted back to a string before it can be displayed in a message or list
box.
Interface
'three variables that store the two inputs from the interface and the value of pie
Dim radius As Decimal = txtRadius.Text
Dim height As Decimal = txtHeight.Text
Dim pie As Decimal = 3.14159
'calculations to work out the volume and surface area
Dim volume As Decimal = pie * (radius * radius) * height
Dim surfaceArea As Decimal= 2 * (pie * (radius * radius)) + 2 * (pie * radius * height)
#outputs the volume and surface area of the cylinder in a message box.
MessageBox.Show("The volume of your cylinder is: " & Decimal.Round(volume, 2).ToString & " to 2 decimal places" & v
bNewLine & "The surface area of the cylinder is: " & Decimal.Round(surfaceArea, 2).ToString & " to 2 decimal place
s.")
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
the program first checks to see if the colour selected in the combo box on the interface is Red and if it is will display a message
box saying STOP .
if the colour selected isn’t red it will go onto the next condition where the Elseif is and check if the colour is Amber . If it is then it
will display a message box saying GET READY TO STOP
if neither conditions are met it will go to the Else part of the code and display a message box saying GO .
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)
Validating Data
What is Validation?
Validation is the process of checking to see if data that is entered meets a set of requirements, this does mean it will always stop
incorrect data being entered. For example if you had to enter a telephone number, you could validate it and say it needs to be 11 digits
starting with a 0. The user could enter 01234567891, this meets the requirements set, but does not mean it is a valid telephone number.
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.
Nothing entered
Something entered
Interface
To perform a range check you can simply use an If and then use And to connect two conditions together.
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
How it works
Valid
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.
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
Interface
The answer on this example is 15. This is because it will add the first, third and fifth digit to the total (5 + 6 + 9) which gives 20. It then
subtracts digits 2 and 4 (3 + 2) from the total, therefore 20 - 5 to give 15.
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 .
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)
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:
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
Dim day As String = cmbDay.Text 'stores the input from the user
Dim fileReader As New StreamReader("D:\timetable.csv") 'opens the file
Dim lessons As Array 'declares an array to store a line of information from the file
Dim found As Boolean = False 'stores whether the day is found in the file, set to False at the beginning
While fileReader.EndOfStream = False 'loops for the number of lines in the file
lessons = fileReader.ReadLine.Split(",") 'splits the line into the lessons array
If lessons(0) = day Then 'checks if the day entered is in element 0 of the list
'if it is it prints the timetable referring to the different elements of the array
MessageBox.Show(day + vbNewLine + "Period 1 - " + lessons(1) + vbNewLine + "Period 2 - " +
lessons(2) + vbNewLine + "Period 3 - " + lessons(3) + vbNewLine +
"Period 4 - " + lessons(4) + vbNewLine + "Period 5 - " + lessons(5))
'sets found to True as a match is found
found = True
End If
End While
'after the loops checks if found if still False
If found = False Then
'displays a message if it is
MessageBox.Show("Day not found")
End If
Interface
Dim console As String = cmbselectconsole.Text 'stores the console choice from the user
Dim filereader As New StreamReader("D:\games.csv") 'opens the file
Dim details As Array 'declares an array to store a line of information from the file
Dim gamevalue As Integer = 0 'stores the total value of a game
Dim found As Boolean = False 'stores whether the console is found in the file, set to False at the beginning
Dim totalvalue As Integer = 0 'stores the total value of all games
While filereader.EndOfStream = False 'loops for the number of lines in the file
details = filereader.ReadLine().Split(",") 'splits the line into the details list
'variables that store different pieces of information from the list to make them easier to reference
Dim game As String = details(1)
Dim price As Decimal = details(2)
Dim rating As String = details(3)
Dim noinstock As Integer = details(4)
If details(0) = console Then 'checks if the console entered is in element 0 of the array
gamevalue = price * noinstock 'calculates the total stock value of a game
totalvalue = totalcost + gamecost 'calculates a running total of the entire stock value
'adds the game information to the list view box
lstStock.Items.Add(New ListViewItem({game, FormatCurrency(price), rating, noinstock, FormatCurrency(gameval
ue)}))
'sets found to True as a match is found
found = True
End If
End While
'add the totalvalue to the text box on the interface
txtTotalValue.Text = FormatCurrency(totalvalue)
'after the loops checks if found if still False
If found = False Then
'displays a message if it is
MessageBox.Show("Console not found.")
End If
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 money")
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
Interface
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:
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:
Interface
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
Adding
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.
Defining
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