introduction to 1lwc1/files/files/s3_cl/vb/vb...introduction to visual basic - book 1 4 chapter 1...

48
Introduction to Copyright © HKTA Tang Hin Memorial Secondary School 2012 A revised course with - Concise concepts - Hands on class work - Plenty of examples - Programming exercises 1

Upload: others

Post on 23-Aug-2020

7 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

TextBox1

Introduction to

Copyright © HKTA Tang Hin Memorial Secondary School 2012

A revised course with

- Concise concepts

- Hands on class work

- Plenty of examples

- Programming exercises

1

Page 2: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

2

Contents

Chapter 1 Ideas of Programming ............................................................................................ 4

1.1 What is a program? ................................................................................................ 4

1.2 What is programming? .......................................................................................... 4

1.3 What is a programming language? ........................................................................ 5

1.4 Compilers ............................................................................................................... 5

1.5 Names of some programming languages .............................................................. 6

Chapter 2 Visual Basic 2010 Express ...................................................................................... 8

2.1 Download Visual Basic 2010 Express ..................................................................... 8

2.2 Register Visual Basic 2010 Express within 30 days ................................................ 8

2.3 Your first project .................................................................................................... 9

2.3.1 Create and save a new project .................................................................. 9

2.3.2 Introduction to Visual Basic 2010 IDE ...................................................... 11

2.3.3 Adding controls and code ........................................................................ 12

2.3.4 Open an existing project .......................................................................... 13

2.4 Structure of a Visual Basic 2010 project .............................................................. 14

2.5 Microsoft Developer Network (MSDN) ............................................................... 14

Chapter 3 Working with Controls ......................................................................................... 15

3.1 Introduction to GUI programming in Visual Basic ............................................... 15

3.2 Controls ................................................................................................................ 15

3.3 Properties window ............................................................................................... 16

3.4 Changing properties at runtime ........................................................................... 17

3.5 Assigning values to properties ............................................................................. 18

3.6 Add a comment to your source code .................................................................. 19

Exercise 3 ......................................................................................................................... 19

Chapter 4 Events and Methods ............................................................................................ 20

4.1 Introduction to events and methods ................................................................... 20

4.2 Events ................................................................................................................... 20

4.2.1 Introduction to event procedures ........................................................... 20

4.2.2 Adding an event procedure in Visual Basic .............................................. 21

4.2.3 Names and types of events ...................................................................... 22

4.2.4 The structure of an event procedure ....................................................... 23

4.2.5 TextChanged events ................................................................................. 23

Page 3: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

3

4.3 Methods ............................................................................................................... 24

Exercise 4 ......................................................................................................................... 26

Chapter 5 Variables, Input and Output ................................................................................ 27

5.1 Variables............................................................................................................... 27

5.1.1 Declaring variables with Dim statement .................................................. 27

5.1.2 Keywords and names of variables ........................................................... 28

5.1.3 Giving values to variables in the Dim statement ..................................... 28

5.1.4 Declaring several variables in a single line .............................................. 28

5.1.5 Using variables to store values ................................................................ 29

5.1.6 Scope of variables .................................................................................... 30

5.2 Introduction to InputBox and MsgBox ................................................................ 32

5.2.1 InputBox ................................................................................................... 32

5.2.2 MsgBox ..................................................................................................... 33

5.2.3 Miscellaneous examples .......................................................................... 34

Exercise 5 ......................................................................................................................... 34

Chapter 6 Operators and Expressions .................................................................................. 35

6.1 Arithmetic Operators ........................................................................................... 35

6.2 Parentheses (singular: parenthesis) .................................................................... 36

6.3 Concatenation Operators .................................................................................... 36

6.4 Operator Precedence ........................................................................................... 37

6.5 Increment and Decrement ................................................................................... 38

6.6 Val function .......................................................................................................... 38

6.7 Mathematical Constants and Functions .............................................................. 39

6.8 Miscellaneous Examples ...................................................................................... 40

Exercise 6 ......................................................................................................................... 41

Chapter 7 Flow Control (1) ................................................................................................... 42

7.1 Decision Making ................................................................................................... 42

7.2 Relational Operators ............................................................................................ 42

7.3 If...Then...Else Statement ..................................................................................... 43

7.4 Multiple conditions with keyword ElseIf ............................................................. 44

7.5 Official Syntax of If...Then...Else Statement ........................................................ 46

Exercise 7 ......................................................................................................................... 47

Alphabetical Index ................................................................................................................... 48

Page 4: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Introduction to Visual Basic - Book 1

4

Chapter 1 Ideas of Programming

1.1 What is a program?

A program is a set of instructions that tells a computer how to do a task. With programs,

computers can perform tasks __________________ and ___________________.

1.2 What is programming?

Programming is the process of designing, writing, testing and debugging (remove mistakes)

a program. To write a program, you need to know and solve the problem first. After

solving the problem, you tell the computer how to solve the problem using a programming

language.

For example, if you need to write a program that calculates percentage changes, you

should first solve the problem by obtaining the formula of percentage change. After that,

you will write a program to do the task. In this course, Visual Basic.net the programming

language you use.

To get the idea of how to

create a computer

program, you may refer to

the diagram at the right.

(Note: after having a

finished program, you can

do an evaluation to look

for possible

improvements.)

Define the Problem

Solve the Problem

Write a Program

Testing and Debugging

Evaluation

Page 5: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Chapter 1 Ideas of Programming

5

Trivia: The earliest programmers write programs in machine code, because programming languages are not available yet!

1.3 What is a programming language?

In computers, instructions are stored in machine code, that each instruction (e.g. ADD,

SUBTRACT, MULTIPLY, etc.) is given a unique number. Computers can understand machine

code only!

However, machine codes are very difficult to be understood by human. Therefore,

programming languages, that are understandable by human,

are created to bridge the gap.

A programming language consists of a specification and an

implementation. The specification provides a definition of the programming language, and

programmers write programs according to the specification.

And the implementation is a translator: something that converts the program from the

programming language into machine code.

1.4 Compilers

Compilers are a type of translator that converts source code into an object program. The

object program is stored in an executable file (.exe), which can be executed directly in a

computer. The usage of a compiler can be summarized in the diagram below:

Source Code (written in programming

language)

Compiler Object

Program (written in machine code)

Execution

Page 6: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Introduction to Visual Basic - Book 1

6

1.5 Names of some programming languages

Here are the names and characteristics of some programming languages. You are only

required to remember the names of these programming languages.

(The characteristics and example are provided for reference only.)

Programming language Characteristics

