Sie sind auf Seite 1von 31

Visual Basic Notes http://doyle.wcdsb.ca/ICS3MI/Notes/notes.

htm#FormatFunctions

Visual Basic.NET Class Notes


Introduction
Steps to Creating a Program Terminating a Form
System Development Lifecycle Debugging
Visual Basic IDE Math Functions
Controls/Objects String Object Methods
Object Naming Conventions String Object Numeric Functions
Object Properties Format Functions
Object Methods Random Numbers
Object Events Subprograms
Adding Code to a VB Program User-Defined Functions
Outputting data Variable Scope
Internal Documentation Form Load
Data Types Message Box
Variables Input Box
Assigning Values to Variables Showing Multiple Forms
Arithmetic Operators Modal Forms
Constants Arrays
Inputting data Dynamic Arrays
Simple IPO charts Multidimensional Arrays
Selection - IF StopWatch Object
Compound Selection Searching
IPO - Selection Sorting
Counted Repetition - For Menus
IPO - Repetition Timer Objects
Uncounted Repetition - Do Moving Images(Animation)
File Input and Output Reading from an Access Database
Counting and Accumulating ListView Control
ListBox Control

What is Computer Programming?

A program is a set of instructions that guide the computer in carrying out a specific task. To write a program you need to have a programming
language (software) such as: Visual Basic, Turing, Basic, Java, Fortran, Cobol, C++, etc. These are English-like languages that humans can read,
understand and write, however the computer can not understand these languages! In order for the computer to carry out the instructions, the program
must be translated to a language the machine understands, called machine language and then executed. The programs we write in Visual Basic are
first translated by the VB software. When the statements in the original or source program are translated to machine language, called the object
program, the program is said to be compiled and ready for execution

Why Write Programs


All the software we use on the computer are programs written to carry out various applications. Even DOS and Windows is a program (or set of
programs) written as an interface between the user and the hardware. DOS and Windows are operating systems. Without one of them we would need
to know a great deal more to communicate with, and manage the hardware components of the computer system. Windows is a software package that
allows us to work in DOS without needing to understand all the built in commands. It makes the computer friendlier to use because the menus and
icons replace the need to remember all the DOS commands.

There is software referred to as application software such as; word processors (MS Works/Word), spreadsheets (Works,Lotus,Excel), desktop
publishing (Pagemaker, Ventura Publisher) , database programs (Access,dBASE, Paradox,) graphics programs (CorelDRAW, AutoCAD) and
communications software (PCtalk, HyperAccess). These programs are built to to particular types of jobs and allow us to process information easily.

If information needs to be processed in a repetitive manner then programming a computer to carry out the task will make the job quicker and easier.

Steps To Creating a Program:


Software refers to a collection of instructions, called a program ( VB calls them a solution) that directs the hardware (monitor, keyboard, mouse, CPU
etc.)

The first step in writing instructions to carry out a task is to determine what the output should be. The second step is to identify the data, or input,
necessary to obtain the output. The last step is to determine how to process the input to obtain the output. Therefore, the problem solving process used
will always consist of three steps:

1. input
2. processing
3. output

When solving a computer problem, each assignment asks you to first create an IPO chart. IPO stands for input, processing and output. IPO charts are
done before you start to code. IPO charts state the processing in a structured english, sometimes called pseudo-code. For example:

Create an IPO chart for a program that will allow a person to input an amount to be deposited in a bank account, the interest rate and the number of
years the money will be left in the account. Print the amount of money in the account at the end of the time.

Input Processing Output


amount deposited final amount = amount deposited final amount
interest rate repeat for the number of years
number of years final amount = final amount + final amount * interest rate

Notice that the IPO chart 'explains' how to change the input to the output. All the inputs are used in the processing and the outputs are clearly
calculated in the processing. The processing is structured and indented similar to VB programs but the language is more like 'normal' English than a
programming language. Many VB details are not included, such as dim, end if, next, toString, because they are 'understood' to be needed when you
start to code.

System Development Lifecycle


When working in teams of programmers, or on large programming projects, it is important to stay organized. Many efficient programmers plan their
programs using the system development lifecycle or SDLC. The step-by-step process is shown below:

Step Explanation How to..


Analysis Define and understand the problem Be sure you understand what the program should do, that is, what the input and output should be.

1 of 31 7/25/17, 7:37 PM
Visual Basic Notes http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm#FormatFunctions

Find a logical sequence of precise steps that solve the problem.Create the IPO chart, in this class.

Plan the solution to the problem A sequence of steps such as this is called an Algorithm. Three popular methods used to develop logical plans are flowcharts,
Design pseudocode and top-down charts. These tools or methods will assist the programmer in breaking down a large problem into
smaller tasks.
Choose the Interface Determine how the input will be obtained and how the output will be displayed - layout the form(s)
Create the form and translate the algorithm into a programming language. The program is written during this stage. Write
Development Code
comments inside the program that explain to other programmers what the code is doing.
Testing Test and Debug Locate and remove any errors in the program.
Install the working program on the user's computer and train Write documentation that is intended to allow another person to understand the program and train the user how to use the
Implementation
the user program.

This method of organizing a programming project is sometimes called the waterfall method, because the steps proceed from one to the next, like water

falling down from step to step.

There are other project methodologies that exist such as:

rapid application development (RAD)


joint application develop (JAD)
spiral model
synchronize and stabilize
extreme programming (XP)

All these methodologies are used to coordinate teams of programmers working on large projects. Each methodology has its strengths and weaknesses.

Visual Basic Programming Environment (IDE - Integrated Development Environment)

Controls/Objects
In VB, a program is started by drawing the user interface (the part of the program a user will see) on a form (the rectangular area with the grid marks in
the center of the IDE). All the controls you can place on a form are in the toolbox, on the left side of the IDE. Controls you place on a form and the form
itself are called objects.

Examples of objects:

2 of 31 7/25/17, 7:37 PM
Visual Basic Notes http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm#FormatFunctions

form - a windows screen


button
label - user can not change during run time
textBox - user can change during run time
horizontal scroll bar
pictureBox

The Toolbox contains the following standard controls:

Picture Box
Label
TextBox
Button
GroupBox
Check Box
RadioButton
ComboBox
ListBox
Horizontal Scroll Bar
Vertical Scroll Bar
Timer

When placing several objects on a form, use the commands on the Format menu to place, size, and align the objects. First, drag the mouse around the
objects to select them. Using the commands on the Format menu, you can then align or size the objects as necessary. Object properties can generally
be set at either design time or run time

Here is a form with Label, TextBox and Button objects.

Label Control

A label is a graphical control used to display text. The user cannot edit the text in a label. The most common use for a Label control is to identify controls
that do not have a Caption property, such as the TextBox control. You can also use the Label control to display text such as status messages and other
program information.

TextBox Control

You use a TextBox control to obtain information from the user or to display information provided by the application. Unlike information displayed in a
label, the user can change information displayed in a text box.

TextBox objects have a 'ReadOnly' property, that when set to 'true' does not allow the user to type into the textbox.

Button Control:

A Button performs a task when the user clicks the button. You use a Button control to begin, interrupt, or end a process. When clicked, a command
button appears to be pushed in and so is sometimes called a push button. The most common event for a Button control is the Click event.

Object Naming Conventions


All objects you place on a form must be given a name, in this course. An object's name is used to refer to the object in your program code. You can
assign any name to an object, but it is a good idea to adopt a naming convention and use it consistently throughout your programs.

The following table lists the standard naming conventions used in Visual Basic. Adopting these conventions makes it easier for others familiar with the
standard naming conventions to understand your code.

Suggested Prefixes for Controls

Control Type Prefix Example


Check box chk chkReadOnly

Combo box, drop-down list box cbo cboEnglish

Button btn btnExit

Form frm frmEntry

Horizontal scroll bar hsb hsbVolume

Label lbl lblHelpMessage

List box lst lstPolicyCodes

3 of 31 7/25/17, 7:37 PM
Visual Basic Notes http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm#FormatFunctions

Menu mnu mnuFileOpen

Radio button rad radGender

Picture box pic picVGA

Text box txt txtLastName

Timer tmr tmrAlarm

Vertical scroll bar vsb vsbRate

Properties
Properties define the appearance and behavior of objects. Text, Font, and Name are common examples of properties. Properties are the attributes you
set or retrieve. Each object has a long list of properties. These properties are very important to making the screen look right and to making the program
act right.

Setting Properties at Design-Time:

Design-time is the time when you are laying out your form and writing your program code. Most properties of any object may be set at design-time.
When an object on the form is selected, the properties for the object are displayed on the right-side of the IDE. To change or set a property, simply type
your desired change in the area next to the property name.

Examples of Label properties:

text - the text that appears on the screen


name - the name of the object

NB: We will never leave the names - Label1, Label2, etc - because these are not meaningful names and will be confusing.

We will use the suggested prefix (see above) and meaningful names so that others familiar with the standard naming conventions will more easily
understand your code. Eg. change the name of Label1 to lblTitle

font - controls the font, size, style (bold italics)


forecolor - controls the colour of letters. The properties window shows a coded number (more later on the hex number)
back color - controls the background color of the label (a box)
visible - controls whether the label is visible or not (True or False)

Examples of Form properties:

back color - controls the background color of the whole screen


text - the text that appears in the form's title bar
window state - controls how big the window is when the program is run
0 Normal 1 Minimized 2 Maximized (best)
name - the name of the form
eg. change Form1 to frmTitlescreen
FormBorderStyle - controls the appearance of the form=s border
also determines whether the user can resize the form
you set the BorderStyle property at design time
you cannot change the BorderStyle property at run time
Size - to set the size of a form

Changing Object Properties during Run-Time

When the user is running the program, this is called run-time. Any property of any object can be changed during run-time. The general form of
commands to change object properties is:

objectname.property=value

Examples:

lblQuestion.visible = False (makes lblQuestion invisible)


