Ltpi VB
Ltpi VB
S Langfield
Learning to Program in
Visual
Basic .NET >>
S Langfield
Published by
PG Online Limited
The Old Coach House
35 Main Road
Tolpuddle
Dorset
DT2 7EW
United Kingdom
sales@pgonline.co.uk
www.pgonline.co.uk
Graphics: PG Online Ltd
Design and artwork: PG Online Ltd
First edition 2019
A catalogue entry for this book is available from the British Library
ISBN: 978-1-910523-18-6
Copyright © S Langfield, PM Heathcote, 2017
All rights reserved
iii
Downloading Visual Basic .NET
LEARNING TO PROGRAM IN VISUAL BASIC
iv
Contents
Chapter 1 – Input, output and assignment 1
Programming in VB .NET 1
Programming in VB .NET console mode 2
Adding comments 4
Programming conventions 5
Data types 5
Rounding a result 6
Variables7
Augmented assignment operators 9
The Write and WriteLine statements 9
The ReadLine statement 11
Chapter 3 – Selection 20
Programming constructs 20
Boolean conditions 21
The ElseIf clause 21
Case statements 22
Nested selection statements 23
Complex Boolean expressions 23
Generating a random number 24
v
Chapter 4 – Iteration 26
LEARNING TO PROGRAM IN VISUAL BASIC
vi
Chapter 9 – Reading and writing files 67
Storing data 67
Records and fields 68
Opening, reading and closing a text file 68
Writing to a file 72
Formatting output 75
File processing 77
vii
Chapter 13 – Developing a Windows application 107
LEARNING TO PROGRAM IN VISUAL BASIC
Index127
viii
Chapter 1
Input, output and assignment
Objectives
• Write a simple console application
• Use string, numeric and Boolean data types and operators
• Learn the rules and guidelines for declaring and naming variables
• Use input and output statements
Programming in VB .NET 1
Visual Basic (VB) is a popular programming language. A VB program is simply a series of
instructions written according to the rules or syntax of the language, usually designed to
perform some task or come up with a solution to a problem. You write the instructions,
and then the computer translates these instructions into binary machine code which the
computer can execute. It will do this using a translator program, called a compiler.
VB.NET is the latest version of the Visual Basic programming language. It comes with an
integrated development environment (IDE) which enables you to enter your program,
save it, edit it, translate it to machine code and run it once it is free of syntax errors. If you
have written a statement incorrectly, it will be reported by the IDE or the compiler as a
syntax error, and you can correct it and try again.
You can write simple programs as a console application or you can write Windows®
based applications using Windows forms (see Chapters 12 and 13).
1
Augmented assignment operators
Using & has the advantage that you do not have to worry about the variable type. You can
mix integers, real numbers and strings in the Write statement.
9
ARRAYS AND TUPLES
What will happen if you write
Q1 Dim name = {"Mark", "Juan", "Ali", "Cathy",
"Sylvia", "Noah"}
For index = 0 To 6
Console.WriteLine(name(index))
Next
Operations on arrays
Some array methods are shown in the table below. Assume a = {45,13,19,13,8}.
Example 2
Determine whether the number 100 is in the array
numbers = {56,78,100,45,88,71}, and if so, print its index.
'Program name: Ch 5 Example 2 Array of numbers
Dim numbers = {56, 78, 100, 45, 88, 71}
Dim index = Array.IndexOf(numbers, 100)
If index = -1 Then
Console.WriteLine("100 is not in the array")
Else
Console.WriteLine("100 is at index number: " & index)
End If
An array is a static data structure, that means it is fixed in size. The elements of an array
must all be of the same data type.
35
produces the output:
LEARNING TO PROGRAM IN VISUAL BASIC
The table below shows some of the most useful built-in dictionary methods.
Method Description
ContainsKey(key) Finds if a key is present in the dictionary
Add(key, value) Adds a key to the dictionary
Keys Returns all the keys in the dictionary
Remove(key) Removes an item from the dictionary
7 Table 7.1: Useful dictionary methods
52
Example 6
LEARNING TO PROGRAM IN VISUAL BASIC
Write a program that uses StreamWriter to create a new file called temperatures.txt, or
append records to the file if one already exists.
Imports System.IO
' Program name: Ch 9 Example 6 writing to a file using
StreamWriter
Module Module1
Sub Main()
Dim tempsFile As New StreamWriter("temperatures.txt",
True)
Dim city, localTime As String
Dim temperature As Integer
Console.WriteLine("Writes data to temperatures.txt")
Console.WriteLine("If file does not exist, it will
be created")
Console.Write("Enter city name, xxx to end: ")
city = Console.ReadLine()
Do While Not city = "xxx"
Console.Write("Enter temperature: ")
temperature = Console.ReadLine()
Console.Write("Enter local time: ")
localTime = Console.ReadLine()
tempsFile.WriteLine(city & "," & temperature &
"," & localTime)
Console.Write("Enter city name: ")
city = Console.ReadLine()
Loop
tempsFile.Close()
Console.Write("Press Enter to exit ")
Console.ReadLine()
9 End Sub
End Module
Example 7
Read the data in the file temperatures.txt, convert all the Centigrade temperatures to
Fahrenheit and print out both the Centigrade and Fahrenheit temperatures.
Imports System.IO
' Program name: Ch 9 Example 7 process temperatures file
Module Module1
Sub Main()
Dim tempsFile = 1
Dim city, localTime As String
Dim temperatureC As Integer
Dim temperatureF As Double
74
Controls
LEARNING TO PROGRAM IN VISUAL BASIC
Controls are GUI objects, such as buttons and text entry fields, that are used to interface
with the program. They can also be used to display information to the user in the form of
a label or a graphic. When adding a control to the form designer, it is a good idea to give
it a sensible name, so that your program code will be easier to maintain. The convention is
to use a prefix with each control identifier that represents the control’s type. For example,
the identifier for a confirm button might be btnConfirm.
Here is a list of prefixes for some common components along with an example:
102
Sample application 3
LEARNING TO PROGRAM IN VISUAL BASIC
This application allows a user (for example, a teacher) to create a multiple-choice test
consisting of several questions which could be saved in a text file or database. The input
window will look like this:
Create a new Windows Forms App project and add the following components to the
form. The values for key properties are shown below.
13 Component
Form1
Property
Text
Value
Question entry
BackColor 192, 255, 255
GroupBox1 Text ""
BackColor 224, 224, 224
Label1 Text Name of test
Font Arial, 12pt, Bold
TextBox1 Name txtTestName
GroupBox2 Text ""
BackColor 224, 224, 224
Label2 Text Question number
Label3 Text Question
Label 4 Text Possible answers
Label5 Text Correct answer:
TextBox2 Name txtQuestionNumber
114
Index
INDEX
A D F
ampersand 9 database fields 40, 68
append mode 72 attribute 81 file processing 77
array 34 connection object 87 flat file 80
2D 37 creating 85 For Each loop 31
array processing 36 error handling 95 For loop 26
Asc() 46, 58 field 81 nested 27
ASCII code 44 flat file 80 format check 43, 48
assignment operator 7 primary key 81 format items 75
assignment statement 8 query 92 format modifiers 76
attribute 81 record 81 format operators 75
augmented assignment updating 97 formatting output 75
operators 9 database table functions 18, 57
add new record 82 string 14
data structure
B static 35
Boolean 6, 21
data types 5
G
expressions 23 global variable 63
Boolean 6
condition 28 group boxes 108
collection 51
breakpoint 123 GUI application 107
floating-point 5
built-in functions 58
numeric 5
button 103
string 5 I
debugging 120, 123 identifier 81
C decimal 5 index 31
call statement 59 Designer view 104 indexing arrays 34
camel case 8 dictionary 51 Indexing strings 31
case statements 22 key 51 initialise 36
Chr() 46 value 51 input statement 33
Clear button 110
close() method 88
command object 87
Do ... Loop 30
dot notation 40
double 5
integer 5
integer division 5
integrated development
I
comments 4 Do Until 30 environment 1
commit() method 88 Do While 30 interrupting execution 32
compiler 1 InvalidCastException 10
composite formatted strings 75 iteration 20
E
concatenate 5, 9
ElseIf 21
connection object 87
console mode 2
encapsulation 64 K
event subroutines 110 key-value pair 53
constants 19
ExecuteNonQuery() method 88
control 102
conventions 5
cursor object 87
127
L Q T
LEARNING TO PROGRAM IN VISUAL BASIC
I selection statements 23
nested selection 23
numbers 16
index 31
length 15
processing 31
W
While loop 28
widget 106
Submit button 110 Windows form
subroutine 57 closing 113
O substrings 32 Windows Forms app 100
object 18
syntax 1 write statement 9
operator 7
syntax errors 16 mixing variables 12
operators
WriteLine 9, 58
augmented 9
writing files 67
Boolean 21
X
P XML documentation block 60
parameter 58, 60
primary key 81
printing 10
procedure 57
Properties window 101
pseudocode 118
128
Visual Basic >>
Learning to Program in