BASIC

(Beginner’s All-purpose

Symbolic Instruction Code)

BASIC is designed to be easy-to-learn. It gradually evolved

into modern programming languages, firstly QuickBasic, and

then Visual Basic.

Example program Output

10 FOR I=1 TO 5

20 PRINT I*I

30 NEXT I

1

4

9

16

25

Logo Logo is known for drawing attractive graphics. It was used to

teach programming in schools.

Example program Output

REPEAT 5 [FD 100 RT 144]

(Note: FD = forward, RT = right turn.

Only the star is drawn. The triangle is

the cursor, pointing upwards.)

Pascal Pascal was designed mainly to teach good programming

style. Pascal is being taught in the HKDSE ICT syllabus. Some

modern programs are also written in Pascal.

Example program Output

program example1;

var i : integer;

begin

for i := 1 to 5 do

begin

WriteLn(i*i);

end;

end.

1

4

9

16

25

Page 7: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Chapter 1 Ideas of Programming

7

Programming language Characteristics

C++ C++ is one of the most popular programming language

(much more popular that Pascal). If you want to be a good

programmer, C++ is a programming language that you must

learn.

C language, the predecessor of C++, is also widely used

today.

Example program Output

#include <iostream>

int main(int argc,char* argv[])

{

for (int i=1; i<=5; i++) {

cout << i*i << endl;

}

}

1

4

9

16

25

JavaScript JavaScript is the programming language available in a web

browser, allowing dynamic user interaction in a web site.

New web technologies, i.e. Ajax and HTML5 rely on

JavaScript as the programming language.

PHP PHP is one of the most popular programming languages for

a web server. With PHP you can dynamically generate web

contents, and many other things, depending on user input.

PHP is used in the http://www.tanghin.edu.hk

Visual Basic.net Visual Basic.net is the programming language you are going

to learn in this book. Visual Basic is the easiest programming

language to learn if you want to program in Graphical User

Interface (GUI).

Page 8: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Introduction to Visual Basic - Book 1

8

Chapter 2 Visual Basic 2010 Express

2.1 Download Visual Basic 2010 Express

To download Visual Basic 2010 Express, you should search of “Visual Basic 2010” in Google.

After that, click the second link (“Visual Basic 2010 Express | Microsoft Visual Studio”)

(Note: in the PDF version of the file, you can simply click the link above.)

Click “Install Now” to download the file “vb_web.exe”, and then follow the instructions.

2.2 Register Visual Basic 2010 Express within 30 days

You must register your copy

to use Visual Basic 2010

Express after the 30 days. For

more information, press

“Help” “Register Product”

in the menu bar, and then

follow the instructions (see

the figure) to get a

registration key.

Page 9: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Chapter 2 Visual Basic 2010 Express

9

Use only common characters (letters, digits, space, ‘.’ and ‘_’) in the project name. Otherwise, you may not be able to compile your program.

2.3 Your first project

2.3.1 Create and save a new project

The first thing you do in Visual Basic is to start a new project. Follow the instructions

below:

1. Click “New Project”.

2. Choose “Windows

Forms Application”.

3. Give the project a name.

4. Press “Okay”.

Page 10: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Introduction to Visual Basic - Book 1

10

Once you have created a project, you should immediately save the project by pressing “Save All”.

In Tang Hin, do not save the project to C drive. When you switch off the computer, everything in C drive will be deleted.

5. Choose “File” “Save

All” in the menu bar.

(Always save the project

first!)

6. Choose a location for

your project.

(The location is only asked

when you press “Save All” for

the first time.)

Page 11: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Chapter 2 Visual Basic 2010 Express

11

2.3.2 Introduction to Visual Basic 2010 IDE

After you create and save a project, you can see the screen like the figure below. This is

known as an Integrated Development Environment, or simply IDE. An IDE contains

different kinds of tools that help you to write programs, like source code editor, form

designer, compiler, debugger and many other tools.

If some of the above features is/are missing, you can click the buttons to show them.

(See the figure above for the icons’ position on the screen.)

Toolbox

Solution Explorer

Properties Window

Form Designer

Page 12: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Introduction to Visual Basic - Book 1

12

You MUST type all the words, including the punctuations, in exactly the same way. Extra spaces is NOT allowed between letters and digits.

2.3.3 Adding controls and code

Now we add some controls and code to the program. For your first program, follow the

steps below:

1. Find “Button” in Toolbox,

and then put it into the

form.

2. Adjust the size of the form

and the button.

3. Change the property “Text”

of the button to “Go.”

4. Double click the button

“Go”, you should see

that some VB codes

appear.

5. Insert a line of code

shown in the right.

6. Run the program. (Press

the green arrow or F5 in

your keyboard.)

When you run the program, click the button “Go”

(i.e. Button1), and then a message box containing

the message “Hello” will be shown.

Points to note:

The words “Public Class Form1”, “Private Sub …”, “End Sub” and “End Class” must be

put in this order. It is too difficult to understand their meanings at this stage.

The button is known as “Button1” because you can find the words “Button1” in its

“(Name)” property. You can rename the button by setting this property.

Public Class Form1

Private Sub Button1_Click(...) Handles Button1.Click

MsgBox("Hello")

End Sub

End Class

Insert this line of code

Page 13: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Chapter 2 Visual Basic 2010 Express

13

2.3.4 Open an existing project

After you save a project, you can open the project later. To open the project, please follow

the instructions here:

1. Click “Open Project”

2. Browse into the folder

and you should see a

“Solution File”. Choose

this file and then click

“Open”.

Alternatively, you can simply use Windows Explorer to find the same Solution File.

However, if you have installed two different versions of Visual Basic, this method may not

work well.

Page 14: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Introduction to Visual Basic - Book 1

14

2.4 Structure of a Visual Basic 2010 project

The screenshot below illustrates the folder structure of a Visual Basic project. When you

need to copy the project to another computer, or submit your homework or test in eClass,

remember to ZIP all the contents of the base folder!

Also, when you create a Form in Visual Basic IDE, three files are created. You can open

the .Designer.vb file with a text editor, in order to see the source code. However, no

apparent action can be done in the .resx file.

2.5 Microsoft Developer Network (MSDN)

If you have a question, you can go to Microsoft Developer Network (MSDN) to find the

information. For example, if you want to know the meaning of the keyword “Then”, just

Google “then vb msdn” and you will find the information in MSDN.

The base folder (ZIP all contents of this folder when you need to submit your program to eClass.)

Do not ZIP this one!!!

bin: Find the executable file (.exe) here!

