Beruflich Dokumente
Kultur Dokumente
htm#FormatFunctions
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
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.
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.
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.
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
All these methodologies are used to coordinate teams of programmers working on large projects. Each methodology has its strengths and weaknesses.
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
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
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.
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.
3 of 31 7/25/17, 7:37 PM
Visual Basic Notes http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm#FormatFunctions
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.
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.
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
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:
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.
4 of 31 7/25/17, 7:37 PM
Visual Basic Notes http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm#FormatFunctions
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.
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.
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 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 = 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.
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.
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.
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.
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:
7 of 31 7/25/17, 7:37 PM
Visual Basic Notes http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm#FormatFunctions
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:
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
IPO Chart
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.
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.
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
Relational Operators
= 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
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.
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
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:
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
else
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)
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
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
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.
Do While condition
Statements
Loop
num = 1
txtOutput.text = ""
num = 1
txtOutput.text = ""
Example 6: Write a program that prints a message once the correct password is entered.
Dim password As String
txtOutput.text = ""
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.
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.
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.
The following 3 tasks must be carried out when accessing a data 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
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()
txtOutput.text = ""
FileOpen(1, "data.txt", OpenMode.Input)
input(1, schoolNumber)
input(1, Street)
End Sub
12 of 31 7/25/17, 7:37 PM
Visual Basic Notes http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm#FormatFunctions
The output statement takes the form WriteLine ( filenumber, variablename, variablename,...)
When creating a data file using Notepad, the format is important if the data is to be read in properly:
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()
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
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
FileClose (1)
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
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
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.
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.
Right click anywhere on the code and click on debug. A second method is to click on View, Toolbars and Debug.
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.
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
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"
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
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
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 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.
first = "sam"
last = "jones"
String.concat(str1, str2) concatentation - joins together two strings
fullName = String.concat(first,last)
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
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)
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)
Convert.ToInt32(str)
Convert.ToSingle(str)
Convert.ToDouble(str)
Form Load
If you have code that you want executed automatically when a form comes up, put the commands in:
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.
MessageBoxButtons.OK
MessageBoxButtons.YesNoCancel
MessageBoxButtons.YesNo
MessageBoxButtons.OKCancel
MessageBoxButtons.RetryCancel
MessageBoxButtons.AbortRetryIgnore
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
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.
DialogResult.OK Ok 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.
Example:
dim lastname As String
lastname = InputBox("Please enter your last name", "Registration Entry")
If the user presses the cancel button, then the value returned by the InputBox is the VB constant Nothing.
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
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.
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:
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:
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.
19 of 31 7/25/17, 7:37 PM
Visual Basic Notes http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm#FormatFunctions
Option Explicit on
num1 = 2
num2 = 3
answer = num1 + num2
End Sub
Option Explicit on
numl = 2
num2 = 3
answer = num1 + num2
Call ExplainPurpose
txtOutput.text = txtOutput.text + "The sum of" + numl + "and" + num2 +"is" + answer
End Sub
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
num1 = 2
num2 = 3
Call ExplainPurpose
Call AddDisplay(num1, num2)
End Sub
End Sub
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
'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
End Sub
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
Call ExplainPurpose
Call GetData(num1, num2)
Call AddDisplay(num1, num2)
End Sub
End Sub
End Sub
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.
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
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.
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:
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.
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
radius = 2
area = CalculateArea(radius)
End Sub
return area
End Function
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
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)
' 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
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.
mark
64
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.
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
OR
for x = 0 to 20
age(x) = 0
next x
24 of 31 7/25/17, 7:37 PM
Visual Basic Notes http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm#FormatFunctions
for x = 19 to 0 step -1
txtOutput.Text = txtOutput.Text + mark(x).ToString
next x
For x = 19 to 0 step -2
txtOutput.Text = txtOutput.Text + mark(x).ToString
Next x
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.
James B. Fraser 92
John H. Malby 91
Rovert A. Shade 91
'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
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
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
Note: redim does not specify the type of the array again and the value in the brackets is the index of the upper bound.
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
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
numStudents = 0
FileOpen(1, "scores.txt" ,OpenMode.Input)
26 of 31 7/25/17, 7:37 PM
Visual Basic Notes http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm#FormatFunctions
Total = 0
For student = 0 To numStudents-1
Total = Total + score(student)
Next student
average = Total / numStudents
StopWatch Object
VB has a class named StopWatch which can be used to determine an elapsed time between two times.
To calculate how many milliseconds a block of code has been running for (the elapsed time):
Dim myWatch as New StopWatch
myWatch.Start()
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.
found = false
foundIndex = -1
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
found = false
foundIndex = 0
currentIndex = 0
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.
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)
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
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.
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 ->
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
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.
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
You can change the picture shown by a pictureBox by copying the picture from another pictureBox object (usually invisible).
picImage1.picture = picImage2.picture
in module
in timer
if switch then
picRealimage.picture = picInvisibleimage1.picture
else
picRealimage.picture = picInvisibleimage2.picture
end if
switch = not switch
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
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 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:
31 of 31 7/25/17, 7:37 PM