lblAnswer.ForeColor = &H000000FF& (changes the foreground color of the label to red. &H - hexadecimal number (base 16 - 0 1 2 3 4 5 6 7 8 9 A
B C D E F). To figure this number out, manually change the property and carefully record the number. The hexadecimal code numbers are built
based on so much Red Green and Blue)

Methods
Methods are actions that an object is pre-programmed to perform, such as move, hide, show itself, etc.

The Hide method, is an example of a method that does not have arguments. The following code makes the form frmGame disappear from view:
e.g. frmGame.Hide
In contrast, the FindString method, which finds a string in a ListBox requires the desired string to be found. The following code returns the location
in the ListBox of the word 'school':
e.g. location = lstBuildings.FindString("school")

Events
Events are actions the user can perfom, which objects can be programmed to respond to, such as click, double-click, keypress etc. An event is an
action recognized by an object. Clicking a mouse or pressing a key are examples of events.

Some events include:

4 of 31 7/25/17, 7:37 PM
Visual Basic Notes http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm#FormatFunctions

Activate DragOver Load

Change GotFocus LostFocus

Click KeyDown MouseDown

DblClick KeyPress MouseMove

DragDrop KeyUp MouseUp

Each object has its own set of events that it recognizes. The events listed do not apply to all objects. For example, a form can recognize either a Click or
DblClick event while a button only recognizes a Click event.

Adding Code to a VB Program


Every VB object may have code (programs) attached to it. When the user clicks on the object, VB will execute this program. Double click on an object
on the form at design-time to bring up its code window which looks like:

Private Sub objectname_Click()

End Sub

Your commands go in between Private Sub and End Sub. Commands are the lines of code you type in order to get the program to perform as you
desire.

Never erase or change Private Sub and End Sub.


Always rename your objects before coding them or the code will not be executed for the correct objects

Some sample lines of code include:

close - terminate the execution of the program


frmQ2.show - show frmQ2 on the screen (move to new question in Quiz program)
txtName.Text = "Hello, World!" - change the text itself to Hello, World!

Auto List Members Feature:

When the name of a control or object is entered, the Auto List Members feature presents a drop-down list of available members (such as properties and
methods).

When you type in the first few letters of the property name, the name is selected in the list. Pressing the TAB key enters the property in the code
window. In addition to accelerating your typing, this option is helpful when you aren't sure which properties are available for a given control.

The Auto Quick Info Feature:

The Auto Quick Info feature displays the syntax for statements and functions. When you enter the name of a valid Visual Basic statement or function,
the syntax is shown immediately below the current line with the first argument in bold, as shown in the following illustration. After you enter the first
argument value, the second argument appears in bold.

In the example above, notice the '1 of 12' to indicate there are 12 different possible sets of parameters that are acceptable.

Outputting Data
Information can be displayed to the user in a textbox. In your code you assign your output to the TEXT property of the textbox object.

If you do not want the user to change the contents of the output, then the ReadOnly property of the textbox can be set to true.
If you your output will be more than one line long, then set the MULTILINE property of the textbox object to true.
If your output will be many lines long and your textbox object is too short to display all the lines of output, you can add a scrollbar to the textbox
object, set the SCROLLBAR property to vertical.
To join together many strings into one output line, use the string concatenation operator (& or +).

5 of 31 7/25/17, 7:37 PM
Visual Basic Notes http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm#FormatFunctions

To assign non-strings to the textbox text property, use the convert-to-string builtin function ToString.
To start a new line, use the vbNewLine constant. (or the System.Environment.NewLine constant)
To left align a string and allow for padding on the right side of the string, with an exact number of output places, use the padRight(n) function with
'n' to indicate the room the output should take, such as "Tigers".padRight(20)
To format a number with an exact number of output places and align right, use the padLeft(n) command on the converted-to-string value, such as
50.ToString.padLeft(20)

Examples:
txtOutput.text = "hello there"

txtOutput.text = "hello" + " there"

txtOutput.text = "hello " + name

txtOutput.text = "hello " + name + vbNewLine + "goodbye now"

txtOutput.text = "hello " + name + vbNewLine


txtOutput.text = txtOutput.text + "goodbye now"

txtOutput.text = "my age is " + 16.ToString

txtOutput.text = name.padRight(15)

Internal Documentation:
Internal documentation, also called comments, are English statements added to your program code that explains your program to other people, which
the computer does not process. Adding comments to code makes it easier for someone else to determine what the code does. It also helps you to
understand the code at some later date.