My Project: Configuration and other files

obj: Temporary file created when we compile the program. Safe to delete.

The three files related to “Form1.vb”. Do not delete any of them!

Page 15: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Chapter 3 Working with Controls

15

Chapter 3 Working with Controls

3.1 Introduction to GUI programming in Visual Basic

When we create a new program, one of the first things to do is to

create a user interface. The most common type of interface is

called graphical user interface (GUI). You create a GUI program in

Visual Basic by creating a new Windows Form Application.

When you create a new project (see 2.3.1 for details), you see an

empty dialog box, which is known as a form, and also a Toolbox

with a lot of controls (see the figure).

You can add controls by dragging the controls into the form.

When you finish, press F5 (the function button at the top of the

keyboard) to run the program.

3.2 Controls

In Visual Basic, users interact with the program using the controls

in the form. Each control has its own use. Here are the types of

controls we learn in this chapter:

Type of control Functions

TextBox A text box allows users to enter text (input). It

can also be used to display results (output).

Label

A label provides visual cues to users, e.g.

describe the meaning of the text box next to it.

It can also used to display results (output).

Button The program performs some actions when the

user press or click the button.

Forms and controls have properties, events, and methods. Together they make the forms

and controls useful for programmers.

Page 16: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Introduction to Visual Basic - Book 1

16

Put some controls into a form and change their properties. Don’t forget the form!

3.3 Properties window

You can change the appearance of the controls

(and form) by setting their properties in the

properties window (see the figure).

Here is a shortlist of the properties we use in the course:

Property Use

(Name)

(design time only)*

You give a name to the control, and use this

name to refer to the control in your own

source code.

Text† The text on the control, or the title of the

form.

ForeColor The foreground colour (i.e. colour of the

text) inside the control.

BackColor The background colour (i.e. colour of the

empty space) of the control/form.

Left Horizontal position of the object, counted

by the number of pixel relative to the left

side of its parent.

Top Vertical position of the object, counted by

the number of pixel relative to the top side

of its parent.

Visible Whether the control is visible to the user.

Enabled Whether users can interact with the control.

If not, the control is usually dimmed.

TextAlign

(design time only)

The horizontal and vertical alignment of the

text inside the control.

Font

(design time only)

The font used by the text in the control.

* Even though we say “design time only”, it is possible to change these properties during runtime. However,

how to changing these properties in runtime is too difficult to be included in this course.

† For labels and buttons, there is a subtle difference with the Text property. Search “UseMnemonic” in

Google for details.

Page 17: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Chapter 3 Working with Controls

17

In Visual Basic, the word “Color” is spelt in American English (no “U”).

3.4 Changing properties at runtime

Properties of controls can be changed using the properties window (during design time) or

by Visual Basic code (during runtime).

Here is an example program that changes some

properties of the form and the controls. To enter

the code into Visual Basic IDE, you can double

click Button1 in design view. Can you guess what will happen after Button1 is clicked?

(Note: “Me” refers to the form.)

Example 3.4.1 Changing properties at runtime

Public Class Form1

Private Sub Button1_Click(sender As System.Object, e As

System.EventArgs) Handles Button1.Click

Me.Text = "Button1 Pressed!"

Me.BackColor = Color.Pink

Label1.Text = "Name"

Label1.BackColor = Color.Green

Label1.ForeColor = Color.Yellow

Label1.Top = 80

TextBox1.Text = "Sarah"

TextBox1.BackColor = Color.Red

TextBox1.Enabled = False

TextBox1.Left = 20

Button1.Visible = False

End Sub

End Class

Page 18: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Introduction to Visual Basic - Book 1

18

3.5 Assigning values to properties

Different properties accept values of different data types. Please see the table below:

Name of property Data type Example

Text String Me.Text = "Title of the Window"

ForeColor Color* Label1.ForeColor = Color.Red

BackColor Color TextBox1.BackColor = Color.Green

Left Integer Me.Left = 100

Top Integer Label1.Top = 234

Visible Boolean (True/False) Button1.Visible = True

Enabled Boolean (True/False) TextBox1.Enabled = False

Note: A string is enclosed in a pair of double quotes (""). If you want to have the "

character inside a string, type that character twice. E.g. "She said ""hello"" to

me."

Class Work 3.5

Write down a Visual Basic statement for each of the following operation.

Operation VB statement

Change the background colour of the

TextBox1 to blue.

Make Button2 disappear.

Set the title of the form to

“New Document”

Change the colour of the text in Label1

to yellow.

Move Button1 that Button1 is vertically

aligned with Button2. (Assume that the

heights of both buttons are the same.)

* For a list of the colours available, search for “System.Drawing.Color” in Google.

Page 19: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Chapter 3 Working with Controls

19

3.6 Add a comment to your source code

After you write some source code, you should also write some comments in your program.

