Upload
vohanh
View
233
Download
4
Embed Size (px)
Citation preview
Highdown School
Visual Basic .Net Programming for Beginners | Mr Stephenson
HIGHDOWN
SCHOOL
A GCSE GUIDE TO VB.NET
PROGRAMMING
Highdown School
A GCSE GUIDE TO VB.NET PROGRAMMING
2
This guides assumes you know nothing about programming, have fun and remember that
the only way to become an effective coder is practice.
Contents (all of the descriptions are hyperlinks)
Chapter 1: Finding your way around ..................................................................................... 4
Setting up a project............................................................................................................ 4
Your first program – Hello World ........................................................................................ 8
Chapter 1 Exercises: ....................................................................................................... 10
Chapter 2: Forms controls ................................................................................................... 11
The Text Box ................................................................................................................... 11
The List Box .................................................................................................................... 12
Task 1 – Creating the List Box ..................................................................................... 13
Combo Boxes .................................................................................................................. 14
Radio buttons .................................................................................................................. 14
Check Boxes ................................................................................................................... 14
Group Boxes ................................................................................................................... 15
Task 2 – Experiment with the controls .......................................................................... 15
Timer Controls ................................................................................................................. 16
Task 3 – Using the timer .............................................................................................. 16
Scroll Bars ....................................................................................................................... 17
Task 4 – Using the scroll bars ...................................................................................... 17
Chapter 3: Variables ........................................................................................................... 18
Data Types ...................................................................................................................... 19
Declaring Variables (Dim <Identifier> As <Data type>) .................................................... 19
Data Conversions ............................................................................................................ 20
Task 1 – Adding Two numbers ..................................................................................... 21
Static, Global and Local Variables ................................................................................... 22
Task 2: Using Static variables ...................................................................................... 23
Task 3: Using Global and local Variables ..................................................................... 23
Chapter 3 Exercises ........................................................................................................ 24
Chapter 4: Selection ........................................................................................................... 25
The IF statement ............................................................................................................. 26
Task 1: Using the IF Satement ..................................................................................... 27
A flowchart for the If statement ........................................................................................ 28
A GCSE GUIDE TO VB.NET PROGRAMMING Highdown
School
3
The Case Statement ........................................................................................................ 29
Task 2: Using the Case Statement ............................................................................... 30
Chapter 4: Selection Exercises ........................................................................................ 31
Chapter 5 – Loops and Iteration .......................................................................................... 33
Why use loops? ............................................................................................................... 33
Task 1 .......................................................................................................................... 33
The For Loop ................................................................................................................... 34
Task 2: Times Tables with a FOR loop ........................................................................ 34
The While Loop ............................................................................................................... 36
Task 3: Using the while loop ........................................................................................ 36
The Do - Until Loop ......................................................................................................... 37
Task 4: Using the Do Loop ........................................................................................... 37
Chapter 5 Loops Exercises .......................................................................................... 39
Chapter 5: The Dice Game .............................................................................................. 40
Chapter 6: Arrays ................................................................................................................ 41
Static and Dynamic Arrays .............................................................................................. 42
Processing in an Array .................................................................................................... 43
Task 1: An Array to hold numbers ................................................................................ 44
Epilogue .............................................................................................................................. 46
Highdown School
A GCSE GUIDE TO VB.NET PROGRAMMING
4
Chapter 1: Finding your way around
Microsoft Visual Basic Professional 2010 is an Integrated Development Environment (IDE), it
combines all the features you need to create, test and export your code in one handy
package. You will learn how to program very quickly using visual basic but before you start
it‟s a good idea to explore the environment and learn how to save your work properly.
Setting up a project
The code for the programs you write in VB.NET are stored as projects, to make sure your
work is not lost you must make sure it is saved in the right area, with this in mind your first
task is to create a folder called COMPUTING, then inside the computing folder make one
called PROGRAMMING. This will help you find your work later and ensure that the whole
project is saved correctly.
If you have done this correctly the directory path to your programming folder will be:
Z:\Computing\Programming
The following screens will show you how to set up your first project, features will be
discussed as you need them:
1. First select FileNew Project
A GCSE GUIDE TO VB.NET PROGRAMMING Highdown
School
5
2. The next screen shows many of the options available inside the IDE, in this book we
will only make use of the console applications (programs without forms) and the
Windows Form Application, open the Windows Forms Application now.
Note: In VB.NET 2008 you should also enter the directory the project should
be saved in, which should be Z:\Computing\Programming
At this point a screen will appear looking something like this, the arrows highlight the
main areas you will be using.
Always Name Your Project
Form
Properties
Toolbox
Run Program (F5)
Highdown School
A GCSE GUIDE TO VB.NET PROGRAMMING
6
3. Now before you go any further you should save your project, this ensures it will be in
the right folder, either press CTRL+S or FileSave
4. If the toolbox is not showing on the screen then press CTRL+ALT+X
To use objects in the toolbox we
simply drag them onto the form, try
doing this now.
We will use the following tools often,
so make sure you can find them:
Button
Textbox
Label
Check box
Horizontal Scroll Bar
Hint: One of these tools is not found
under common controls.
A GCSE GUIDE TO VB.NET PROGRAMMING Highdown
School
7
5. The last thing you need to see before starting your first program is the properties
panel, this displays all of the options that you can change on the form object you
have selected. Drag a Text Box onto your form now, the properties box should look
something like this:
This is slightly larger than the
one you will see, the most
important fields here are:
Text
Name
The name of this Text Box is
TextBox1 (this can be changed)
It is possible to change and
access every single one of
these fields by using the dot
operator.
So to change the text displayed
inside the program we might
enter:
TextBox1.Text = “Hello
World”
Before moving on see what
some of the options do.
Highdown School
A GCSE GUIDE TO VB.NET PROGRAMMING
8
Your first program – Hello World
It is something of a tradition among programming books that the first program you should
learn is one that displays the text “Hello World”, this was the first official message ever sent
over the internet ( though the computer melted after the letter H arrived).
To build our own version of this program first build a form that looks like this:
Then use the properties window to change the following settings:
Object Text Name
Form Hello World HelloWorld
Label 1 Press The Button InstructionLabel
TextBox1 OutputTextBox
Button1 Update Text Box
The form will now look like this:
An informal algorithm for our program would
be:
Assign the string “Hello World” to Message
When Button1 is pressed display message in
OutputTextBox.
(these will become far more complex soon)
A GCSE GUIDE TO VB.NET PROGRAMMING Highdown
School
9
Okay you are now ready to see the real code, double click the button:
before too long you will understand everything in the box above, for now it is enough to
know:
Public Class HelloWorld – This is the same name as our Form, the class contains will
contain the functions we develop for objects such as Button1.
The Private Sub Button1_Click(…) contains the code that will be executed when the
button is clicked.
The End Sub marks the end of the section of code that will be executed when the
button is clicked, at the moment the private sub_button1_Click() function is empty,
let‟s fix that.
Enter the following code between the private and End Sub class then press F5 to run the
program:
When you run the program and press the button it should look like this:
You have now completed your first program!
Dim message As String
message = “Hello World!”
OutputTextBox.Text = message
Strings can store numbers, letters
and symbols as text.
Integers are used to store numbers.
Highdown School
A GCSE GUIDE TO VB.NET PROGRAMMING
10
Chapter 1 Exercises:
You have actually learned a lot in the last few pages, to show this I would like you to
complete the following challenges. Remember to give sensible names to the objects on your
forms as this is good practice for when things get difficult.
Task Aims Rating for chapter
1 When you press the Update Button it should change the appearance of the text in the InstructionLabel as follows: Text = Button Now Pressed Backcolour = aqua ForeColour = firebrick
Very Easy *
2 Place a label on the form and set its visible property to false. Now create to buttons named On and Off… I think you know what to do now.
Easy**
3 Take whatever value the user enters into the textbox then display it in the Label whenever the button is pressed.
Easy **
4 Change the background colour of the form when the button is pressed
Easy **
5 Add a second textbox, now create a program that will swap the contents of the two textboxes when the button is pressed.
Medium ***
6 Modify the program so that it will add together numbers entered into the textboxes and output the results in a third. Does your program work as you expect?
Hard ****
A GCSE GUIDE TO VB.NET PROGRAMMING Highdown
School
11
Chapter 2: Forms controls
There are many form controls available, it is useful to learn what they can do early on so you
do not waste time trying to code them for yourself (unless you want to).
The Text Box
These are used for entering and displaying data (as opposed to the labels which are just for
displaying data), useful commands include:
Commands Descriptions
TextBox.Focus( ) Positions the cursor inside the textbox
TextBox.Text = “” Sets the textbox to blank
Label.Text = Textbox.Text Assigns the value held in Textbox.Text to be displayed in the Label Text
Have a quick go with the above commands before you move onto the next control.
Highdown School
A GCSE GUIDE TO VB.NET PROGRAMMING
12
The List Box
Use a List Box when you want to select one or more items from a list of items, for example
this could be used on a form to record the different types of games console people own or
countries they have visited.
Properties Descriptions
Items Contains all the items in the list box, the first of which is always given the index 0, the second 1, the third 2….
Items.Count Returns the number of items in the list
SelectedIndex Contains the number of the index currently selected, if no item is currently selected then it returns an index of -1
Sorted Specifies whether or not the items in the list are sorted
Text Contains the currently selected item in the list box
Methods
Items.Add Adds an item to the listbox, e.g: lstConsoles.Items.Add(“Nintendo”)
Items.Clear Removes All items from the listbox, e.g: lstConsoles.Items.Clear
Items.RemoveAt Removes a single item from the list at a given index e.g: lstConsoles.RemoveAt(lstConsoles.SelectedIndex)
The first programming task for this section is to make a listBox for games consoles (or
countries, cakes, bands or whatever you feel like putting in there):
A GCSE GUIDE TO VB.NET PROGRAMMING Highdown
School
13
Task 1 – Creating the List Box
First drag the controls from the toolbox onto the page, the only new one here is the lstBox:
Now set the controls as follows:
Control Properties Property Settings
Text Box Name Text
txtConsole “” (Blank)
Button Name Text
btnAdd Add
Button Name Text
btnDelete Delete
Button Name Text
btnClear Clear
List Box Name Sorted Items
lstConsoles True Gamecube Jaguar Virtual Boy
Insert the following code into btnAdd , then run your program:
lstConsoles.Items.Add(txtConsole.Text) „adds the contents of the textbox to the list
txtConsole.Text = “” „clears the text box
txtConsole.Focus() „puts the cursor in the textbox ready
Now try to work out the code for the Clear and Delete buttons on your own.
List Box
Highdown School
A GCSE GUIDE TO VB.NET PROGRAMMING
14
Combo Boxes
Combination (Combo) or drop-down boxes are a
combination of a list and a text box. You use one of
these every time you select a new font in word.
The main advantage of a combo box is that the items
remain hidden until you click it. They also allow you to
enter your own choices, such as when choosing the size
of the font.
Radio buttons
These are used when you want to restrict your user to
selecting only one of two or more options.
Its most useful property is Checked, this is set to True if
the box is selected or False if not selected (Selection
will be covered in a later chapter).
The only events you are likely to use are:
Click: Which occurs when you click on radio button
CheckedChange: Occurs when you check or uncheck a
button
Check Boxes
These are similar to radio buttons and share the same
events and properties… but allow you to select more
than one option.
A GCSE GUIDE TO VB.NET PROGRAMMING Highdown
School
15
Group Boxes
These are used to group together several controls, there
are two common uses:
1. To allow more than one set of radio buttons on the
page
2. To show or hide the entire group at runtime.
Task 2 – Experiment with the controls
First build the following form, note there are two groups for the radio boxes:
Note the Label has the following settings:
Text: <Blank>
BorderStyle: Fixed3D
AutoSize: False
Name: lblOutput
Now double click the Part Time button, enter the following inside the check_changed
procedure:
lblOutput.Text = “You selected Part Time”
Now: Run the program and demonstrate the Part-Time option is working.
Add similar feedback to the other options.
Highdown School
A GCSE GUIDE TO VB.NET PROGRAMMING
16
Timer Controls
The timer has only one event called the Tick Event, it will carry this out at the interval set by
the user. Its two properties are:
Enabled This is set to either True or False, tick event actions will not take place when
this is set to false.
Interval This is measured in milliseconds. (1 second = 1000 milliseconds).
The Timer can be found in the All Windows Forms toolbox, the following example will show
you how to create a program that will display the current time.
Task 3 – Using the timer
1. First create the form shown below:
2. Now double click the tmrTime and enter the following code into the tick event:
3. Run the program, it should update the time every second.
Extension: Try to make a reaction game that measures how long it takes a user to click a
series of buttons following prompts from a label
The label on the right has the
following settings:
Text: <Blank>
BorderStyle: Fixed3D
AutoSize: False
Name: lblTime
Note that the timer appears below
the form, its settings should be:
Name: tmrTime
Enabled: True
Interval 1000
A GCSE GUIDE TO VB.NET PROGRAMMING Highdown
School
17
Scroll Bars
The horizontal and vertical scrollbars can be found in the „All windows components‟ section
of the toolbox. A scrollbar works by either increasing or decreasing a value depending on
where you drag the slider.
There are three properties you will use often:
Maximum: The highest value that is reached when the slider is at the far right of a
horizontal bar or the very top of a vertical one.
Minimum: The lowest value that is reached when the slider is at the far left of a
horizontal bar or the very bottom of a vertical one.
Value: The current value of the bar
It‟s most useful event is:
Scroll This event is carried out whenever the user moves the slider on the
scroll box.
Task 4 – Using the scroll bars
In Visual Basic colours are made from a mix of the three primary colours Red, Green and
Blue. Each of these colours holds a value between 0 (none) and 255 (max).
Bonus: How many bits are used to represent value held by each of the three colours?
The aim of this program is to use scrollbars to change the background colour of the form
they are placed on.
1. open a new project and set the Text property of the Form to: Scrollbar Colour
Change
2. Place three scrollbars on the form and name them sbRed, sbGreen and sbBlue
3. Set the minimum and maximum property for each bar (see above for values)
4. Double click the sbRed bar and enter the following code
5. Now run the program and test it, then look at ColorTranslator and From Ole in the
help files.
Highdown School
A GCSE GUIDE TO VB.NET PROGRAMMING
18
Chapter 3: Variables
A simple definition of a Variable is that they are containers used by a program to store data,
so it can be used again at a later date. A more accurate definition is that a variable is a
name chosen by a programmer to identify the address in RAM where a particular
piece of data is stored.
So far we have focused on changing the properties of objects we have placed on the form,
such as changing the text values of labels and text boxes. When we want to store a value
currently held in the text box even after the user has typed something else then a variable is
needed.
An example is shown below:
If we wanted the value held in the textbox (txtImputValue) to be displayed in a label
(lblOutputValue) we would use the following code:
lblOutputValue.Text = txtInputValue.Text
If we just wanted to record the value held in the textbox for later use then we would use:
Dim InputValue as String „InputValue has been declared as a variable of the string data type
InputValue = txtInputValue.Text
When declaring a variable visual basic requires two things:
Its name or Identifier (In the above example this is InputValue)
Its data type (In the above example this is String)
String is one example of a Data Type that is used to deal with one or more characters (for
example a sentence). There are many other data types such as Integer (whole number),
Date and Boolean (True or False).
It is good programming practice to always declare variables before you use them.
Try to memorise the 10 data-types shown on the next page, take note of how many bytes it
takes to store each one… why do you think we might use Single instead of Decimal?
(Hint: you may need to look at the help files in VB.Net to get the full answer)
A GCSE GUIDE TO VB.NET PROGRAMMING Highdown
School
19
Data Types
Data Type Used for storing Possible Values Bytes
Short Whole numbers -32768 through +32767 2
Integer Whole Numbers -2,147,483,648 through 2,147,483,67
4
Long Whole Numbers Very long numbers. -9,223,372,036,854,775,808 through 9,223,372,036,854,775,807
8
Single Numbers with decimal places
Very small to very large -3.402823e38 to positive 3.402823e38 The e represents how many places the decimal point should be moved to the left, or (1038)
4
Double Numbers with decimal places
You will rarely need double outside of specialised scientific applications 1.79769313486231570E+308 through 4.94065645841246544E-324
8
Decimal Numbers with decimal places, especially currency values
A very large range 16 bytes (rather large)
Char A single character Any Unicode character in the range 0 to 65,535
2
String One or more characters Any Unicode characters 2 per character
Date Date and Time Dates from 1 Jan 100 to 31 Dec 9999 Time from 00:00:00 to 23:59:59
8
Boolean True or False Values True, False 2
Declaring Variables (Dim <Identifier> As <Data type>)
When declaring a variable you always use the keywords Dim and As, for example:
Dim number As Integer
Dim Date_Of_Payment As Date
Dim Input_One, Input_Two, Input_Three As Integer
Your identifiers should always be meaningful and cannot have spaces, you can however use
underscores to link words. As the third example shows it is possible to declare more than
one variable of the same type at the same time by separating the identifiers as commas.
Highdown School
A GCSE GUIDE TO VB.NET PROGRAMMING
20
Data Conversions
Sometimes you will need to convert data from one Data Type to another, a very common
problem is converting data entered as a string into a number for processing by the program.
For example:
Dim age as Integer
age = Cint(txtAge.Text) „the Cint converts the Text value into an integer
I‟m sure you can guess what the following functions would do:
CBool, CChar, CDate, CDec, CDbl
It goes without saying that there is one for every Data Type, and they will appear in help
drop down inside VB.Net if you type the character C as shown below:
Try this in VB.Net now.
A GCSE GUIDE TO VB.NET PROGRAMMING Highdown
School
21
Task 1 – Adding Two numbers
So far you have made a basic calculator which used two text boxes to get input values from
the user, on completion of this task you should have an some ideas as to how this can be
accomplished with a single box… not unlike a real calculator.
1. Create a new project called Chapter_3_Task_1_Calculator
2. Place two labels on the form as shown below, the text value of the right one should be
left blank. Both labels should use the Fixed 3D border style. Change the name of the
right hand label to lblTotal.
3. Now open up the code view for the form and declare variables of type short for the First
and Second numbers to be input and for the Total. These should be declared as shown
below:
4. We now add some code to the Form1_Load function, which is carried out when the form
is called by the program. The code shown causes an Input box to appear, if you are not
sure what this is then all will become clear when you run the code:
5. Now try running the program.
6. What happens if you try to add up numbers greater than 32768? How can you solve this
problem?
Highdown School
A GCSE GUIDE TO VB.NET PROGRAMMING
22
Static, Global and Local Variables
Global and Local are collectively known as the Scope of the variable, the scope defines
which parts of the program can use the variables.
Global Variables
The variables declared in Chapter 3 task 1 were global variables; these can be
accessed by any procedure/function on the form. The data held by global variables is
lost when the form is closed.
If the program had more than one form then they could also reference the global
variables shown below.
Local Variables (narrow scope)
Variables declared inside a function (such as Form1_Load) are called local variables
and can only be used inside the function they are declared. The data stored in local
variables is lost when the procedure has finished/closed.
It is good programming practice to declare variables with as narrow a scope
as possible!
While it is possible to give global and local variables inside the same
program the same Identity this is very bad programming practice and often
leads to some interesting errors.
Static Variables
Sometimes you need a store the data held inside local variable until the next time the
function is called, to do this you need to declare the variable as static. An example of
this is shown in Task 2 on the following page.
Constant Variable
Constant variables are used when:
A variable does not change
The user does not provide the value
You want to ensure the value cannot be changed
For example if completing a game in under an hour doubled your score you might
use:
Const TimeBonus As Integer = 2
(Or you could use it for VAT and rates of taxation)
A GCSE GUIDE TO VB.NET PROGRAMMING Highdown
School
23
Task 2: Using Static variables
Sometimes you need a store the data held inside local variable until the next time the
function is called. to do this you need to declare the variable as static.
Create a form with a listbox and a button, then add the following code to the
button.
Dim Count as Integer
Count += 1
ListBox1.Items.Add(“Number of Clicks = “ & Count)
Run the program, then see what happens when you change the first line to:
Static Count as Integer.
Task 3: Using Global and local Variables
Design the form and type in the code as shown below:
Trace (read) through the code before you run the program:
1. What value will be held in the text properties of lblGlobal and lblLocal at the end of
the program
2. What problems do you think this could cause?
lblGlobal
lblLocal
btnLocal
Highdown School
A GCSE GUIDE TO VB.NET PROGRAMMING
24
Chapter 3 Exercises
Before we get to the programming tasks I would like you to carry out a little investigation
work, the following topics are not covered in this guide but will be used in later chapters.
1. What do the Byte and Object data types do?
2. When you declare a global variable you can replace dim with words public or
private, what effect does this have?
3. If you haven‟t done so already find out how many functions VB.Net offers to convert
from one data type to another.
Chapter 3 Programming exercises
Task Aims Rating for chapter 1 Modify the program from chapter 3 task 1 to accept
3 numbers.
Very Easy *
2 Modify the program from chapter 3 task 1 to output the total using a Message box (MsgBox)
Easy**
3 There is a way to obtain the results from chapter 3 task 2 without using static, change the code to reflect this.
Easy **
4 A motorist wants to work out how many miles per gallon their car is doing. The program should accept the following input from the user: 1. The cars mileage when the tank was last filled 2. The number of gallons put in the tank 3. The cars mileage when the tank is empty Place the algorithm for your code inside comments.
Medium ***
5 Develop a calculator program that adds numbers using a single text box for data entry.
Hard ****
(Task 4 would be a GCSE level question, Task 5 an Assessment level task).
A GCSE GUIDE TO VB.NET PROGRAMMING Highdown
School
25
Chapter 4: Selection
In this section you will learn about the IF and Case statements, these are used to determine
if a piece of code will be executed (or not) depending on whether a given condition is True or
False.
Highdown School
A GCSE GUIDE TO VB.NET PROGRAMMING
26
The IF statement
There are three variations on the IF statement, these are:
How the IF statement is used in VB.NET
Example Algorithm Comments
If (Condition is True) Then carry out task 1 End If
If (Age < 18) Then Output “you cannot buy beer” End If
Task one is only carried out if the user is under 18.
If (Condition is True) Then carry out task 1 Else carry out task 2 End If
If (Age < 18) Then Output “you cannot buy beer” Else Output “You can legally buy beer” End If
If the user is under 18 then task 1 is carried out, otherwise task 2 will be carried out.
If (Condition is True) Then carry out task 1 ElseIf (Condition is True) carry out task 2 Else (Condition is True) carry out task 3 End If
If (Age > 17) Then Output “You are old enough to drive” Else If (Age = 16) Then Output “You need to be 17 to drive” Else Output “You are too young to drive” End If
You can have use as many ElseIf as you want in your statements. However when there are more than 2-3 it‟s a Case statement is often more appropriate,
Basic Conditions are evaluated using the following terms.
Conditions Example Will return True if… = Age = 18 Age is equal to 18
< Age < 18 Age is less than 18 Note: 18 will return false
> Age > 18 Age is greater than 18 Note: 18 will return false
>= Age >= 18 Age is greater than or equal 18.
<= Age <=18 Age is less than or equal to 18
<> Age <>18 Age is Not equal to 18
It is also possible to have more multiple conditions, the rules here are the same as for
Boolean logic.
Conditions Example AND If (Age < 18) AND (School = Highdown) then…
If (Gender = M) AND (Age <=18) AND (Name = Owen) then…
OR If (Gender = M) OR (Gender = F) then Output “It is not an amoeba” End If
A GCSE GUIDE TO VB.NET PROGRAMMING Highdown
School
27
Task 1: Using the IF Satement
1. Create a form and add the following objects:
A label with the text field set to: Enter your age
A label named lblOutput with the text field emptied
A textBox named txtInput with a fixed 3D border and the text field left blank.
A button named btnCheckAge with the text field set to: Check Age
2. Now double click on the button and add the code for the following algorithm:
Assign the value held in the text field txtInput to the variable Age
If Age is greater than or equal to 18 then
Display “You can buy a cinema ticket for Saw”
End If
3. Run and test your code
4. Expand your code to output the message “you are too young to buy a ticket for Saw” if the
user is under 18.
5. Run and test your code
6. Expand your code to suggest a different film for those between the ages of 15 and 18,
and for those under the age of 15.
7. Run and test your code
8. Expand your code to suggest a different film depending on if the user is male or female.
9. Run and test your code
Expansion Tasks
10. Create a new version of the program using 3 check boxes (for age) and 2 radio buttons
(for Gender)
11. Make the application look as professional as possible (titles, labels, named forms, group
boxes etc)
12. Run and test your code
Highdown School
A GCSE GUIDE TO VB.NET PROGRAMMING
28
A flowchart for the If statement
You will need to be able to draw flowcharts in your exam, here‟s are some examples:
Example of a Flow Chart for using a Nested IF statement
The algorithm below shows a nested if statement, notice how the indents make it easier to read. Function broken_lamp( ) If (Lamp is plugged in) then If (Bulb burned out) then Replace bulb Else Buy new lamp End If Else Plug in Lamp End If
A GCSE GUIDE TO VB.NET PROGRAMMING Highdown
School
29
The Case Statement
If you have more than 4 options to choose from then a Case Statement is often the best
option, for example if you wanted to output the name of the month corresponding to an
integer between 1 and 12 input by the user the code would look like this:
Algorithm Code Output message “Enter a number (1 to 12): ” Get input from user If input is equal to 1 then output January Else if input equal to 2 then output February Else if input equal to 3 then output March Else if input equal to 4 then output April … Else if input equal to 11 then output November Else if input equal to 12 then output December Else Output you did not enter a valid number EndIf
Dim Month As Integer Choice = CInt(txtInputBox.Text) Select Case Month Case 1 MsgBox(“January”) Case 2 MsgBox(“February”) … Case 12 MsgBox(“December”) Case Else MsgBox(“Please enter a valid Number”) End Select
It is of course possible to enter more than one line of code for each case statement, for
example:
Select Case Month
Case 1
MsgBox(“January”)
MsgBox(“4 months till your exam”)
Case 2
MsgBox(“February”)
MsgBox(“3 months till your exam”)
End Select
Some other tricks include:
Using a range of values A Continuous Range (Is) A non-Continuous Range
Select Case Exam_Results Case 0 To 9 MsgBox(“Fail”) Case 10 To 20 MsgBox(“Pass”) End Select
Select Case Exam_Results Case Is < 40 MsgBox(“Fail”) Case Is <= 59 MsgBox(“Pass”) Case Is >= 60 MsgBox(“Merit”) End Select
Select Case Number Case 1, 3, 5, 7, 9 MsgBox(“Odd”) Case 2, 4, 6, 8, 10 MsgBox(“Even”) End Select
Before you move onto the next task experiment with the Case Statement
Highdown School
A GCSE GUIDE TO VB.NET PROGRAMMING
30
Task 2: Using the Case Statement
Goal: Present the user with two list boxes, one of these lists will display the name of the
three schools involved in a programming competition. When a team is selected the members
of that team will be displayed in the other list box.
1. Create a new project called Chapter 4 - Teams and members
2. Keeping in mind that you only you will only need to Add the Teams at this point use the
following table to create your form:
Control Property Setting
Form Text Teams and Members
Label Text Teams
Label Text Members
List Box Name Items
lstTeams Any three team names
List Box Name lstMembers
3. Now double click the Teams list box and enter the following code:
4. Test and run your code, what happens when you select more than one team?
5. Add the following line to the code: lstMembers.Items.Clear (you can figure out where)
Extension
It‟s important to note that in a real project the members would be stored and retrieved from a
file, though the Items.Add method is still used. If you have time try and figure out how you
can do this.
A GCSE GUIDE TO VB.NET PROGRAMMING Highdown
School
31
Chapter 4: Selection Exercises
Two short investigation tasks before you start programming:
1. Use the help files to investigate the Not, AndAlso and OrElse operators in VB.NET
2. Investigate how you might use the Switch statement instead of Case
To be an effective programmer you must learn how to use the help files and online forums to
solve your problems, you should only ask the teacher for advice when these methods have
failed.
In the controlled assessment the teacher will not be able to help… but you should be able to
help yourself by then.
Task Aims Rating for chapter 1 Create a program that uses a Case statement to determine if
a grade is a Fail, Pass(40 to 49), Merit (50 to 59) or Distinction (60-100).
Easy **
2 WorkingGames have released a new game called plunder company and sells a range of lead miniatures to replace the cardboard tokens used in the game. It wants you to create a price calculator for their website and has provided the following information. Factions Users should be able to select the game faction from a list box, these should include Orcs, Elves, Dwarves. Items Once they have selected their faction they need to select the items they wish to buy using a check boxes. They sell the following for each faction War Machines, Heroes and Infantry. There should also be a fourth option called full set Hint: The items checkboxes will need to be grouped Quantity The user should then be able to select 1,2,4 or 8 from a set of grouped radio buttons. Price Button: When pressed this will output the current faction and Quantity
Medium ***
In this task you will create a form with a
list box, a set of grouped check boxes and a set of grouped
radio buttons.
Take it step by step and read the
specification carefully you should be able to
manage this task.
The functionality of the Price button will
change over the next few tasks.
3 You have now developed the prototype of the
Highdown School
A GCSE GUIDE TO VB.NET PROGRAMMING
32
WorkingGames software, in this task you will work on the Items part of the program. Buying a full set of miniatures will give the user a discount that will show when the Price button is pressed, for now you will need to write code for the item specification that meets the following guidelines. Requirements If the Full Set Option is selected then all of the check boxes in Items menu should be checked If the Full Set Option is deselected then all of the options in the Items menu should be unchecked. If War Machines, Heroes and Infantry are all checked then Full set option should be checked. If any of War Machines, Heroes and Infantry are not checked then Full Set should not be checked.
Medium***
Remember the checked property if a
checkbox can only be True or False
4 Add code to the price button that ensures at least one option has been chosen from Faction, Items and Quantity. If this is not the case then an error message should be displayed when the Price Button is pressed. Hint: Write the algorithm down first and make good use of brackets, it will save you time in the long run
Hard ****
This would be a good
place to use a complex statement made of ANDs and
ORs
5 If the user has selected at least one item from Faction, Items and Quantity then it‟s time to work out the price. Item Cost Heros cost £5.00 Infantry cost £10.00 War Machines cost £14.50 Full Set (With Discount applied) = £25 Faction Costs Dwarves = 0.5 Orcs = 1 Elves = 1.5 The formula for the price is Faction cost * (Cost of Items) * Quantity The result can be output to a message box or onto the form using a label or text box (your choice).
Hard ****
Okay hints again,
start off by creating variables for each part of the formula
and figuring out what needs to be stored
there.
Possibly Case for quantity?
6 Make it so selecting a race chooses appropriate colours for the background and text (Orcs e.g. Green and white)
Medium ***
A GCSE GUIDE TO VB.NET PROGRAMMING Highdown
School
33
Chapter 5 – Loops and Iteration
Why use loops?
A loop is a piece of code that may be executed repeatedly; it will contain a Boolean condition
(true or false) to determine when it should terminate (end).
There are three basic loops you will need to understand for the GCSE computing, these are
the For, Do While and Do Until.
Each of the three loops are useful for a different circumstance, as with all coding the best
way to get to grips with loops is to experiment with them.
As to why we use them…. consider the following code
Without Loop With Loop
Dim Count as Integer = 0 Count += 1 ListBox.Items.Add(Count) Count += 1 ListBox.Items.Add(Count) Count += 1 ListBox.Items.Add(Count) Count += 1 ListBox.Items.Add(Count) Count += 1 ListBox.Items.Add(Count)
Dim Count as Integer = 0 Followed by For Count = 1 to 5 Listbox.Items.Add(Count) Next Count Or Do ListBox.Items.Add(Count) Count += 1 Loop Until Count = 5 Or Do While (Count < 5) Count += 1 ListBox.Items.Add(Count) Loop
Obviously the loops are far more efficient, but can you think of when we might use the
different loops?
Task 1
Write a program in VB.Net that uses the loops in the above example.
1. Do any of the loops work unexpectedly?
2. What does this tell you about how the loops works?
Highdown School
A GCSE GUIDE TO VB.NET PROGRAMMING
34
The For Loop
The FOR loop is used when you know exactly how many times the code needs to be
repeated, another common purpose is populating arrays (Chapter 6).
The General form of a For loop is:
For variable_Identifier = start value To end value
statements
Next variable_Identifier
The start and end values can be integer constants, variables or expressions.
A code example
For Count = 1 to 5 „Count is initialised to 1
Listbox.Items.Add(Count) „The statement is executed
Next Count „Add 1 to Count unless Count = 5.
So how does it work?
1. When the first line is executed for the first time the value 1 is stored in the variable
Count.
2. Then the statement in the loop body is executed (outputting the value of Count to the
list box)
3. In final line Next indicates the end of the loop and control is passed back to the first
line, and Count is automatically incremented to 2 and the loop body executes again
(this time outputting the value 2)
4. When the loop has been executed 5 times the control passes to the first statement
after the loop.
Task 2: Times Tables with a FOR loop
You are going to make a program to output the
multiplication table for any number input by the
user, there‟s a screenshot of the finished product
to the right but you need to figure out how to make
it:
A GCSE GUIDE TO VB.NET PROGRAMMING Highdown
School
35
The For Loop Continued (Stepping)
In the previous program the count was incremented by 1 to step through the program, while
this is the most common form of For loop there are a few other a few other methods you
should be aware of:
Code Explanation
For Index = 1 to 10 Step 2 lstOutput.Items.Add(Index) Next Index
This increments index by 2 each time round the loop. So the numbers 1, 3, 5, 7 and 9 will be added to the list. The loop will then terminate as the next value assigned to index is 11, which is larger than the end statement of 10.
For Index = 10 to 1 Step -1 lstOutput.Items.Add(Index) Next Index
It is also possible to give Step a negative value.
For i = 1 To 4 For j = 1 To 3 lstOutput.Items.Add(“I x J” & I * J) Next j Next i
It goes without saying you can also nest loops, the code on the left is a common way of populating arrays (See next chapter) Questions How many times will loop j be executed in this program? What will the final line output be?
Highdown School
A GCSE GUIDE TO VB.NET PROGRAMMING
36
The While Loop
The while loop checks to see if a condition is true before it executes the statements in
the body of the loop, if the condition is not true then the loop will be skipped.
The general form of the While loop is:
Do While condition is true
Statements
Loop
A common use for while loops is in error detection, the algorithm below shows one example:
Prompt user to enter a choice from the menu
Choice A number input by the user
Do While Choice less than 1 or greater than 6)
Output “Im sorry you have not entered a valid option, please try again”
Prompt user to enter a choice from the menu
Choice A number input by the user
Loop
Process Choice
The code in the while loop is only executed if the user makes an invalid choice.
Task 3: Using the while loop
1. Turn the algorithm in the example above into a working VB.NET program
2. Can you think of a problem that might arise by using loops? (Dry run the following code)
Number = 5
Do While Number <> 10
lstOutput.Items.Add(Number)
Number = Number + 2
Loop
A GCSE GUIDE TO VB.NET PROGRAMMING Highdown
School
37
The Do - Until Loop
A Do-Until loop is always executed at least once as the condition is placed at the end of
the loop, this is why the example at the start of the chapter produced 6 results rather than 5.
The general form of the Do-Until loop is:
Do
Statements
Loop Until condition is true
One good example of a Do-Until loop would be a program that requests a password for
entry; this is because the password must be entered at least once.
Consider the following code:
Dim Password, Input_Password As String
Dim Attempt As Integer „records how many attempts have been made
Password = “secret” „assigns Secret to the variable Password
Do
Attempt += 1
Input_Password = InputBox(“Please enter password”)
Loop Until (Input_Password = Password) „This looks like a good place to add an OR
MsgBox (“This password is Valid”)
Once the user reaches the Do Loop in the code they must enter the correct password before
the program will let them continue. The code inside the Do UNTIL loop is always
executed at least once.
Task 4: Using the Do Loop
Create a program based on the above code, once your password program is working you
should make the following improvements:
Limit the user to three attempts at entering the password
Add a message to the input box to say how many attempts the user has made
If the wrong password is entered three times the program should output a message
to tell the user they cannot log in.
Extension (internet research)
Now you are probably wondering how to make it so the password you are typing does not
display in the input box… the simple answer is you cannot, but can you find out a way of
hiding characters entered into a text box?
Highdown School
A GCSE GUIDE TO VB.NET PROGRAMMING
38
A GCSE GUIDE TO VB.NET PROGRAMMING Highdown
School
39
Chapter 5 Loops Exercises
You are very near the end of the guide now and have learned a great deal, it might be worth
going back and trying some of the earlier tasks that might have been too hard the first time
round.
Task Aims Rating for chapter 1 Modify the program from task two in this chapter to
ensure the user only enters values between 2 and 12. You could use an InputBox to request a valid number when stray outside the stated range.
Very Easy *
2 Ask the user for two different numbers Display all the numbers between the two values. So for 11 and 15 output 11,12,13,14,15
Easy**
3 Find out how to use the Mod operator. Develop a program that allows the user to input as many numbers as they wish, then 0 to indicate they have finished. Output how many of the numbers entered were odd and how many were even(you will need the Mod operator for this)
Medium ***
4 A theatre can hold 100 people. Allow the user to keep entering the number of people in each group as they walk through the door. Display a running total and how many people are allowed in before it becomes full. Output messages when:
There are not enough seats for the last group.
Exactly 100 people have been admitted.
Medium ***
5 Use a nested for statement to output the values and suite of each card in a standards deck: Suites (H, S, D, C) Values (A 2 3 4 5 6 7 8 9 10 J Q K) Example Output: AH, 2H, 3H, 4H, etc.
Hard ****
vbTab can be used to format
6 Use a Nested For…Next to output the cell references found in the top upper left part of a spreadsheet, within the range A1 to E5. HINT: You should use the Asc and Chr commands to convert characters to and from ASCII
Very Hard *****
Highdown School
A GCSE GUIDE TO VB.NET PROGRAMMING
40
Chapter 5: The Dice Game
The following code is part of a simple dice game; to win the user has to roll the number
selected by their opponent, the number of rolls is recorded:
„RANDOM ROLLS - This code would be placed inside a button on the form
Dim Opponents_Choice As Integer „The number selected by the user
Dim Roll_Count as Integer „The number of times the dice has been rolled
Dim Current_Roll as Integer „The value of the current roll
Roll_Count = 0
Opponents_Choice = Cint(txtOpppnent_Input_Box.Text)
Do While (Current_Roll <> Opponents_Choice)
Current_Roll = RandomClass(1,6) „Assigns a random integer between 1 and 6
lstOutput.Items.Add(Current_Roll) „Outputs the current roll
Roll_Count += 1
Loop
lstOutput.Items.Add(“It took player 1 “ & Roll_Count & “turns to roll a ” & Current_Roll)
1. Is the Do While loop the best choice? modify the code to use a more appropriate
loop.
2. Modify the code to create a two player game, the winner being the user whose dice is
rolled the least number of times before matching the opponents number.
3. After the winner has been declared add the option to play again.
4. Add an option to let the user choose how many sides the die has.
Extension Tasks
5. There is a Dice game known as Yahtzee, find out the rules and try to recreate the
game in VB (Medium)
6. There is a Dice game known as Craps, find out what the rules are and try to recreate
the game in VB. (Hard)
7. Figure out a way to animate the dice on the screen (Very Hard)
Hint: You will need a graphic for each face on the die.
A GCSE GUIDE TO VB.NET PROGRAMMING Highdown
School
41
Chapter 6: Arrays
This is the final chapter of the book and the last topic you need to understand for your GCSE
in computing. Conceptually arrays can be confusing for some people… if you feel that way
after reading the chapter then please look online for a different definition!
Even once you have finished this chapter it would be a very good idea to find out more about
them, we will only cover the basics here and there will be a lot more to explore:
What is an array?
An array is a data structure that allows you to store as many items as you require using a
single variable.
If you want to declare five integer variables you might use a line of code similar to this:
Dim FirstNumber, SecondNumber, ThirdNumber, FourthNumber, FifthNumber As Integer
This is all well and good, but what if you needed hundreds or even thousands of variables
using the same data type? This is where you would declare an Array:
Dim Numbers(4) As String „The variable Numbers stores all the data in the array
This small piece of code can be used to store 5 integer numbers, the first of which is stored
in slot 0 (just in case you thought it was a typo). The following table shows how this can be
represented.
An example of a one dimensional Array
0 1 2 3 4
42 48 108 24 -8
Numbers(1) Numbers(3)
The individual slots are called subscripts or elements and you can refer to the contents held
in each element by referencing the variable identifier followed by the elements position in
brackets. In the array shown above the value stored at position 1 of the numbers array can
be referenced by Numbers(1).
An Array can be made for any Data Type including Strings, Decimals, Characters, Boolean.
Dim Names(5000) As String
Dim Choices(10) As Boolean
Dim Initials (10) As Character
Highdown School
A GCSE GUIDE TO VB.NET PROGRAMMING
42
Static and Dynamic Arrays
A static array is one whose size is fixed throughout a program
A dynamic array is one whose size can shrink or grow during the program
The examples in the previous section were all static arrays, chances are most of the arrays
you use during this course will be static arrays but it is important to understand how dynamic
arrays can work.
To declare a dynamic array you create leave the brackets empty when you declare the
variable:
Dim Numbers( ) As Integer
Then you use ReDim to declare how large it needs to be when the program is uses it:
ReDim Numbers(29) As Integer
If you ReDim an array that already in use then its contents will be lost unless you use the
keyword Preserve:
ReDim Preserve Numbers(59) As Integer
The Numbers Array can now hold 60 items and any information already entered has been
retained.
A GCSE GUIDE TO VB.NET PROGRAMMING Highdown
School
43
Processing in an Array
In this example I have declared an array to hold 10 names:
Dim Names(9) As String
To store a name in the 8th element (or subscript) of the array you could write:
Name = txtUsersName.Text „Reads the users name from a text box
Names(7) = Name „Remember the array starts at 0
It is more common to use a variable to identify the subscript in an array, this allows you to
reuse the code. In the following example a for loop is used to display the contents of the
array in a list box:
For Index = 0 to Number_of_Names – 1 „Number_of_Names is assumed to store
lstNames.Items.Add(Names(Index)) „the number of names in the array
Next Index
Highdown School
A GCSE GUIDE TO VB.NET PROGRAMMING
44
Task 1: An Array to hold numbers
1. Create the form as shown:
Group Boxes Objects in group box Property Values
Input txtInput Text Border
“ ” Fixed 3D
btnAdd_To_Array Text Add to Array
Output lstDisplay_Array Items Cleared
btnDisplay_Array Text Display Array
Search txtSearch Text Border
“ ” Fixed 3D
btnFind_Number Text Find Number
lblMessage Text Border Auto Size
“ ” Fixed 3D False
2. Declare the following as global variables on the form:
Dim Numbers(4) As Integer
Dim CurrentIndex As Integer
3. In the forms load event procedure initialise the Current Index to -1, the reason for this
will become obvious in the next step:
CurrentIndex = -1
A GCSE GUIDE TO VB.NET PROGRAMMING Highdown
School
45
4. Add the following code to the click event for the Add_To_Array button:
Dim Number as Integer
Number = txtInput.Text
If CurrentIndex = 4 Then
MsgBox(“The Array is Full”)
Else
CurrentIndex += 1 „On the first run sets CurrentIndex to 0
Numbers(CurrentIndex) = Number
txtInput.Text = “” „clears the txt.Input text property
txtInput.Focus „places the cursor in the text field
End If
5. Because the CurrentIndex also stores the number of entries in the array it can also be
used to control a FOR loop to display the arrays contents.
Use the code example from Processing in an Array to write a FOR loop that displays the
contents of the numbers array in lstDisplay_Array.
(Hint: To clear the array lstDisplay_Array.Items.Clear)
6. Run the program and check it is working correctly
7. The search is a little more complex, the method used here is a linear search, it would be
useful to remember this for the exam. Enter the following code and add comments to
explain how it works:
„The following code should be placed in the btnFind_Number Click Event.
Dim Index As Integer
Dim Found As Boolean
Dim SearchNumber as Integer
Index = 0
Found = False
SearchNumber = txtSearchNumber.Text
Do While (Found = False) And (Index <= CurrentIndex)
If Numbers(Index) = SearchNumber Then
Found=True
Else
Index += 1
EndIf
Loop
If Found Then
lblMessage.Text = “This number IS in the array”
Else
lblMessage.Text = “This number is NOT in the array”
End If
8. Now run and test your program
Highdown School
A GCSE GUIDE TO VB.NET PROGRAMMING
46
Epilogue
Congratulations, you have now reached the end of the book.
I hope you are proud of what you have achieved and feel confident in tacking programming
problems on this course.
However I would like you to consider this guide a first step into the world of programming,
while you should now have a strong grasp of the basic data structures form the basis of all
programming languages there is still a lot to learn.
Where next?
On the Highdown Learning Platform you will find a book of programming exercises
that takes you right from the very basics of temperature converters through to building
fairly complex games in VB.Net. To succeed you will need to make use of the help files
and research programming techniques online. (Classroom Task)
Alternatively you could look at the following website which offers free lessons that will
take you up to A-Level Standard:
http://www.homeandlearn.co.uk/net/vbnet.html
You might consider joining a programming forum such as:
http://www.vbdotnetforums.com/
or
http://www.daniweb.com/forums/forum2.html
or
http://www.programmersheaven.com
Or write your own games…
http://www.vbgames.com/ or http://www.vbprogramming.8k.com/tutorials/main.htm
or http://www.alanphipps.com/VisualBasicdotNET-XNA.html
Practise, it‟s the only way to get better.