In Visual Basic there are two methods for adding comments to code. Visual Basic ignores anything following a single quote (') or REM, so comments
can be placed on their own line or at the end of a line of code.

You must add the following comments to your program in the 'General' section:

1. question number
2. name
3. date
4. purpose of the project.

Example:
' assignment : 4
' programmer : Frank Furter
' date : Feb. 21, 2000
' purpose : A program that calculates profit for a company by reading from a file the
' revenue and expenses of a given 'file.

At the top of each sub/end sub, you must include comments to explain the code. Do not place a comment above each line of code.

To comment a section of your program, when you are testing a program and don't want some of the program to run, select the lines of text or code to be
commented and click Comment Block icon on the TextEdit toolbar.

To access the TextEdit toolbar, click on View, then Toolbars and then TextEdit.

Data Types
The computer stores all data (a number, a name) as a pattern of 0's and 1's. Each single letter is a different pattern of 16 0's and 1's. The same pattern
may mean the letter 'a' or the number 97. The computer knows how to interpret the patterns, because the programmer gives each pattern a data type. A
data type is an instruction that tells the computer how to interpret a pattern of 0's and 1's.

Visual Basic has the following data types:

Variable type Purpose Alternate Name Size Value range


Boolean 2 bytes True or False.
Byte 1 byte 0 through 255 (unsigned).
Char 1 character 2 bytes 0 through 65535 (unsigned).
Decimal 16 bytes 0 through +/-79,228,162,514,264,337,593,543,950,335 with no decimal point;
0 through +/-7.9228162514264337593543950335 with 28 places to the right of the
decimal; smallest nonzero number is
+/-0.0000000000000000000000000001 (+/-1E-28).
Double number with decimal portion 8 bytes -1.79769313486231570E+308 through
-4.94065645841246544E-324 for negative values; 4.94065645841246544E-324
through 1.79769313486231570E+308 for positive values.
Integer number without decimal portion Int32 4 bytes -2,147,483,648 through 2,147,483,647.
Long number without decimal portion Int64 8 bytes -9,223,372,036,854,775,808 through 9,223,372,036,854,775,807.
Short number without decimal portion Int16 2 bytes -32,768 through 32,767.
Single number with decimal portion 4 bytes -3.4028235E+38 through -1.401298E-45 for negative values; 1.401298E-45 through
3.4028235E+38 for positive values.
String Depends on implementing 0 to approximately 2 billion Unicode characters.
platform

6 of 31 7/25/17, 7:37 PM
Visual Basic Notes http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm#FormatFunctions

Variables:
A variable in computer programming is location in the computer's memory that will store a single value, to which you give a name and data type. You
can think of a variable as a storage box with a name for holding certain types of things:

This is the variable whose name is age and the number value 16 is stored in the box.

What is stored in this memory location can change; it can vary.

You must name your variables so that your program can remember where you stored the information and you must give a data type so the computer
knows how to interpret what is stored. In a machine's language these memory locations are numbered which can be very confusing for the programmer.
In a high level language like Visual Basic, good programmers give meaningful names to their variables, such as 'age' to store an age, 'name' to store a
name, 'address' to store an address. In doing this, programs become easier to follow. Variables like x and b can be used but it becomes more difficult to
know what is stored in them and using meaningless names is poor programming style and should be avoided wherever possible.

Naming Conventions for Variables

Visual Basic insists that the name of a variable must begin with a letter followed by letters, numbers or the underscore. You cannot put any special
characters such as spaces, hyphens, periods etc. in the variable name. You must also avoid using reserved words or command names like print, tab,
var, etc These words are part of the Visual Basic language and using them would confuse the processor.

Declaring Variables

It is good programming practice to declare all variables before they can be used in a program. We declare a variable to instruct the processor to set
aside a location in memory for our use, to assign a name to the memory location and to inform the processor what type of data we wish to store there. A
programmer in VB uses the keyword dim to declare a variable. There are several different types of data - integer, Double, string and boolean. String
data consists of any alphanumeric characters, such as names, addresses, phone numbers. Numbers can be stored as string data if you do not wish the
carry out mathematical operations on them.

Here are some declaration statements and what they do:

dim age as integer


This statement will set up a memory location called age to store an integer (a positive or negative number without decimals). In most computers an
integer only requires 2 bytes of memory.

dim answer as Double


This statement will set up a memory location called answer, to store real values (positive or negative numbers that contain a decimal portion). The
common number of bytes used is four.

dim flag as boolean


This type of variable can only have two values true or false. A boolean variable could be represented by one bit.

dim name as string


This statement will set up a memory location called name, to store string data - data consisting of alphanumeric characters. Each location will have
enough space set aside for up to 256 characters of string. (each character is one byte of information)

You can require that all variables be declared before they are used. You do that by placing the Option Explicit ON statement in the General
Declarations section of the module. This ensures that misspelled variable names do not get automatically declared by VB - which can cause program
errors that are difficult to find.

Assigning Values
Values can be assigned to a variable using the = sign. The variable name always appears on the left of the = sign. Whatever is on the right is evaluated
and then stored in the variable. The right side may be a literal (such as "Devoy"), a numeric value (such as 18), an object property (such as
txtName.text) or an expression (such as 3 + 1), or another variable.

Arithmetic Operators
Parentheses should be used when necessary to clarify the meaning of an expression. When no parentheses are used, normal BEDMAS rules apply.
VB has designated certain symbols to represent certain mathematical operators. See table below for details:

Operator Symbol Code Output


Addition + 3+4 7
Subtraction - 7-4 3
Multiplication * 4*7 28
Division / 25/5 5

7 of 31 7/25/17, 7:37 PM
Visual Basic Notes http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm#FormatFunctions

3 - rounds to the lowest


Integer Division \ 7\2
integer.

Exponent Math.pow() Math.pow(4, 2) (four squared) 16

Parentheses () (80 + 90 + 100)/3 90

4E-01 0.4
Scientific Notation E
5.6E02 560

Constants
A constant is a meaningful name that takes the place of a number or string that does not change. Although a constant somewhat resembles a variable,
you can't modify a constant or assign a new value to it as you can to a variable. VB has many predefined constants, these all start with vb___. User-
defined constants are declared using the Const statement, in a manner similar to declaring variables. For example:

const PI as Double = 3.141592


const TAX_RATE as Double = 0.08

Constants are used to make your program more readable, since a name such as TAX_RATE provides more meaning than a number such as 0.08. They
are also used when a value appears many times throughout your program - a change to the value of the constant must only be made in the declare, not
the many places in your program where the constant is use.

To make others aware that a name is a constant, it is good programming practice to make the name all capitals, with individual words separated by an
underscore.

Inputting Data
On a form, input form the user is frequently accepted in a textbox object. The TEXT property of the textbox object contains the user input. After the user
has typed their input into a textbox, they often are required to use the mouse to click a button. Your code can then assign the contents of the textbox
object to an appropriate variable.

Examples:
dim name as string
name = txtName.text

dim age as integer


age = Convert.ToInt32(txtAge.text)

dim cost as Double


cost = Convert.ToDouble(txtCost.text)

IPO Chart

Input Processing Output


list all data the user will input to make the program show how the input data will be converted into the output data list all data the program will output
work use the exact same names you have in the input and output columns use meaningful names
use meaningful names state the conversions as equations, as you would in Math class, with the output on the left side of the equal sign

student Name future age = student age + number of years future age
student age
number of years

Selection
In your computer program, you can instruct the computer to make a decision and then based on the decision, select to run a part of your program or not
run a part of your program. The Visual Basic command for making this selection is the 'if' command.

General format is:

if <condition> then
code to run only when the condition is TRUE
end if

Or:

if <condition> then
code to run only when the condition is TRUE
else
code to run only when the condition is FALSE
end if

You replace the <condition> with some test that can be true or false, such as grade = 11

Note: the 'else clause' is not required when no action is to be performed when the condition is false.

3 - way or More Decisions

if <condition1> then
code to run only when condition1 is TRUE

8 of 31 7/25/17, 7:37 PM
Visual Basic Notes http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm#FormatFunctions

elseif <condition2> then


code to run only when condition1 is FALSE and condition2 is TRUE
elseif <condition3> then
code to run only when condition1 is FALSE and condition2 is FALSE and condition3 is TRUE
else
code to run only when all conditions are FALSE
end if

Relational Operators

= equal to

< less than

> greater than

<= less than or equal to

>= greater than or equal to

<> not equal to

Note: two strings may be compared, or a string may be compared to a literal. In this case, the values are compared letter by letter, as you would list
words in a dictionary. However, capital letters come before lower case letters (eg. "A" is less than "a"). To compare strings without the concern for upper
and lower case, you may want to convert the strings to all capitals or lower letters prior to doing the compare (see UCase and LCase below).

Examples:
if userschoice = 6 then
(some code goes here)
end if

if age > 13 then


(some code goes here)
(another line of code goes here)
end if

if age >= 13 then


(some code goes here)
else
(some other code goes here)
end if

if town = "Winchester" then


(some code goes here)
elseif town = "Cambridge"
(some other code goes here)
elseif town = "Kitchener"
(some other code goes here)
else
(some other code goes here)
end if

Note that the else clause may be omitted, when not needed.

Coding Conventions

The code within each subsection of the selection (IF) structue is indented one TAB, for clarity. Remember to always indent your programs for easier
readibility.

Compound Selection Statements


At times we have a more complex condition than just one simple test to determine whether a portion of the program should be executed or not. In this
case we must connect together multiple tests using the Boolean operators.

Logical (Boolean) Operators

A Boolean expression can be formed using the logical operators AND, OR and NOT. A logical expression joins two expressions and creates an
expression that evaluates to either true or false. When AND is used both expressions must evaluate to true for the entire condition to be consider true.
If OR is used, either one of the expressions or both expressions must evaluate to true for the entire condition to be considered true.
If condition 1 AND condition 2 Then
Statements
Endif

If condition 1 OR condition 2 Then


Statements
Endif

If NOT condition 1 Then


Statements
Endif

9 of 31 7/25/17, 7:37 PM
Visual Basic Notes http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm#FormatFunctions

Operator Hierarchy

The use of parentheses with logical operators improves readability: however, they can be omitted sometimes.
Visual Basic has a operator hierarchy for deciding how to evaluate expressions without parentheses which is:

1. all arithmetic operations are carried out


2. then all expressions involving >,< and = are evaluated to true or false
3. then logical operators are next applied, in the order:
1. BRACKETS
2. NOT
3. AND
4. OR

Examples:
if age < 18 OR grade = 12 AND weight > 100 + 10 then
(some code goes here)
end if

if (heightA < heightB - 10 OR weight < 110) AND grade > 9 then
(some code goes here)
end if

IPO Charts - Selection


When creating IPO charts that make use of selection, clearly show the decision the computer will make. Indent any instructions that will be executed
based on the decision. It is not necessary to write the 'end if' command.

Input Processing Output


age if age < 18 or grade = 12 and weight > 100 + 10 then sports team eligible
grade
weight sport team eligible = true

else

sports team eligible = false

For Next Loops:


A loop is used to repeat a sequence of statements a number of times. When we know how many times a loop should be executed, a special type of
loop, called a ForNext loop can be used. The ForNext loop designates a numeric value, called the control variable, tht is initialized and then
automatically changes after each execution of the loop.

The For..Next loop takes on the following form:

For I = m to n
Statement(s)
Next I

I = control variable
M = initial value
N = terminating value

Example 1: A Program that displays the first five numbers and their squares.
Dim x As Integer
For x = 1 To 5
txtOutput.text = x.ToString + Math.pow(x , 2).ToString.padLeft(8)
Next x

In the above example, the control variable was increased by 1 after each pass through the loop. A variation of the For statement allows any number to
be used as the increment. The statement

For 1 = m to n step x

Instructs the next statement to add 'x' to the control variable instead of 1. The number x is called the step value of the loop.

Example 2: a program that that uses 0 as an intial number and requests an ending number and a step value as input from the user and then displays
the numbers within that range.
dim x As Integer
dim ends As Integer
dim increments As Integer

ends = Convert.ToInt32(txtEnds.Text)
increments = Convert.ToInt32(txtSteps.Text)

For x = 0 To ends Step increments


txtOutput.text = txtOutput.text + x.ToString + vbNewLine
Next x

Nested Loops
The statements inside a ForNext loop or a Do Loop can consist of another ForNext loop. Such a configuration is known as a nested loop and is

10 of 31 7/25/17, 7:37 PM
Visual Basic Notes http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm#FormatFunctions

useful in repeating a single data-processing routine several times.

Example 3: A program that prints a multiplication grid 3 X 3


dim j As Integer
dim k As Integer

txtOutput.text = ""
For j = 1 To 3
For k = 1 To 3
txtOutput.text = txtOutput.text + j.ToString + " X " + k.ToString + " = " + (j * k).ToString + Space(8)
Next k
txtOutput.text = txtOutput.text + vbNewLine
Next j

IPO Charts - For Loops


When creating IPO charts that make use of a 'for' loop, clearly show how many times the loop will repeat. Indent any instructions that will be repeated. It
is not necessary to write the 'next' command.

Input Processing Output


amount deposited final amount = amount deposited final amount
interest rate for the number of years
number of years final amount = final amount + final amount * interest rate

Do Loops
A DO LOOP repeats a sequence of statements either While or Until a certain condition is true. A DO statement precedes the sequence of statements
and a Loop statement follows the sequence of statements. The condition, along with either the word While or Until, follows the word Do.

The format for the DO LOOP is as follows:

Do While condition
Statements
Loop

Example 4: Write a program that displays the numbers 1 to 10 using a Do While


Dim num As Integer

num = 1
txtOutput.text = ""

Do While num <= 10


txtOutput.text = txtOutput.text + num.ToString + vbNewLine
num = num + 1
Loop

Example 5: Write a program that displays the numbers to 10 using a Do Until


Dim num As Integer

num = 1
txtOutput.text = ""

Do Until num >10


txtOutput.text = txtOutput.text + num.ToString + vbNewLine
num = num + 1
Loop

Example 6: Write a program that prints a message once the correct password is entered.
Dim password As String

txtOutput.text = ""

Do While password <> "HOOAH"


password = InputBox("Please enter your password")
password = UCase(password)
Loop

txtOutput.text = "Congratulations , you 've entered my server space."

File Input and Output


To date, our data has been put into memory using assignment statements created by the programmer
(e.g. name = "Frank Furter", num = 5)

or we have assigned the contents of an object to a variable


(e.g. name = txtName.text, num = Convert.toInt32(txtNumber) )

These methods are sufficient for small scale applications but with large volumes of data and most real-world applications we need a better , more

11 of 31 7/25/17, 7:37 PM
Visual Basic Notes http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm#FormatFunctions

versatile and accessible way of storing data. The hard disk or floppy disk offers the solution. Data files stored on disk can be accessed by several
programs for different purposes.

Why use a disk?

Non-programmers can use a program and modify the data on disk without knowing how to program, such as a student typing an essay in MS Word.
Data on a disk may be accessed and modified many times, such as changes to an essay. Data on a disk may be used by many different programs, such
as an essay created in MS Word used for input to a MS Publisher document.

Types of Disk-File Access

Your programs can access files in 2 ways

1. sequentially
2. randomly

A sequential file accesses information one record at a time, in the same order the records were written, this is like a cassette tape, where you must pass
by the first 3 songs to get the the fourth song.

A random access file can be accessed in any order you want. This is like songs on a CD where you can jump to any song you want, in any order.

Processing a Data File

The following 3 tasks must be carried out when accessing a data file:

1) Open the data file