Comments in Visual Basic start with a single quote ('), which is followed by any text you

want. Please see the following example:

Example 3.6.1 Comments

Public Class Form1

' This is a comment that occupy for a whole line

Private Sub Button1_Click(...) Handles Button1.Click

TextBox1.Text = "Sarah" ' This is another comment

TextBox1.BackColor = Color.Red

End Sub

End Class

It is easy to understand the program if there are only a few lines of source code. However,

after writing 100 or even 1000 lines of source code, it will very difficult to understand the

logic behind the source code without reading the comments.

Exercise 3

1. Write a program with two controls: Button1 and TextBox1.

When Button1 is clicked, the following things should happen:

(a) TextBox1 is disabled,

(b) The background colour of TextBox1 becomes yellow,

(c) Button1 becomes visible, and

(d) The form’s background colour becomes white.

2. Identify the mistakes in the following source code. There is one mistake in each line.

(Note: There are no mistakes with the words Me, Label1, Button1 and TextBox1.)

Me.Title = "Title of the form"

Label1.BackColor = Colour.Green

Button1.Visible = Ture

TextBox1.Enable = False

TextBox1.Text = Very good!

Page 20: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Introduction to Visual Basic - Book 1

20

Chapter 4 Events and Methods

4.1 Introduction to events and methods

Besides working with properties, you need to use events and methods to communicate

with the controls.

4.2 Events

When the user does some action in the form (e.g. click a button), an event is raised or

triggered. You can write a procedure in your Visual Basic program to handle the event, and

that procedure will be executed every time the user does the same action.

4.2.1 Introduction to event procedures

In the previous chapters, you have seen something like the following excerpt:

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

[Add your code here]

End Sub

The excerpt above is an event procedure, i.e. a procedure that handles an event. When

Button1 is clicked, the event Button1.Click is handled by the procedure Button1_Click, and

the code inside is executed.

Some Action (e.g. the user clicks a button)

Raise an Event

Execute an Event Procedure

The user clicks Button1

Raise the event Button1.Click

Execute procedure Button1_Click

Page 21: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Chapter 4 Events and Methods

21

4.2.2 Adding an event procedure in Visual Basic

Method1 Double click the needed item in a form

A quick method to add an event procedure is to double click the related control in the

form designer. The following events will be created:

Type of control / form Event When the event is raised

Form Load When the form is displayed for the first time

Button Click When the Button is clicked

Label Click When the Label is clicked

TextBox TextChanged When the Text property of the TextBox is changed

Method2 Select the event in the source code window

If you want to create other event procedures, then you need to select the list in the source

code view. First, select the control at the left, and then select the event at the right.

Note: To add events to Form1, select “(Form1 Events)” instead of “Form1”.

Page 22: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Introduction to Visual Basic - Book 1

22

4.2.3 Names and types of events

The most commonly used events of are Load and Click. Here is a shortlist of events we use

in this course:

Name of event When the event is raised

Load Before a form is displayed the first time. In most cases, this is when

the program starts running.

Click When the user clicks a form or control (e.g. Button).

DoubleClick* When the user double clicks certain kinds of controls (e.g. Form,

Label, TextBox). Note: A Button does not raise the DoubleClick event.

TextChanged† When the content of the Text property is changed (either by user

input or by Visual Basic.net code.)

MouseEnter When the mouse enter a form or control

MouseLeave When the mouse leaves a form or control

We identify an event by connecting the name of the control and the name of the event

using a dot symbol, e.g. Button1.Click, TextBox2.TextChanged, etc.

Events related to the form are prefixed by “Me” or “MyBase”, e.g. MyBase.Load‡,

Me.Click, Me.MouseEnter, etc.

Class Work 4.2.3

Identify the events raised by the actions below:

Action Event raised

Execute a program

Click Button1

The text inside TextBox1 is changed

The mouse cursor leaves Label3

* Only some types of controls raises DoubleClick events. For details, see

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.doubleclick.aspx

† TextChanged events are also raised when the form is created, before the Load event is raised. Open

Form1.designer.vb in a text editor to see the reason behind. Careless implementation of TextChanged events

always causes runtime errors.

‡ It is okay to use either Me.Load or MyBase.Load

Page 23: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Chapter 4 Events and Methods

23

4.2.4 The structure of an event procedure

You can look at the following example for the structure of an event procedure.

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

[Add your code here]

End Sub

Now the code is explained part by part:

Part Meaning

Private Sub Declare a procedure

Button1_Click The name of the procedure. The default is the name of the

event, with “.” changed to “_”. You can change this name by

yourself.

(sender As System.Object,

e As System.EventArgs)

Currently unimportant. Usually abbreviated as (…) in this

book

Handles Button1.Click The event or events to handle. Change this to something like

“Handles Button1.Click, Button2.Click, Button3.Click”

to handle multiple events in the same procedure

End Sub Marks the end of the event procedure

4.2.5 TextChanged events

A correct implementation of TextChanged events is provided here without explanation.

You should read this section again after you finish Chapter 7.

Public Class Form1

Dim loaded As Boolean = False

Private Sub Form1_Load(...) Handles MyBase.Load

loaded = True

End Sub

Private Sub TextBox1_TextChanged(...) Handles TextBox1.TextChanged

If Not loaded Then Exit Sub

' Add your code below

End Sub

Private Sub TextBox2_TextChanged(...) Handles TextBox2.TextChanged

If Not loaded Then Exit Sub

' Add your code below

End Sub

End Class

Page 24: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Introduction to Visual Basic - Book 1

24

4.3 Methods

A method is a procedure that exists inside the control. You invoke methods to do

something with a control. Sometimes it is possible to the same thing using either

properties or methods. For example, the statements “Form2.Visible = True” (setting

a property) and “Form2.Show()” (invoke a method) do the same thing.

Here is the list of methods we learn in the course:

Control Method Meaning Example

[All] Hide Hide a control/form. Form2.Hide()

[All] Show Show a control/form. Form2.Show()

Form ShowDialog Show a form as a modal dialog box.

(A modal form must be closed or hidden before you can

continue working with the rest of the application.)

Form2.ShowDialog()

Form Close Close a form. The program ends when

the startup form (usually Form1) is

closed.

Me.Close()

TextBox AppendText Add some text to the end of the

current text in the text box.

TextBox1.AppendText("Hello")

TextBox Paste Paste some text to the

cursor/selection of the text box.

TextBox1.Paste("Hello")

Example 4.3.1 AppendText and Paste methods Public Class Form1

Private Sub ButtonAppendText_Click(...) Handles ButtonAppendText.Click

TextBox2.AppendText(TextBox1.Text)

End Sub

Private Sub ButtonPaste_Click(...) Handles ButtonPaste.Click

TextBox2.Paste(TextBox1.Text)

End Sub

End Class

Note: When you run the example, you should note

the way computer join strings. No extra spaces are

added by the computer!

Page 25: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Chapter 4 Events and Methods

25

A hidden form is NOT closed. If the startup form is hidden, then the program may not end properly! (If it happens, you can terminate the program in the Task Manager.)

Example 4.3.2 Multiple forms (try the buttons and text box yourself)

Form1.vb Public Class Form1

Private Sub ButtonShow_Click(...) Handles ButtonShow.Click

Form2.Show()

End Sub

Private Sub ButtonShowDialog_Click(...) Handles ButtonShowDialog.Click

' Note: a runtime error will occur if Form2 is already visible

Form2.ShowDialog()

End Sub

End Class

Form2.vb Public Class Form2

Private Sub ButtonClose_Click(...) Handles ButtonClose.Click

Me.Close()

End Sub

End Class

Class Work 4.3

Write down Visual Basic statements for each of the following operation.

Operation VB statement(s)

Append “Hello!” to TextBox1.

Show Form3 as a modal dialog box.

Show Form2 as a modal dialog box. The

current form is hidden until Form2 is

closed.

Page 26: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Introduction to Visual Basic - Book 1

26

Make sure your source code is inputted in the correct events! Check for spelling mistakes!

Exercise 4

1. Write a program with two controls: Button1 and Button2.

When Button1 is clicked, the following things should happen:

(a) Button1 is disabled,

(b) The text in Button1 becomes

“Disabled!!!”,

(c) Button2 becomes visible, and

(d) The form’s background colour becomes pink.

And when Button2 is clicked, the following things should happen:

(a) Button1 is enabled,

(b) The text in Button1 goes back to “Button1”,

(c) Button2 becomes invisible, and

(d) The form’s background colour becomes yellow.

2. Write a program to tease the user with a button labelled “Click Me”. In this program,

the user cannot press a button because the following happens:

When the mouse is inside the form, the button is disabled. When the mouse is

outside the form, the button is enabled again. To verify that the tease works, you

should also add a Click event for the button, which changes the text of the button to

“Clicked”.

(Note: I would like to replace the words “form” by “button” in the question, but the

program created that way does not work properly.)

Page 27: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Chapter 5 Variables, Input and Output

27

Chapter 5 Variables, Input and Output

5.1 Variables

In Visual Basic, you use variables to store values. Variables have a name and a data type.

5.1.1 Declaring variables with Dim statement

Before you use a variable, you should tell Visual Basic in advance, using the Dim statement:

Dim variablename [As type]

The data type of the variable can be one of the following:

Data type Description

Integer Integer (between -2,147,483,648 through 2,147,483,647)

Single Single-precision floating-point (about 7 significant figures).

Double Double-precision floating-point (about 16 significant figures).

Boolean True or False

String Text (holds your name, ID card number, etc…)

Example 5.1.1 Dim statements

Dim score As Integer

Dim weight As Double

Dim finished As Boolean

Dim name As String

Class Work 5.1.1

Determine the correct data type(s) for the following data, and write down a Dim

statement, where the name of the variable is the underlined word.

Description of data Data type Dim statement

The height of a student (in cm).

The marks of a test.

The academic grade of a student.

The age of your father.

Whether you are wealthy.

Page 28: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Introduction to Visual Basic - Book 1

28

Visual Basic is not case sensitive,

e.g. ScOrE and score are the same name in Visual Basic .

5.1.2 Keywords and names of variables

Some words have special meanings in Visual Basic, such as Dim, As, Integer, Double,

Boolean, and String. These words are known as keywords, or reserved keywords. The

list of keywords in Visual Basic 2010 can be found in

http://msdn.microsoft.com/en-us/library/dd409611(VS.100).aspx

The name of a variable cannot be any of the

reserved keywords. In addition, it must obey the

following rules:

It must begin with an alphabetic character or an underscore (_).

It must only contain alphabetic characters, decimal digits, and underscores.

It must contain at least one alphabetic character or decimal digit.

It must not be more than 1023 characters long.

5.1.3 Giving values to variables in the Dim statement

We can assign a value to a variable in the same Dim statement. This is a good practice in

programming because it eliminates potential mistakes.

Example 5.1.2 Dim statements with initial values

Dim score As Integer = 0

Dim weight As Double = 129.3

Dim finished As Boolean = False

Dim name As String = "Chan Tai Man"

5.1.4 Declaring several variables in a single line

We can declare several variables in a single Dim statement. However, in Visual Basic, we

cannot assign a value to these variables at the same time.

Example 5.1.3 Dim statements with several variables in one line

Dim a, b, c As Single, x, y As Double, i As Integer

' a, b, and c are all Single; x and y are both Double

Page 29: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Chapter 5 Variables, Input and Output

29

5.1.5 Using variables to store values

We can assign a value to a variable with the equal sign “=”. Once a new value is stored in

the variable, the old value is forgotten. See the example below:

Example 5.1.4 Use of variables

Dim x, y As Integer

x = 5 ' x is set to 5

y = 3 ' y is set to 3

x = 2 ' x becomes, y is unchanged

y = x + 2 ' y becomes (x+2)=(2+2)=4, x is unchanged

x = y + 3 ' x becomes (y+3)=(4+3)=7, y is unchanged

Class Work 5.1.2

With reference to the programs below, write down the values of the variables after the

execution of each of the statements.

Program Value of a Value of b Value of t

Dim t As Integer

Dim a As Integer = 2 2

Dim b As Integer = 6 2 6

t = a

a = b

b = t

Program Value of p Value of q

Dim p As Double = 3

Dim q As Double = 4.5

q = p - 0.5

p = 2

p = (p + q) / 2

q = (p - q) / 2

Page 30: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Introduction to Visual Basic - Book 1

30

5.1.6 Scope of variables

The variable can be declared inside the Class or inside a Sub procedure. The variable is

only effective inside the Class or Sub structure. Once the given structure finishes

execution, the variable is deleted and its value is forgotten. Here is an example:

Variable

inside Class

Public Class Form1

Dim x As Integer = 20

Private Sub Button1_Click(...) Handles Button1.Click

x = x + 10 'increase x by 10

Label1.Text = x

End Sub

End Class

After execution of Sub Button1_Click,

the new value of x is remembered.

Therefore, x is increased by 10 every time we click the button.

Variable

inside Sub

Public Class Form1

Private Sub Button1_Click(...) Handles Button1.Click

Dim x As Integer = 20

x = x + 10 'increase x by 10

Label1.Text = x

End Sub

End Class

After execution of Sub Button1_Click,

the new value of x is forgotten

because x is declared inside Sub Button1_Click.

Therefore, x becomes 20 + 10 = 30 every time we click the button.

If a variable exists both inside and outside the sub, the variable inside the sub is used.

You may also declare variable inside an If…Then…Else statement (see chapter 7) or other

statement blocks. Like the case with Sub procedure, those variables will be forgotten after

the statement block finish execution.

Page 31: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Chapter 5 Variables, Input and Output

31

Class Work 5.1.3

The following is a program with label Label1 and buttons Button1, Button2 and Button3.

Public Class Form1

Dim x As Integer = 5

Private Sub Button1_Click(...) Handles Button1.Click

Dim x As Integer

x = 8

Label1.Text = x

End Sub

Private Sub Button2_Click(...) Handles Button2.Click

Label1.Text = x

End Sub

Private Sub Button3_Click(...) Handles Button3.Click

x = 12

Label1.Text = x

End Sub

End Class

Now the program is run and the buttons is pressed step by step as follows. Determine the

value of Label1.Text after each step:

Step Action Value of Label1.Text

1 Run the program.

2 Click Button1.

3 Click Button2.

4 Click Button3.

5 Click Button1.

6 Click Button2.

Page 32: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Introduction to Visual Basic - Book 1

32

Without the Val function, a runtime error occurs if the user press “Cancel” in the InputBox.

5.2 Introduction to InputBox and MsgBox

Besides using labels and textboxes, we can use InputBox and MsgBox to handle input and

output. In this part, we only deal with the simplest way to handle input and output. The

details will be discussed in the second term.

5.2.1 InputBox

To use an InputBox to input a string, we use the following statement:

variablename = InputBox("message")

If you want to input a number, you should use

the Val function to convert the string into a

number, i.e.

variablename = Val(InputBox("message"))

Here is an example asking for your name using InputBox:*

Example 5.2.1 InputBox

Dim s As String

s = InputBox("What is your name?")

* Starting from this chapter, there may be no Button1 and Button1.Click in the examples. You should create

the button Button1 and the event Button1.Click yourself, and then input the code inside Button1.Click.

Page 33: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Chapter 5 Variables, Input and Output

33

If you want to check the value of a variable, you can add a MsgBox statement in your source code..

5.2.2 MsgBox

To use MsgBox to display a message, we use the following statement:

MsgBox("message")

Here is an example using MsgBox:

Example 5.2.2 MsgBox

MsgBox("This is a wonderful message!")

If you want to display a message with more than one line, see the example below. The “&”

character join strings together, and vbCrLf is similar to the “Enter” key in the text editor.

(Note: the example below should be typed in a single line.)

Example 5.2.3 Multiline MsgBox

MsgBox("You Won!!!" & vbCrLf & vbCrLf & "You rolled a 6"

& vbCrLf & "and the computer rolled a 5!")

Page 34: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Introduction to Visual Basic - Book 1

34

5.2.3 Miscellaneous examples

Example 5.2.4 Calculate the product of two numbers

Dim x, y, product As Double

x = Val(InputBox("Input the first number."))

y = Val(InputBox("Input the second number."))

product = x * y

MsgBox("Their product is: " & product)

Exercise 5

1. Rewrite Example 5.2.4 into a program that does not use InputBox and MsgBox. Use

text boxes and labels instead.

2. Write a program that uses InputBox to input two numbers when the form is loaded.

The numbers are stored into two variables. Now the user can press one of the four

buttons, that each of the buttons does a basic arithmetic operation (i.e. +, –, × or ÷)*

on the two numbers, and then display the results using a MsgBox.

Note: Do not use any text boxes or labels in this question.

3. Suggest a name and a data type of the variable for each of the following.

Meaning of variable Name of variable Data type

The name of a student.

The class of a student.

The date of the computer examination.

* The “×” symbol can be typed by pressing Alt-0215. It means holding the Alt key and typing 0215 in the

numeric keypad while the Alt key is held. Similarly, “÷” can by typed by pressing Alt-0247.

Page 35: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Chapter 6 Operators and Expressions

35

Chapter 6 Operators and Expressions

You can enter expressions in Visual Basic to do calculations. The expressions in Visual Basic

are similar to what you type in your calculator, Casio fx-50FH.

Operators in Visual Basic can be classified into arithmetic operators, (string) concatenation

operators, relational operators and logical operators. The first two types are discussed in

this chapter, while the others are discussed in the next chapter.

6.1 Arithmetic Operators

Here is a list of the arithmetic operators in Visual Basic 2010. You should get yourself

familiar with the operators “\” and “Mod” before examinations.

Operator Meaning Example Result

+ Addition 3+8 11

- Subtraction 10-15 -5

-(unary) Negation -2 -2

* Multiplication 3*8 24

/ Division (floating point) 14/4 3.5

\ Integer division

Note: Avoid decimals. They are rounded off in a strange way.

14\4

31.25\4.5

3

7

Mod Find the remainder of division

(decimals are okay)

10 Mod 4

31.25 Mod 4.5

2

4.25

^ Exponentiation 3^4 81

Class Work 6.1

Evaluate the following expressions:

VB expression Result VB expression Result

3 + 6 3 * 6

3 - 6 2 ^ 5

15 / 7 5 ^ 2

15 \ 6 3 ^ (5 - 2)

15 Mod 6 5 ^ (-2)

Page 36: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Introduction to Visual Basic - Book 1

36

Do not forget to add a pair of

parentheses. E.g.

should be

“a/(b+c)” but not “a/b+c”.

Adding a number and a string by the “+” sign, e.g., "4" + 2 , will produce a runtime error!

6.2 Parentheses (singular: parenthesis)

Parentheses (or brackets) are used to force some

parts of an expression to be evaluated before

others.

Class Work 6.2

Convert the following expressions into Visual Basic code:

Mathematical expression VB statement

a = b + c

(

)

6.3 Concatenation Operators

Concatenation is the operation joining two strings together. The strings are simply joined

together into a single string. There are two concatenation operators in Visual Basic: “+”

and “&”. The “&” operators is preferred because it is defined for strings only.

Example: "Con" & "caten" & "ation"

evaluates to "concatenation"

Note: No space is added to the strings.

Page 37: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Chapter 6 Operators and Expressions

37

6.4 Operator Precedence

Similar to Mathematics expressions, the evaluation of expressions in Visual Basic is

ordered by its operator precedence. Here is the list*:

(Note: operators that are introduced in the future are also listed here.)

Low

est ←

− −

− −

− −

− −

→ H

igh

est 11 Exponentiation ^

10 Unary identity and negation† + –

9 Multiplication and floating-point division * /

8 Integer division \

7 Modulus arithmetic Mod

6 Addition and subtraction + –

5 String concatenation &

4 Relational/comparison operators = <> < <= > >=

3 Negation Not

2 Conjunction And

1 Inclusive disjunction Or

For operators in the same order of precedence, the calculations are done left-to-right.

Class Work 6.4

Evaluate the following expressions:

VB expression Result

"con" & "cent" & "rated"

4 * 3 & 5 * 2

9 - 25 / 2 * 3

9 - 25 \ 2 * 3

-35 Mod 3 ^ 3

* The operator precedence table above is only valid of Visual Basic. It is different for Excel.

† A unary operator has only one expression next to it. e.g. the – sign in – .

Page 38: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Introduction to Visual Basic - Book 1

38

6.5 Increment and Decrement

One of the most common operations in a program is to increase and decrease the value of

a variable. See the following example for an idea.

' Assigns the value 10 to the variable.

applesSold = 10

' The following statement increments the variable.

applesSold = applesSold + 1

' The variable now holds the value 11.

In the previous example, the statement applesSold = applesSold + 1 increase the

value of the variable applesSold by 1. You may also write applesSold += 1 instead.

In the example, += is an assignment operator, which add a certain value to a variable.

-=, *=, /=, \=, ^= and &= are having similar meanings.

Class Work 6.5

Express the following actions into Visual Basic code:

Action VB statement

Increase x by 100

Decrease y by 5

Multiple product by -3

Add "sugar" to the end of the str1

Move the form downwards by 3 pixels

Move the form to the left by 20 pixels

6.6 Val function

In Chapter 5, you have learnt to use the Val function to convert strings into numbers. We

use the Val function in either of the following ways:

variablename = Val(InputBox("message"))

variablename = Val(TextBox1.Text)

We call Val a function because it returns a value that can be assigned to a variable.

Similarly, InputBox is also a function.

Page 39: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Chapter 6 Operators and Expressions

39

6.7 Mathematical Constants and Functions

Here is a list of mathematical constants and functions you will use in Visual Basic:

Function Meaning Example Result

Math.Sqrt Find the square root of a number. Math.Sqrt(4) 2

Math.Abs Absolute value (remove the negative

sign).

Math.Abs(-4) 4

Math.Sign The sign of the number.

1 = positive, 0 = zero, -1 = negative

Math.Sign(-5) -1

Math.PI The value of . Math.PI 3.141592653589793

Int

(or Math.Floor)

Round down to the nearest integer. Int(2.3)

Int(-2.3)

2

-3

Fix

(or Math.Truncate)

Find the integral part of a number. Fix(2.3)

Fix(-2.3)

2

-2

Math.Ceiling Round up to the nearest integer. Math.Ceiling(2.3)

Math.Ceiling(-2.3)

3

-2

Math.Round Round off a number to an integer or a specified number of decimal places. (Note: The behavior of this function is a bit different from what you learn in Mathematics. See MSDN for details.)

Math.Round(12.56)

Math.Round(12.56,1)

13

12.6

Math.Max Returns the larger of two numbers. Math.Max(2, 5) 5

Math.Min Returns the smaller of two numbers. Math.Min(2, 5) 2

Class Work 6.7

Convert the following expressions into Visual Basic code:

Mathematical expression VB statement

( √ )

√ √

Page 40: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Introduction to Visual Basic - Book 1

40

6.8 Miscellaneous Examples

Example 6.8.1 Find the value of a polynomial

Public Class Form1

Private Sub Button1_Click(...) Handles Button1.Click

Dim x As Double = Val(TextBox1.Text)

LabelResult.Text = -x ^ 2 + x + 3

End Sub

End Class

Example 6.8.2 Cycling through 0 to 9

Public Class Form1

Private Sub Button1_Click(...) Handles Button1.Click

Dim n As Integer = Val(Label1.Text)

Label1.Text = (n + 1) Mod 10

End Sub

End Class

Example 6.8.3 Marks Counter

Public Class Form1

Private Sub ButtonPlus20_Click(...) Handles ButtonPlus20.Click

Dim marks As Integer =

Val(LabelMark.Text)

marks = marks + 20

LabelMark.Text = marks

End Sub

Private Sub ButtonMinus10_Click(...) Handles

ButtonMinus10.Click

Dim marks As Integer = Val(LabelMark.Text)

marks = marks - 10

LabelMark.Text = marks

End Sub

End Class

LabelResult

TextBox1 Button1

Button1

Label1

LabelMarks

ButtonPlus20

ButtonMinus10

Page 41: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Chapter 6 Operators and Expressions

41

Exercise 6

1. Write a program to find the value of the n-th triangle number, i.e. .

2. Write a program to calculate the value of in .

3. Rewrite the programs in the previous questions, using InputBox for input and MsgBox

for output.

4. Write a program similar to Example 6.8.2. However, the number in the box should

cycle backwards, i.e. 0, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 9, …

5. Write a program that calculates percentage changes. The program should be able to

find the original value, the new value and the percentage change.

(Hint: What are the formulas?)

6. Write a program with four buttons: up, down, left and right. When you press the

button, the form moves itself by 10 pixels, to the direction indicated by the button.

Page 42: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Introduction to Visual Basic - Book 1

42

Chapter 7 Flow Control (1)

7.1 Decision Making

A logical expression can give Boolean results, i.e. True or False. A computer can use these

results to make decisions.

7.2 Relational Operators

Relational operators (or comparison operators) are the equality signs and inequality signs

in Mathematics. If the equality or the inequality is satisfied, then the result is True,

otherwise the result is False. Here is the list of the relational operators:

Operator Meaning Example Result Opposite

= Equal to 9 = 11

> Greater than 11 > 9

< Less than 11 < 9

>= Greater than or equal to 15 >= 15

<= Less than or equal to 9 <= 15

<> Not equal to 9 <> 9

Class Work 7.2

Convert the following comparison into Visual Basic code:

Comparison VB code

1. Is Peter (PHeight) taller than Mary (MHeight?)

2. Is Linda’s age (LAge) not equal to May’s age (MAge)?

3. The passing mark is 50. Has Gigi (GMark) failed the test?

4. It is free to travel by MTR for a person with height 100 cm

or below. Is it free for Kitty (KHeight) to travel by MTR?

5. Is X an even number?

Page 43: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Chapter 7 Flow Control (1)

43

7.3 If...Then...Else Statement

The If...Then...Else statement conditionally executes a group of statements, depending on

the value of an expression. (See the flowchart below.)

The basic If…Then…Else syntax is listed here.

If condition Then

Statement1

Statement2

...

Else

Statement3

Statement4

...

End If

Sometimes we do not want to execute anything if the condition is false. In this case, we

can skip the keyword Else, i.e.

If condition Then

Statement1

Statement2

...

End If

Page 44: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Introduction to Visual Basic - Book 1

44

marks>=50?

result="Pass"result="Fail"

start

input marks

end

output result

Yes

No

The spelling of the word ElseIf is

E-L-S-E-I-F, not E-L-S-E-L-F!

The following example shows the use of If...Then...Else statements:

Example 7.3.1 Pass or failure

Dim marks As Integer

Dim result As String

marks = Val(InputBox("Enter the marks:"))

If marks >= 50 Then

result = "Pass"

Else

result = "Fail"

End If

MsgBox(result)

In the above example, if the marks is more than or equal to 50,

then the result is “Pass”. Otherwise (i.e. marks less than 50),

the result is “Fail”.

7.4 Multiple conditions with keyword ElseIf

If you want to have more than two outcomes, you can add additional conditions using the

keyword ElseIf (else and if together in one word).

If condition1 Then

Statement1

...

ElseIf condition2 Then

Statement2

...

(more ElseIf conditionals if applicable)

Else

Statement3

...

End If

Page 45: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Chapter 7 Flow Control (1)

45

marks>=80?

start

end

input marks

marks>=70?

output grade

marks>=50?

grade = "A"

grade = "B"

grade = "C"

grade = "D"

No

No

Yes

Yes

Yes

No

To see how the keyword ElseIf works, see the example below:

Example 7.4.1 Grading the results

Dim marks As Integer

Dim grade As String

marks = Val(InputBox("Enter the marks:"))

If marks >= 80 Then

grade = "A"

ElseIf marks >= 70 Then

grade = "B"

ElseIf marks >= 50 Then

grade = "C"

Else

grade = "D"

End If

MsgBox("Your grade is: " & grade)

In this example, the marks are used to determine

the grade. When we check for the second

condition marks >= 70, we already know that

marks >= 80 is false. Therefore, only people

with marks from 70 to 79 get a grade of “B”.

(Note: In this example, the marks are integers.

This is NOT true in Tang Hin, where the marks are correct to 2 decimal places.)

Class Work

With reference to Example 7.4.1, please fill in the table below:

Marks Grade

≥ 80 “A”

“B”

“C”

“D”

Page 46: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Introduction to Visual Basic - Book 1

46

7.5 Official Syntax of If...Then...Else Statement

Here is the official syntax of the If…Then…Else statement. The parts inside [] are optional.

If condition [ Then ]

[ statements ]

[ ElseIf elseifcondition [ Then ]

[ elseifstatements ] ]

[ Else

[ elsestatements ] ]

End If

-or-

If condition Then [ statements ] [ Else [ elsestatements ] ]

When you enter your code into the Visual Basic IDE, it will do the following changes

automatically:

Add the missing keyword “Then”

Change “Else If” into “ElseIf”

Change “EndIf” into “End If”

And here is an example of the single line syntax. The symbol “:” is used to separate

multiple statements. (Note: you may use “:” outside the If…Then…Else statement.)

If A > 10 Then A = A + 1 : B = B + A : C = C + B

Page 47: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Chapter 7 Flow Control (1)

47

Exercise 7

1. Write a program that the user will enter the number . If , output

“A big number!” in a label, otherwise output “A small number!”.

2. Write a program that the user will enter the amount of pocket money he/she spends

per week. Then the program will output a message according to the table below:

Pocket Money ($) Message

0 You didn't spend any money. Are you lying?

>0 and <$100 Below average. What a good student!

>=$100 and <$200 Average.

>$200 Above average. Consider to spend less!

3. BMI Calculator: The Body Mass Index (BMI) is a method to see if you are overweight

or underweight. Your program should receive two inputs: mass (in kg) and height (in

cm). Calculate the BMI by to the formula

. (Be careful with the

unit!!!)

Finally, your program should determine the result according to the following table:

BMI Classification

<18.5 Underweight

18.5 – 23.9 Average

24.0 – 27.9 Overweight

>= 28 Obese

4. Write a program that the user will enter his/her marks in Chinese, English and

Mathematics subjects. Then output the number of subjects that he/she has failed (i.e.

marks less than 50).

Page 48: Introduction to 1lwc1/files/files/s3_cl/vb/vb...Introduction to Visual Basic - Book 1 4 Chapter 1 Ideas of Programming 1.1 What is a program? A program is a set of instructions that

Introduction to Visual Basic - Book 1

48

Alphabetical Index

A AppendText (method)............... 24

As (keyword) ............................. 27

B BackColor (property)................. 16

Boolean (data type) .................. 27

Button (control) ........................ 15

C Class (keyword) ......................... 30

Click (event) .............................. 22

Close (method) ......................... 24

code .......................................... 12

comment................................... 19

compiler ...................................... 5

concatenation ........................... 36

control ................................ 12, 15

D data type ............................. 18, 27

design time ............................... 17

Dim (statement) ........................ 27

Double (data type) .................... 27

DoubleClick (event) ................... 22

E Else (keyword) .......................... 43

ElseIf (keyword) ........................ 44

Enabled (property) .................... 16

event ......................................... 20

event procedure ....................... 20

F False (keyword) ......................... 27

Font (property) ......................... 16

ForeColor (property) ................. 16

form .......................................... 15

form designer ........................... 11

G graphical user interface ............ 15

GUI .... See graphical user interface

H Hide (method) ........................... 24

I IDE ... See Integrated Development

Environment

If (keyword) ............................... 43

If...Then...Else (statement)........ 43

InputBox ................................... 32

Integer (data type) .................... 27

Integrated Development

Environment ........................ 11

K keyword .................................... 28

L Label (control) ........................... 15

Left (property) .......................... 16

Load (event) .............................. 22

M machine code.............................. 5

mathematical functions ............ 39

Me (keyword) ..................... 17, 22

method ..................................... 24

Microsoft Developer Network .. 14

Mod (operator) ......................... 35

MouseEnter (event) .................. 22

MouseLeave (event) ................. 22

MSDN ..... See Microsoft Developer

Network

MsgBox ..................................... 33

MyBase (keyword) .................... 22

N Name (property) ....................... 16

New Project ................................ 9

O object program ........................... 5

Open Project ............................. 13

operator precedence ................ 37

operators .................................. 35

arithmetic operators............ 35

assignment operators .......... 38

concatenation operators ..... 36

relational operators ............. 42

P parentheses .............................. 36

Paste (method) ......................... 24

procedure ................................. 20

program ...................................... 4

programming .............................. 4

programming language ............... 5

BASIC ..................................... 6

C++ ......................................... 7

implementation ..................... 5

JavaScript ............................... 7

Logo ....................................... 6

Pascal ..................................... 6

PHP ........................................ 7

specification .......................... 5

Visual Basic.net ...................... 7

Properties Window ................... 11

property .................................... 16

R reserved keywords.................... 28

runtime ..................................... 17

S Save All ..................................... 10

scope of variables ..................... 30

Show (method) ......................... 24

ShowDialog (method) ............... 24

Single (data type) ...................... 27

Solution Explorer ...................... 11

source code........................... 5, 12

String (data type) ...................... 27

Sub (keyword) ........................... 30

T Text (property) .......................... 16

TextAlign (property) .................. 16

TextChanged (event)........... 22, 23

Then (keyword) ......................... 43

Toolbox ..................................... 11

Top (property) .......................... 16

translator .................................... 5

True (keyword) ......................... 27

U user interface ............................ 15

V Val (function) ...................... 32, 38

variable ..................................... 27

vbCrLf (constant) ...................... 33

Visible (property) ...................... 16

Visual Basic 2010 Express ........... 8

W Windows Form Application .. 9, 15