2) Process the records, as required by the program (either read or write)
3) Close the file

Example #1:Write a program that uses a file for input and displays what is read. The form should consist of a command button and a textbox. Use
Windows' Notepad to create the file data.txt containing the following line.

Data.txt
4, High Street

Example: Programmer assigns values


Private Sub cmdDisplay_Click()

dim schoolNumber as integer


dim street as string

txtOutput.text = ""
schoolNumber = 4
street = " High Street"
txtOutput.text = "Mr. Devoy's house is located on " + schoolnumber.ToString + street

End Sub

Example: User stores values on hard/floppy disk and data is read from the file
Private Sub cmdDisplay_Click()

dim schoolNumber as integer


dim Street as string

txtOutput.text = ""
FileOpen(1, "data.txt", OpenMode.Input)

input(1, schoolNumber)
input(1, Street)

txtOutput.text = "Mr. Devoy's house is located on" + schoolnumber.ToString + street


FileClose(1)

End Sub

File Open Notes:

The open statement takes the form FileOpen(filenumber, "Filename", mode)

The filename is the name of file you created in Notepad.


Your file must be stored in the same folder as your executable program file (that is the 'bin' folder)
The mode is either OpenMode.Input, OpenMode.Output or OpenMode.Append.
The mode has the following affect:
input - looks for an existing file and places you at the beginning of the file for reading
output - creates an empty file if it doesn't already exist, or erases everything in an existing file and places you at the beginning ready to write
data
append - looks for an existing file and places you at the end, ready to write data.
The filenumber is an integer that links the file to a number from 1 to 255 used throughout the program, and is any number you choose.

12 of 31 7/25/17, 7:37 PM
Visual Basic Notes http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm#FormatFunctions

File Input Notes

The input statement takes the form INPUT (filenumber, variablename)

VB uses the keyword 'input' to read data from a file


the filenumber must be the same as used on the open command
the variablename must be a variable previously declared and the data in the file will be placed into this variable
Each input command moves further through the file.

File Output Notes

The output statement takes the form WriteLine ( filenumber, variablename, variablename,...)

VB uses the keyword 'WriteLine' to output data to a file


the filenumber must be the same as used on the open command
the variablename must be a variable previously declared and the data in the variable will be placed into the file
more than one variable may be on one WriteLine statement
Each WriteLine command moves further through the file.

Making Data Files

When creating a data file using Notepad, the format is important if the data is to be read in properly:

Insert commas between each data entry


No comma is required after the last data entry on a line. This comma is entered automatically.
Enclose a string with quotation marks if it contains commas or spaces as part of the string.
Since we are working with sequential files, the file must be read the same way in which it was created. For example, if the file contains four
variables... a string, an integer and then two more strings. To load the data back in, we must provide four variables of the same data type in the
same order.
Save your file in the 'bin' folder of your VB assignment, so the FileOpen command can find it (otherwise, full qualify the path to the file)

One of the main applications of programming is the processing of lists of data. A Do loop is used to display all or selected items from lists, search lists
for specific items, and perform calculations on the numerical entries of a list.

Example: User stores values on hard/floppy disk and all data is read from the file and displayed.

Create a file named data.txt with 5 names of friend (remember to enclose each name in quotes)
Private Sub cmdDisplay_Click()

dim count as integer


dim name as string

txtOutput.text = ""
FileOpen(1, "data.txt", OpenMode.Input)

for count = 1 to 5
input (1, name)
txtOutput.text = txtOutput.text + name + vbNewLine
next count

FileClose (1)

End Sub

EOF Function
Often the amount of data in a file may vary, unlike the example above that had 5 names. Instead of a counted loop (for) the data in a file to be
processed are often retrieved by a Do loop. Visual Basic has a useful function called, EOF, that tells us if we have reached the end of the file from which
we are reading. If a file has a reference number "1" then the function takes on the following form:

EOF(1)

Example 7: A program that displays the contents of a telephone directory. The names and phone numbers are contained in a file. The loop will repeat as
long as the end of file is not reached.
dim names As String
dim phone As String

FileOpen(1, "ex4.txt", OpenMode.Input)


Do While Not EOF(1)
Input (1, names)
Input (1, phone)
txtOutput.text = txtOutput.text + names + Space(5) + phone + vbNewLine
Loop

FileClose(1)

Example 8: A program that will search the telephone directory in the previous question for a name specified by the user. If the name does not appear in
the directory, a message of notification will appear.
dim names As String
dim phone As String

names = ""

13 of 31 7/25/17, 7:37 PM
Visual Basic Notes http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm#FormatFunctions

FileOpen ( 1, "ex4.txt", OpenMode.Input)

Do Until EOF(1) Or names = txtName.Text


Input(1, names)
Input(1, phone)
Loop

If names = txtName.Text Then


txtOutput.text = names + Space(5) + phone
Else
txtOutput.text = "Name not found"
End If

FileClose (1)

Counters and Accumulators


A counter is a variable that is used to calculate the number of elements in lists.
An accumulator is a variable that is used to sum numerical values in lists.

Example 9: A program that counts and finds the value of coins listed in a file.
dim numCoins As Integer
dim sum As Double
dim value As Double

sum = 0
numCoins = 0

FileOpen (1, "ex6.txt", OpenMode.Input)

Do While Not EOF(1)


Input (1, value)
numCoins = numCoins + 1
sum = sum + value
Loop

txtOutput.text = "The value of the " + numCoins.ToString + " coins is " + sum.ToString

In this example, numCoins is the counter because with each iteration of the loop, we add one to its value, thus in the end, we have counted
how many coins there were in the file.
In this example, sum is the accumulator because with each iteration of the loop, we add the value of the coin, thus in the end, we have
added up how much all the coins are worth.

Note the pattern of the count and accumulation statements: the count and accumulator variable appears on both the right and left side of the
equals sign!

Also, it is important to start the count and accumulator variables out at some value before we start the loop (in this case 0), this is called
initializing the variables.

Terminating a Form
To terminate a form - which exits the program when there is only one form - use the command:

me.close()

'me' refers to the form itself and close is a method of the form that will ask the form to terminate.

Debugging

Computer Programming Errors

Preparing a computer program to solve a problem requires you to be systematic and precise. What is more, a program that is less than correct is no use
at all. You must redefine it until it is perfect. When you first prepare a program it might produce crazy answers. You must correct the program errors or
bugs until it gives correct results on the test data that you feed it. You must give it a wide enough range of test data to ensure it always gives correct
results.

There are three types of errors:

1. syntax errors
2. run-time errors
3. logic errors

A syntax error is one that violates the grammatical rules or syntax rules of the programming language. A syntax error will result in an error message you
are typing your program, and so is easy to find and fix.

A run-time error is an error that occurs when the programming is running and some instruction is impossible for the computer to perform, such as
division by zero. The program is stopped and you are given a message box that asks if you want to END or DEBUG. If you select DEBUG, then VB
highlights the line of code with the error.

On the other hand, with a logic error the program correctly runs but performs the wrong task. These errors can only be found by examining the results
and running the program with a variety of test data. The correcting of program errors is called debugging.

Setting a breakpoint

Setting a breakpoint allows you to stop the programs execution at the line of code where the breakpoint is added. To set a breakpoint, click the Margin

14 of 31 7/25/17, 7:37 PM
Visual Basic Notes http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm#FormatFunctions

Indicator bar next to the line of code. When in break mode, you can move the mouse over any variable name and the ToolTip box will appear giving the
value of the variable. Once in break mode, you can click on the step into, step out or step over buttons on the debug toolbar to execute the program. To
step into a procedure means to run it one line at time. To step over a procedure means to run it as a unit. To step out of a procedure means to run until it
completes the current procedure and returns to the calling procedure. There are function key equivalents to the 'step into' 'step over' and step out of'
buttons.

Adding the debug toolbar

Right click anywhere on the code and click on debug. A second method is to click on View, Toolbars and Debug.

Immediate Window (when in Break mode)

Whenever you are in break mode, you can print the value of any variable in the immediate window. Simply type print variableName and press enter in
the immediate window. If the immediate window is not visible, simply click View and Immediate Window. For example, to print the value of the variable
intLoanPayment simply type print intLoanPayment or ? intLoanPayment. When you press enter, the value of the variable will be displayed. The program
must be running and in break mode for the immediate window to function.

Format Functions

In the following table n represents a number or numeric variable. date String represents a date in a form such as month/day/year.

Function Purpose Examples Output Value


Format(1/6,"Standard") 0.17
converts numbers to string representations having two decimal places and commas
Format(n,"Standard")
every three digits to the left of the decimal point Format(-12345,"Standard") -12,345.00

converts numbers to string representations with a leading dollar sign, two decimal Format(2000,"Currency") $2000.00
Format(n,"Currency") places, commas every three digits to the left of the decimal point, and encloses
Format(-0.2,"Currency") ($0.20)
negative numbers in parentheses

converts numbers to string representations and rounds numbers to whole numbers


Format(n,"#,0") Format(-10002.8,"#,0") -10,003
and places commas every three digits to the left of the decimal point

converts numbers to string representations and rounds numbers to two decimal


-----32.70 ( where -
Format(n,"###,###,##0.00) places and places commas every three digits to the left of the decimal point, taking a Format(32.7,"###,##0.00)
represent blanks)
minimum space of 14 places (# will be blank if no digit, 0 shows a digit always)

converts numbers to string representations of the numbers in percent with two


Format(n,"Percent") Format(0.281,"Percent") 28.10%
decimal places and a trailing percent sign

Format(-0.018,"Scientific") -1.80E-02
converts numbers to string representations of numbers in scientific notation with
Format(n,"Scientific")
decimal places Format(-1018,"Scientific") "-1.02E+03"

Format(dateString, returns a formatted version of the date Format("3/17/00","Long Date")


"LongDate")

"Friday, March 17, 2000"

Math Functions

Output
Function Purpose Examples
Value

Math.Sqrt(16) 4
Sqrt(n) calculates the square root of the number n
Math.Sqtr(2) 1.414214

pow(x, y) calculates x raised to the power of y Math.pow(2, 3) 8

Int(16.01) 16

Int(n) returns the number, with the fractional portion truncated Int(16.967) 16

Int(-16.11) -16

15 Mod 4 3
n Mod m returns the whole number remainder when n is divided by m
-8 Mod 3 -2

Round(n,d) returns n rounded to d decimal places Math.Round(7.666, 1) 7.7

15 of 31 7/25/17, 7:37 PM
Visual Basic Notes http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm#FormatFunctions

Random Numbers

Pseudo random numbers can be generated by the computer with the use of the Random class. To declare a random number generator:
dim randgen as Random

To create an object of the random generator:


randgen = New Random

To generate a random integer between 1 and 6 (including 1 but excluding 6)


dim number as Integer
number = randgen.Next(1, 6)

To generate a random decimal value between 0.0 and 1.0 (including 0.0 but excluding 1.0)
dim number as double
number = randgen.NextDouble()

String Functions

In the following table n and m represent numbers or numeric variables, str represents a string or string variable.

Function Purpose Examples Output Value


dim first as string samjones
sim last as string
dim fullName as string

first = "sam"
last = "jones"
String.concat(str1, str2) concatentation - joins together two strings
fullName = String.concat(first,last)

dim first as string samjones


sim last as string
dim fullName as string

first = "sam"
last = "jones"
+ (or &) concatentation - glue together 2 strings to create a longer string
fullName = first + last

returns a string consisting of n characters of str starting with the m'th character dim name as string ". Dev"
If the parameter n is omitted, str.substring(m) is all the characters from the m'th dim answer as string
character on. "voy"
str.substring(m,n) name="Mr. Devoy"
Note: the first character is in position 0 answer=name.substring(2,5)

answer=name.substring(6)
dim name as string
dim answer as string
str.Remove(m,n) removes n characters, starting at position m evoy
name="Mr. Devoy"
answer=name.remove(0,5)
dim name as string
dim answer as string
str.Insert(n,str2) inserts str2 in the middle of str, starting at position n Mr. Mike Devoy
name="Mr. Devoy"
answer=name.insert(3,"Mike ")
dim name as string
dim answer as string
str.ToUpper() changes all lowercase letters to uppercase "MR. DEVOY"
name="Mr. Devoy"

answer=name.ToUpper()
dim name as string
dim answer as string
str.ToLower() changes all uppercase letters to lowercase "mr. devoy"
name="Mr. Devoy"

answer=name.ToLower()
dim name as string
dim answer as string
str.Trim() removes all the spaces from the beginning and end of str "Mr. Devoy"
name=" Mr. Devoy "

answer = name.Trim()
dim num as integer
dim answer as string
num.ToString() converts numbers to strings "8"
num = 8

answer = num.ToString()
dim name as string
dim answer as string
str.Replace(find,replace) returns a new string with all occurences of find changed to replace "Mr. Divoy"
name="Mr. Devoy"

answer=name.replace("e","i")
dim name as string
str.equals(str2) returns true if str2 contains the same characters as str, false otherwise name = "Doyle" true
if name.equals("Doyle")
dim name1 as string
dime name2 as string
returns 0 if the characters in the two strings are the same, a negative value if the would be true since Doyle is
String.compare(str1,str2) name1="Doyle"
characters in str1 are alphabetically before str2, otherwise a postive number alphabetically before Mustang
name2="Mustang"

if String.compare(name1,name2)<0

16 of 31 7/25/17, 7:37 PM
Visual Basic Notes http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm#FormatFunctions

dim name1 as string


if case-insensitive is true, then compares as above but ignores upper and lower case dime name2 as string
would be false, the compare
differences.
String.compare(str1,str2,case-insensitive) name1="Doyle" returns a 0 since both strings are
if case-insensitive is false, compares as above name2="doyle" the same with case ignored

if String.compare(name1,name2,true)<0
dim name as string
adds spaces to the left of the string str to create a total width of n characters - used for "------Mike" (where - represent a
str.padLeft(n) name = "Mike"
right aligning blank)
name.padLeft(10)
dim name as string
adds spaces to the right of the string str to create a total width of n characters - used "Mike------" (where - represents a
str.padRight(n) name = "Mike"
for left aligning blank)
name.padRight(10)

String-Related Numeric Functions


In the following table n represents a number or numeric variable,str,str1,str2 represent strings or string variables.

Function Purpose Examples Output Value


dim name as string
dim answer as integer
str.Length() the number of characters in the string str 9
name = "Mr. Devoy"

answer = name.Length()
The value of the function is the position of str2 in str. dim word as string 6
dim answer as integer
Note: the first letter is postion 0
str.index(str2)
word = "function"

answer=word.index("o")
returns the ANSI number corresponding to the first character of str Asc("a") 97

Asc(str)

returns the single character corresponding to the ANSI value of int (reverse of Chr(97) a
Asc)
Chr(int)

converts a value in a string variable to an Integer variable type Convert.ToInt32("97") 97

Convert.ToInt32(str)

converts a value in a string variable to a single variable type Convert.ToSingle("97.5") 97.5

Convert.ToSingle(str)

converts a value in a string variable to a double variable type Convert.ToDouble("197.5") 197.5

Convert.ToDouble(str)

Space(n) a string consisting of n spaces "Go"&Space(3)&"Now" "Go Now"

Form Load
If you have code that you want executed automatically when a form comes up, put the commands in:

Form Load - only executes when the form is first loaded.

Warning: most often you should place your code inside the button click command, you should not normally need to use these events.

Message Boxes
Pop-up message boxes are created by the MessageBox.show command in your programming.

Examples of message boxes:

Messagebox.show("The postal code is not entered correctly.")

MessageBox.Show("You must enter a name.", "Name Entry Error", buttonsConstant, iconConstant)

where buttonsConstant can be one of many choices such as

MessageBoxButtons.OK
MessageBoxButtons.YesNoCancel
MessageBoxButtons.YesNo
MessageBoxButtons.OKCancel
MessageBoxButtons.RetryCancel
MessageBoxButtons.AbortRetryIgnore

where iconsConstant can be one of many choices such as

MessageBoxIcon.Exclamation
MessageBoxIcon.Asterisk

17 of 31 7/25/17, 7:37 PM
Visual Basic Notes http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm#FormatFunctions

MessageBoxIcon.Error
MessageBoxIcon.Hand
MessageBoxIcon.Information
MessageBoxIcon.None
MessageBoxIcon.Question
MessageBoxIcon.Stop
MessageBoxIcon.Warning

Using the Returned Value of message boxes

userschoice = MessageBox.show("Are you sure you want to quit?", "Quit",MessageBoxButtons.YesNo)

If userschoice = DialogResult.Yes Then


me.close()
End If

The MsgBox returns a numeric value depending on what the user does and this number is stored in the variable userschoice. Again, the numeric value
exists in built-in constants.

constant User's Action

DialogResult.OK Ok Button

DialogResult.Cancel Cancel Button

DialogResult.Abort Abort Button

DialogResult.Retry Retry Button

DialogResult.Ignore Ignore Button

DialogResult.Yes Yes Button

DialogResult.No No Button

Input Box
Usually, a text box is used to obtain input described by a label. Sometimes we want just one piece of input and would rather not have a text box and
label stay on the screen forever. The problem can be solved with an input box, which is an input form automatically created by VB for you. To display an
inputBox use the following statement.

dim response as string


response = InputBox(prompt, title)

Example:
dim lastname As String
lastname = InputBox("Please enter your last name", "Registration Entry")

if lastname = Nothing then


MessageBox.Show("You pressed the cancel button or didn't enter anything.")
else
MessageBox.Show("So you're the one that made this mess!")
end if

If the user presses the cancel button, then the value returned by the InputBox is the VB constant Nothing.

Modular Code - Subprograms


Large structures are built from smaller modules (e.g. Ikea furniture, Stereo, and computer systems) All these are modular because you build a complete
system from a set of individually purchased components. We can build complete computer programs from modules. VB has two types of modules we
can use to build up larger programs, they are called

1. subprograms (sometimes called procedures)


2. functions

Why use Modular Code within our programs?

Code becomes more organized and readable


Code will become smaller, faster, and more efficient using less code to do the same thing.
Allows teams of programmers to separate a project into smaller, independent parts that individuals can work on.

Subprograms /procedures

18 of 31 7/25/17, 7:37 PM
Visual Basic Notes http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm#FormatFunctions

Call statements:
A subprogram, as the name suggests, is a program written separately from the main program. It is like a mini-program. Each subprogram should do
one, well-defined job. To perform its job, a subprogram may have to be sent in some data, these are called arguments.

Running a Subprogram

Subprograms are run (executed) with the VB CALL statement.

Call AddNumber (num1, num2)

Notice that the first letter of the subprogram name, 'AddNumber' is uppercase to distinguish it from a variable.

Arguments:
Inside the parentheses of a Call Statement are arguments which in this case are variables. (num1, num 2). They could also be constants
AddNumber(2,3,) or expressions AddNumber(num1 + 2, num2 + 3).

Defining a Subprogram

The block of code that is to be the subprogram must start with the subprogram header and end with an 'End Sub' statement.

The subprogram header has the form:

Private Sub <subprogram name> ( <parameter declares>)

Subprogram Name

The subprogram name can be any name you choose. It must start with a letter and contain only letters, digits and _ (no blanks are allowed). In our
class, the name should take the form of at least two words that describe what the subprogram does, the first word should be a verb and the second
should be a noun.

Parameter Declares

Parameters are variables that are data that will be received by the subprogram from the main program, so it can do its job. They appear in the heading
of a subprogram, such as:

Private sub AddNumber (byVal num1 as Double, byVal num2 as Double)

the VB keyword byVal indicates that any changes by the subprogram to the value of a parameter, will not be sent back to the calling program
- you should always use ByVal unless you have a good reason not to!
the VB keyword ByRef indicates that any changes by the subprogram to the value of a parameter, ARE sent back to the calling program -
ByRef will normally only be used by subprograms that gather input from the textboxes on a form
the parameter type must be included (e.g. Double, string, integer)
the names of the arguments and parameters can be the same or different. What matters is that the order, number and types of arguments
and parameters match.

Creating a Subprogram

1. Move your cursor the end of your code, just before the 'End Class' statement
2. Type in the header of the subprogram which has the following format:
Private Sub <subprogram name> (<parameter declares>)
3. A separator line and two lines of code have been added at the bottom of the code window, along with an 'End Sub' statement.
4. Type the statements of the subprogram between the Private Sub and End Sub statements.

Properties of Procedures:

they are separate from the main program


they can use local variables
they can obtain parameters from, and return them to, the main program

Variable Scope:

Local Variables

The main program and each subprogram has its own set of variables - even if the variables have the same names! This means that a variable used in
the main program cannot be accessed by any of the Subs, and that variables used in the Subs cannot be accessed by the main program or any other
Subs. These variables are said to be Local. This makes sense when you consider that much of programming today uses the team approach. There
would be chaos if the variables in one sub could affect the values of variables in another sub.

Form-Level Variables:

Visual Basic provides a way to make a variable visible to every procedure in a form's code without being passed as a parameter. Such a variable is called
a form-level variable or global variable. Form-level variables appear at the top of the code window and are separated from the rest of the code by a
horizontal separator line.

Sub Program Examples


'Example 1:
'A program that adds two numbers without the use of subprograms.

19 of 31 7/25/17, 7:37 PM
Visual Basic Notes http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm#FormatFunctions

Option Explicit on

Private Sub cmdAdd_Click()

dim num1 As Double


dim num2 As Double
dim answer As Double

num1 = 2
num2 = 3
answer = num1 + num2

'Display the sum of two numbers

txtOutput.text = "This program displays a sentence" + vbnewline


txtOutput.text = txtOutput.text + "identifying two numbers and their sum." + vbnewline
txtOutput.text = txtOutput.text + "The sum of" + num1 +"and" + num2 + "is" + answer

End Sub

'Example 2: A program that adds two numbers and calls a subprogram to


'display the header

Option Explicit on

Private Sub cmdAdd_Click()

dim numl As Double


dim num2 As Double
dim answer As Double

numl = 2
num2 = 3
answer = num1 + num2

Call ExplainPurpose

txtOutput.text = txtOutput.text + "The sum of" + numl + "and" + num2 +"is" + answer

End Sub

Private Sub ExplainPurpose()

'Explain the task performed by the program

txtOutput.text = txtOutput.text + "This program displays a sentence" + vbnewline


txtOutput.text = txtOutput.text + "identifying two numbers and their sum."

End Sub

'Example 3:
'A program that calculates the sum of two numbers and calls 2 subprograms
'1st sub displays header
'2nd sub adds/displays the sum of 2 numbers by passing the values from the
'main program to the sub program 'AddDisplay

Option Explicit on

Private Sub cmdAdd_Click()

dim numl As Double


dim num2 As Double

num1 = 2
num2 = 3

Call ExplainPurpose
Call AddDisplay(num1, num2)

End Sub

Private Sub ExplainPurpose()

'Explain the task performed by the program


txtOutput.text = txtOutput.text +"This program displays a sentence" + vbnewline
txtOutput.text = txtOutput.text +"identifying two numbers and their sum." + vbnewline

End Sub

Private Sub AddDisplay(byVal num1 As Double, byVal num2 As Double)

'Display numbers and their subs


dim answer as Double
answer = num1 + num2
txtOutput.text = txtOutput.text +"The sum of" + num1 + "and" + num2 + "is" + answer

End Sub

'Example #4

'A program that calculates the sum of two numbers three times by including
'the numbers as arguments. Subprograms can be called an infinite number of
'times saving the programmer valuable time.

20 of 31 7/25/17, 7:37 PM
Visual Basic Notes http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm#FormatFunctions

Option Explicit on

Private Sub cmdAdd_Click()

'Display the sum of two numbers with the Add subprogram called several
' times.

Call ExplainPurpose
Call AddDisplay(2, 3)
Call AddDisplay(4, 6)
Call AddDisplay(7, 8)

End Sub

Private Sub ExplainPurpose()

'Explain the task performed by the program


txtOutput.text = txtOutput.text +"This program displays a sentence" + vbnewline
txtOutput.text = txtOutput.text +"identifying two numbers and their sum." +vbnewline

End Sub

Private Sub AddDisplay(num1 As Double, num2 As Double)

'Display numbers and their subs


txtOutput.text = txtOutput.text + "The sum of+; num1+"and"+ num2+"is" + num1 + num2

End Sub

'Example #5
'Calculates the sum of two numbers calling 3 subprograms
'1st sub explains purpose
'2nd sub gets two numbers inputted by the user
'3rd sub adds and displays the sum of two numbers.

Option Explicit on

Private Sub cmdAdd_Click()

'Calculates the sum of two numbers calling 3 subprograms

dim num1 As Double


dim num2 As Double

Call ExplainPurpose
Call GetData(num1, num2)
Call AddDisplay(num1, num2)

End Sub

Private Sub ExplainPurpose()

'Explain the task performed by the program


txtOutput.text = txtOutput.text +"This program displays a sentence" + vbnewline
txtOutput.text = txtOutput.text +"identifying two numbers and their sum." + vbnewline

End Sub

Private Sub AddDisplay(byVal num1 As Double, byVal num2 As Double)

'Display numbers and their subs


Dim answer As Double
answer = num1 + num2
txtOutput.text = txtOutput.text +"The sum of"+ num1+"and"+ num2+"is"+ answer

End Sub

Private Sub GetData(byRef num1 As Double, byRef num2 As Double)

'Receives two numbers from the user.


num1 = Convert.ToDouble(txtNum1.Text)
num2 = Convert.ToDouble(txtNum2.Text)

End Sub

User-Defined Functions
User-defined functions are the second type of module that VB supports. A function is similar to a subprogram because it is a block of code that performs
one job. Functions differ from subprograms, because a function always returns exactly one value. You have seen many functions in math class, to
execute a function you must send in a number or numbers and the function returns the answer, an example is the calculation of the area of a circle.

Properties of User-Defined Functions:

they are separate from the main program


they can use local variables
they can obtain parameters from the main program
they return exactly one value (answer), always

Executing a User-Defined Function:

Since functions return exactly one value, we must have a variable in which to store the answer returned. Because of this, functions are executed using
an assignment statement. For example, if our function is CalculateArea, then to run this function we would write:

21 of 31 7/25/17, 7:37 PM
Visual Basic Notes http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm#FormatFunctions

dim area as Double


area = CalculateArea(3) ' 3 is the radius of the circle

Defining a User-Defined Function

Creating a user-defined function is similar to creating a subprogram, except the last statement must be the answer to be returned. The block of code
that is to be the function must start with the function header and end with an 'End Function' statement.

The function header has the form:

Private Function <function name> ( <parameter declares>) As <return variable type>

Function Name

The function name can be any name you choose. It must start with a letter and contain only letters, digits and _ (no blanks are allowed). In our class,
the name should take the form of at least two words that describe what the function does, the first word should be a verb and the second should be a
noun.

Parameter Declares

Parameters are variables that are data that will be received by the function from the main program, so it can do its job. They appear in the heading of a
function, such as:

Private Function CalculateArea(byVal radius as Double) As Double

the VB keyword byVal indicates that any changes by the function to the value of a parameter, will not be sent back to the calling program -
you should always use ByVal unless you have a good reason not to!
the VB keyword ByRef indicates that any changes by the function to the value of a parameter, ARE sent back to the calling program - ByRef
will normally only be used by subprograms that gather input from the textboxes on a form and never by functions, in our class
the parameter type must be included (e.g. Double, string, integer)
the names of the arguments and parameters can be the same or different. What matters is that the order, number and types of arguments
and parameters match.

Return Variable Type

Since the function must return exactly one value (answer), the header is finished with the type of variable that will be sent back. It can be any of the VB
variable types (integer, Double, string, etc.)

Creating a Function

1. Move your cursor the end of your code, just before the 'End Class' statement
2. Type in the header of the function which has the following format:
Private Function <function name> (<parameter declares>) As <return type>
3. A separator line and two lines of code have been added at the bottom of the code window, along with an 'End Function' statement.
4. Type the statements of the function between the Private Function and End Function statements.

Function Example

'Example 1:
'A program that calculates the area of a circle.

Option Explicit on
Option Strict On

Private Sub cmdCircle_Click()


dim radius As Double
dim area As Double

radius = 2
area = CalculateArea(radius)

'Display the area

txtOutput.text = "The area of the circle is " + area.toString + vbnewline

End Sub

Private Function CalculateArea(byVal rad as Double) As Double

dim area as Double

area = Math.PI * Math.pow(rad,2)

return area
End Function

Showing Multiple Forms


A VB program may consist of many forms. The form that is first displayed when the program is started is specified in the project properties menu option.

22 of 31 7/25/17, 7:37 PM
Visual Basic Notes http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm#FormatFunctions

Within the dialog box that appears for the project properties, the 'startup Object' should indicate which form to load when the program is first started.

Other forms that may be in the solution can be shown in the code you write by using the VB method 'Show', this sets the Visible property of a form to
true. The 'Hide' method can be used to make a form disappear, this sets the Visible property of a form to false. To show a form called form2 and draw a
blue square we could add the code below to a button on the first form in our program.
' declare a form object called about, as a type of form2

Dim about As New form2()


about.Show()

' Draw a blue square on the form.


' NOTE: This is not a persistent object, it will no longer be
' visible after the next call to OnPaint. To make it persistent,
' override the OnPaint method and draw the square there

Dim g As Graphics = about.CreateGraphics()


g.FillRectangle(Brushes.Blue, 10, 10, 50, 50)

Modal Forms
At times you may want your program to use a second form to allow user input, but the standard input box does not meet your needs. In this case, you
need to design a second form, which you can show when needed. A form that appears and keeps the focus, until the user dismisses it, is called
'modal'. The VB method 'ShowDialog' is used to display the form. The ShowDialog method takes a parameter which is the parent of the dialog form.
After the user dismisses the dialog form, the contents of the form can be read, afterwhich you should dispose of the form to release unneeded memory.
' declare a form object called testDialog as a type of form we have already designed (form2)

Dim testDialog As New Form2()

' Show testDialog as a modal dialog and determine if user clicked OK button to leave

23 of 31 7/25/17, 7:37 PM
Visual Basic Notes http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm#FormatFunctions

If testDialog.ShowDialog(Me) = System.Windows.Forms.DialogResult.OK Then

' Read the contents of testDialog's TextBox.

txtResult.Text = testDialog.TextBox1.Text
Else
txtResult.Text = "Cancelled"
End If

testDialog.Dispose()

Arrays
A variable is a name to which the computer can assign a single value. An array variable is an ordered collection of variables of the same type to which
the computer can efficiently assign a list of values.

A variable mark would look like this:

mark
64

An array of 10 marks would look like this:

mark
index 64 77 87 75 65 54 95 47 66 87
0 1 2 3 4 5 6 7 8 9

All the storage boxes are called mark and to tell one from another, each has its own number, called the index. So, an array is similar to a motel, the
entire motel has one name and to distinguish between rooms, each has a number on the door. In each element of the array (room of the motel), we can
store one number. In the example above, 64 is stored in the first element of the mark array.

Creating an Array

In Visual Basic we first must declare (create) an array (build the motel) before we try to store information in it. The command for doing this is DIM.

DIM mark(20) as Double


Creates an array called mark with elements 0 to 20 that stores 21 Doubles

DIM age(15) as integer


Creates an array called age with elements 0 to 15 that stores 16 integers

DIM name(10) as string


Creates an array called name with elements 0 to 10 that stores 11 strings

Assigning Values to the elements in an Array

Mark(1) = 76 Stores the number 76 in the fist element of the array mark
Mark(3) = 87 Stores the number 87 in the third element of the array mark

Displaying values in an array


txtOutput.Text = mark(1).toString

To assign 0 in every element in mark


mark(0) = 0
mark(1) = 0
mark(2) = 0 ...
mark(20) = 0

OR
for x = 0 to 20
age(x) = 0
next x

To read from a file 20 marks and store in an array

FileOpen(1, "marks.text" ,OpenMode.Input)


For x = 0 to 19
input (1, mark(x))
Next x
FileClose (1)

To read from a file with an unknown number of record

FileOpen(1, "marks.text" ,OpenMode.Input)


count = 0

24 of 31 7/25/17, 7:37 PM
Visual Basic Notes http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm#FormatFunctions

Do while not eof(1)


count = count + 1
input (1, mark(count))
Loop
FileClose(1)

To display all 20 marks in Reverse Order

for x = 19 to 0 step -1
txtOutput.Text = txtOutput.Text + mark(x).ToString
next x

To display the values stored in odd elements, backwards, on one line:

For x = 19 to 0 step -2
txtOutput.Text = txtOutput.Text + mark(x).ToString
Next x

To Calculate the total of all ages and the average

total = 0 ' initialize variables


For x = 0 to 19
total = total + mark(x)
Next x
average = total/20
txtOutput.Text = total.ToString + average.ToString

To print the highest mark

highest = 0
For x = 0 to 19
If mark(x) > highest then
highest = mark(x)
end if
Next x
txtOutput.toString = highest.ToString

Example 1:Reading data into parallel arrays when the number of entries in known.

The table below gives names and test scores from a mathematics contest. Write a program to display the names of the students scoring above the
average for these eight students.

Richard Dolen 133

Geraldine Ferraro 114

James B. Fraser 92

John H. Malby 91

Paul H. Monsky 130

Max A. Plager 114

Rovert A. Shade 91

Barbara M. White 124

'The following program creates a string array to hold the names of the contestents
'and a numeric array to hold the scores. The number of contestents is known.
Private Sub cmdShow_Click()
dim total As Integer
dim student As Integer
dim average As Double

'Create arrays for names and scores

dim nom(7) As String


dim score(7) As Integer

'Assume the data has been placed in the file "SCORES.TXT"


'(The first line of the file is "Richard Dolen",135)

FileOpen(1, "student.txt" ,OpenMode.Input)


For student = 0 To 7
Input (1, nom(student))
Input (1, score(student))
Next student
FileClose (1)

'Analyze exam scores

total = 0
For student = 0 To 7
total = total + score(student)
Next student
average = total / 8

25 of 31 7/25/17, 7:37 PM
Visual Basic Notes http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm#FormatFunctions

'Display all names with above average grades

For student = 0 To 7
If score(student) > average Then
txtOutput.Text = txtOutput.Text + nom(student) + vbnewline
End If
Next student
End Sub

Dynamic arrays
Can be used when you don't know exactly how large to make an array because it can be resized at any time. After a dynamic array is initially declared,
you can add new elements as needed, rather than establishing the size of the array at the time the code is written.

You declare the array as dynamic by giving it an empty dimension list as follows:
dim age() as integer

To dimension the array, use the Redim command as follows:


Redim age(6)

Or, using a variable:


dim count as integer
count = 6
redim age(count)

Note: redim does not specify the type of the array again and the value in the brackets is the index of the upper bound.

Bounds of the Array


Since the upper bound can be changed by the redim command, we need a way to find what it has been set at. VB provides the function:

arrayname.GetLength(0) returns the number of elements in the 1 dimensional array, note that this will always be one larger than the index of the
upper bound because arrays are indexed starting at the number 0

To create a for loop that displays all elements of an array named 'age', without knowing the upper bound we can write:
for index = 0 to age.GetLength(0) - 1
txtOutput.Text = txtOutput.Text + age(index).ToString + vbnewline
Next index

Arrays as Parameters to functions and subs


Arrays can be sent to functions and subs as parameters. When sending an array as a parameter, just send the array name, not the array size or type.

This is true for user-defined functions and subs.

When creating a user-defined sub or function, we specify the array name and type, but not the bounds, in the function header, for example:
Private Sub DisplayNames(byref names() as string)

Note: passing an array byref means that a second copy of the array is not created, thus saving memory.

Related Arrays
Two or more arrays are said to be related, if they contain information that goes together, such as one array with student names and a second array with
scores. In this case, the index of the arrays connect the information in the arrays, for example, index 3 is student name smith and index 3 is the score
for smith.
'The following program creates a string array to hold the names of the contestants and a numeric array to hold the scores. The number of contestants
is unknown. Use the data file from the previous question.
private Sub cmdShow_Click()
dim numStudents As Integer
dim nTemp As String
dim sTemp As Integer
dim student As Integer
dim Total As Integer
dim average As Double
dim nom() as string
dim score() as integer

'Determine amount of data to be processed

numStudents = 0
FileOpen(1, "scores.txt" ,OpenMode.Input)

Do While Not EOF(1)


Input #1, nTemp, sTemp
numStudents = numStudents + 1
Loop
FileClose (1)

'Create arrays for names and scores

redim nom(numStudents-1) As String


redim score(numStudents-1) As Integer

26 of 31 7/25/17, 7:37 PM
Visual Basic Notes http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm#FormatFunctions

FileOpen(1, "scores.txt" ,OpenMode.Input)

For student = 0 To numStudents-1


Input #1, nom(student), score(student)
Next student
FileClose (1)

'Analyze exam scores

Total = 0
For student = 0 To numStudents-1
Total = Total + score(student)
Next student
average = Total / numStudents

'Display all names with above average grades

For student = 0 To numStudents-1


If score(student) > average Then
txtOutput.Text = txtOutput.Text + nom(student) + vbnewline
End If
Next student
End Sub

StopWatch Object
VB has a class named StopWatch which can be used to determine an elapsed time between two times.

To declare a StopWatch object:


dim myWatch as New StopWatch

The StopWatch methods and properties are:

Method/Property Purpose Examples Output Value

Start starts, or resumes, measuring elapsed time for an interval


myWatch.Start()

Stop stops measuring elapsed time for an interval myWatch.Stop()

number of milliseconds between when the watch


ElapsedMilliseconds returns the elapsed time of interval, measured in milliseconds myWatch.ElapsedMilliseconds
was started and stopped

To calculate how many milliseconds a block of code has been running for (the elapsed time):
Dim myWatch as New StopWatch

myWatch.Start()

.... block of code to time goes here ...

myWatch.Stop()

timeElapsed = myWatch.ElapsedMilliseconds

Searching

Linear Search

If we had an array of 500 names and wanted to find the location of a specific name in the array, we could start at the first element of the array, check it,
then move to the next element of the array, check it, and so on until we found the name we wanted, or until we reached the end of the array.

The algorithm can be stated as:


current index = 0

found = false
foundIndex = -1

repeat while not found and current_index < array_upper_bound


if current_list_element = desired_element then
found = true
foundIndex = current_index
else
add 1 to current index

To code a user-defined function in VB that returned the index of a name in an array of names, we could write:

27 of 31 7/25/17, 7:37 PM
Visual Basic Notes http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm#FormatFunctions

private function findName(byref names() as string, byval seekName as string) as integer


dim found as boolean
dim currentIndex as integer
dim foundIndex as integer

found = false
foundIndex = 0
currentIndex = 0

do while (NOT found and currentIndex < names.GetLength(0))


if seekName = names(currentIndex) then
found = true
foundIndex = currentIndex
else
currentIndex = currentIndex + 1
end if
loop

if found then
return foundIndex
else
return -1
end if
end sub

The linear search is easy to understand and code. It will work on any array. However, it is not an efficient searching technique.

Binary Search

If we had an array of 500 names in alphabetical order and wanted to locate a specific person in the list we one approach is to start with the first name
and consider each name until a match was found. This process is called a linear search. We would find a persons name that begins with the letter "A"
considerably faster than we would a name beginning with "Z". This method is time-consuming for large lists.

If a list has already been sorted a more efficient binary search can be performed.

Sample List:

1. Alex
2. Dave
3. Dan
4. Dylan
5. Jason
6. Kyle
7. Matt
8. Saroja

Lets assume we are looking for the name Kyle. A binary search looks for which half of the list the name lies in and discards the other half. The retained
part of the list now becomes the entire list. This process is repeated until the item is found. A flag can indicate if Kyle is found. This is much the same
way you would look up a person in the telephone book.

The algorithm is as follows:

1. At each stage, denote the subscript of the first item in the retained list by first and the subscript of the last item by last. Initially, the value of first is
the lower bound of the array, the value of last is the upper bound of the array, and the value of the found flag is False.
2. Look at the middle item of the current list, the item having the subscript middle = int(first + last)/2).
3. If the middle item is Kyle, the flag is set to True and the search is over.
4. If the middle item is greater than Kyle, then Kyle should be in the first half of the list. So the subscript of Kyle must lie between first and middle
1. That is, the new value of last is middle 1
5. If the middle item is less than Kyle, then Kyle should be in the second half of the list of possible items. So the subscript of Kyle must lie between
middle + 1 and last. That is, the new value of first is middle + 1
6. Repeat steps 2 through 5 until Kyle is found or until the halving process uses up the entire list. (When the entire list has been used up, first
>=last.) In the second case, Kyle was not in the original list.

To code a user-defined function in VB that returned the index of a name in an array of names, we could write:
private function findName(byref names() as string, byval seekName as string) as integer
dim found as boolean
dim lowIndex as integer
dim highIndex as integer
dim middleIndex as integer

found = false
lowIndex = 0
highIndex = names.GetLength(0) - 1
middleIndex = Convert.toInt32((highIndex + lowIndex)/2)

do while (NOT found and lowIndex <= highIndex)


if seekName = names(middleIndex) then
found = true
elseif seekName > names(middleIndex) then
lowIndex = middleIndex + 1
middleIndex = int((highIndex + lowIndex)/2)
else
highIndex = middleIndex - 1
middleIndex = int((highIndex + lowIndex)/2)
end if
loop

if found = true then

28 of 31 7/25/17, 7:37 PM
Visual Basic Notes http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm#FormatFunctions

return middleIndex
else
return -1
end if

end sub

The binary search is not as easy to code or understand as the linear search, and the array must be sorted, however, it is much more efficient than the
linear searching technique.

Sort Algorithms
There are many different types of sorting routines. Here are some examples. Below is the pseudocode for two different sorts.

Selection Sort

In a selection sort, we start at one end of the array - the 'selected' element. We compare each element in the array against the selected element and
swap them if necessary. When one pass through the entire array is complete, the selected element contains the largest (or smallest) value. We then
select the next element to compare all elements against.
for i = the beginning of the array to the end-1

for j = the i+1 element to the last element


if the jth element is smaller than the ith element
swap the jth element with the ith element

More information is here.

Bubble Sort

In a bubble sort, adjacent values are compared and exchanged if they are not in order. With each pass through the entire array, one more value
'bubbles' up into place.

for i = beginning of the array to the end-1

for j : beginning of the array to i-1

if the jth element is smaller than the j+1 element


swap the jth element with the j+1 element

More information is found here,


A more efficient version is found here.
A quiz if found here.

Multidimensional Arrays:
Two dimensional arrays can be thought of as looking like a table, with rows and columns. The rows are the first dimension and the columns are the
second dimension.

columns
|
v

rows ->

The following statement declares a two-dimensional 10-by-10 array:


dim matrixA(9, 9) as Double

Two dimensional arrays can also be dynamic arrays and declared without any size and then later dimensioned, for example:
dim matrixA(,) as String (Note: the comma is required to indicate 2 dimensions)
dim matrixA(5, 7)

To determine the number of rows and columns of an existing two dimensional array, we can use the GetLength command. The parameter after the array
name is the dimension number we are interested in getting (starting at 0). For example:
dim rows as integer
dim columns as integer
rows = matrixA.GetLength(0) - 1
columns = matrixA.GetLength(1) - 1

When accessing an element of a two dimensional array, we must always specify both dimensions. For example, the output the value of an element in
row 5, column 2 to a picture box, we would write:
txtOutput.Text = matrixA(5, 2)

Two dimensional arrays are often processed in nested for loops. For example, to output all elements of a matrix, we would write:
for row = 0 to matrixA.GetLength(0) - 1
for column = 0 to matrixA.GetLength(1) - 1

29 of 31 7/25/17, 7:37 PM
Visual Basic Notes http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm#FormatFunctions

txtOutput.Text = txtOutput.Text + matrixA(row, column)


next column
next row

Menus
You can make your VB projects very professional by adding menus to your programs. You select the MainMenu control from the toolbox an draw it
anywhere on the form. You must also set the form property 'MenuName' to MainMenu, so the menu is displayed when the program runs.

ALT + letter shortcuts:

Type an & in front of the letter for which you would like the shortcut. For example, if you want ALT + f in the file menu simply type &File in the caption
section of the menu editor

Code:

To add code to the menu option simply double click on the menu item in the project window and the code window with the sub/end sub for that menu
item will be displayed. Add you code.

Timer Objects
A timer can be placed on a form. It does not appear when the program is run. The timer goes off after a set number of clicks (interval property). When
the timer goes off it runs the code in the timer_timer sub. It continues to run the program in the timer sub every time the time interval is reached and in
that sense is also a repetition structure.

Moving Images
Images have 2 properties that control where the image appears on the form - .left and .top. The numbers for these properties start at the upper left
corner of the form. As the top number increases the image moves down the screen. As the left number increases the images moves to the right

To move the image change its top and left properties.

You can change the picture shown by a pictureBox by copying the picture from another pictureBox object (usually invisible).

picImage1.picture = picImage2.picture

changes image1 to the picture that is in picImage2

The switching is done by a boolean variable, if statement and a not.

Example of switching images:

in module

public switch as boolean

in timer

if switch then
picRealimage.picture = picInvisibleimage1.picture
else
picRealimage.picture = picInvisibleimage2.picture
end if
switch = not switch

Reading from an Access Database


Data may be stored in an Access Database, rather than a text file. Databases allow you to access data in a direct manner, rather than needing to read
through all the data to find what you want. In addiiton, with the use of an SQL SELECT statement, a database finds only the data you are interested in.
The example below builds an SQL statement that selects just the OrderID and CustomerID fields from the Orders table where the CustomerID is equal
to a value taken from a textbox on the form and the amount of the order is greater than an amount taken from a textbox on the form. The Access
database called Customer.mdb holds the data. A Reader object returns the data desired.
Dim mySelectQuery As String = _
"SELECT OrderID, CustomerID FROM Orders WHERE CustomerID = '" & txtCust.Text & "' AND Amount > '" & txtAmount.Text & "'"
Dim myConnString As String = _
"Provider=Microsoft.Jet.Oledb.4.0;Data Source=Customer.mdb"
Dim myConnection As New OleDbConnection(myConnString)
Dim myCommand As New OleDbCommand(mySelectQuery, myConnection)
myConnection.Open()
Dim myReader As OleDbDataReader = myCommand.ExecuteReader()

dim strOutput as string

Try
While myReader.Read()
strOutput = "Customer: " & Reader.Item("CustomerID") & vbNewLine
strOutput &= "Order:" & Reader.Item("OrderID")
MessageBox.Show(strOutput, "Search Results")
End While

Catch ex As Exception
MessageBox.Show("An error accessing the database.", "ERROR!")

Finally
' always call Close when done reading.
myReader.Close()

30 of 31 7/25/17, 7:37 PM
Visual Basic Notes http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm#FormatFunctions

' always call Close when done reading.


myConnection.Close()
End Try

ListBox Control
A ListBox control, displays a list of items. If the total number of items exceeds the number that can be displayed, a scroll bar is automatically added to
the ListBox control.

To add items in a ListBox control, use the Items.Add, for example:


lstNames.Items.Add("Michael")

To remove all items from the ListBox control, use the Items.Clear method, for example:
lstNames.Items.Clear()

ListView Control
A ListView control can display a table of rows and columns. To set the the ListView control to display information in rows and columns, set the View
property to Details.

Column titles are added at design time by using the Columns property, click the ellipses next to Collections. The ColumnHeader Collections Editor then
appears and you can add the column headings in the Text property for each column.

Each row in the ListView control is considered an ListViewItem.To start a new row, create a new ListViewItem. The columns, after the first, are considered
subitems. To add data to the columns use the SubItems.Add() method. When you have created all the data for the row, then add the row to the ListView
with the Items.Add() method. For example:

Dim row As ListViewItem


row = New ListViewItem("Mike")
row.SubItems.Add("Casey")
row.SubItems.Add("12")
row.SubItems.Add("M")
lvwNames.Items.Add(row)
row = New ListViewItem("Pete")
row.SubItems.Add("Smith")
row.SubItems.Add("10")
row.SubItems.Add("M")
lvwNames.Items.Add(row)
row = New ListViewItem("Sue")
row.SubItems.Add("Jones")
row.SubItems.Add("10")
row.SubItems.Add("F")
lvwNames.Items.Add(row)

31 of 31 7/25/17, 7:37 PM

Das könnte Ihnen auch gefallen