The words you are searching are inside this book. To get more targeted content, please make full-text search by clicking here.

'Coding' or 'Programming' for you probably mean 'software engineering' - i.e. the science of building software applications. Persons new to the field often confuse knowledge of a specific programming language (e.g. Java, C++, PHP, Python) with the skill of software engineering. A programming language is a simply a means of achieving the goal of building an application. This course can help you design and develop these systems via the .Net technologies.

This course aims to introduce students to the basic concepts of Visual Programming. In this course the students will be involved in the development of graphical user interfaces (GUI), designing complete windows applications, creating and using custom controls, developing web database applications, learning some of the new and more advanced programming concepts introduced in Visual Basic (VB) and the .NET framework. The skills that you gain from this course can be applied at daily life and your tomorrow workplace to solve related programming problems or for setting up your own software-based business.

Discover the best professional documents and content resources in AnyFlip Document Base.
Search
Published by Choo Jun Tan, 2021-01-01 11:31:15

Visual Programming

'Coding' or 'Programming' for you probably mean 'software engineering' - i.e. the science of building software applications. Persons new to the field often confuse knowledge of a specific programming language (e.g. Java, C++, PHP, Python) with the skill of software engineering. A programming language is a simply a means of achieving the goal of building an application. This course can help you design and develop these systems via the .Net technologies.

This course aims to introduce students to the basic concepts of Visual Programming. In this course the students will be involved in the development of graphical user interfaces (GUI), designing complete windows applications, creating and using custom controls, developing web database applications, learning some of the new and more advanced programming concepts introduced in Visual Basic (VB) and the .NET framework. The skills that you gain from this course can be applied at daily life and your tomorrow workplace to solve related programming problems or for setting up your own software-based business.

Keywords: Wawasan Open University

3.7.5 Hands-on: Label and PictureBox controls in Windows Forms App with .Net frame-

work

In this exercise, you will learn to use the label to display information that the user is not allowed to edit

when the program is running. PictureBox is used to display an image. Let’s observe the steps to

create a button control, as the video clip at https://youtu.be/LL7YLF-s01Y

3.7.6 Hands-on: ListBox control in Windows Forms App with .Net framework

In this exercise, you will learn to use the ListBox to display several outputs. Let’s observe the steps to

create a ListBox control, as the video clip at https://youtu.be/_9ATudN_Ics

You will notice that the ListBox does not have a Text property. This is because the word ListBox1
itself is the setting for the Name property. We also place a TextBox, a Button and a Label on the

form. You will notice that the name of the form and the names of the four controls are displayed. Try
to click on one of the names; that object will be selected and its properties displayed in the Properties
window.

Double-click on the Button control to locate the following lines of VB code in the method of ’But-
ton1 Click’.

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

2 ListBox1.Items.Add(TextBox1.Text)
3 Label1.Text = TextBox1.Text + " is added into ListBox!"
4 End Sub

Run the program. Upon the program run, enter some string into the TextBox control before click on
the Button control. You will notice that the entered string is captured in ListBox and a successful
message is showed in the Label control.

Congratulation! You manage to develop a GUI-based VB program. We will explore more VB code in
the subsequence sections. Keep on your reading, and practice the given hands-on exercises!

51

3.7.7 Hands-on: Open a project from the GitHub repository
In this activity, you will use Visual Studio to connect to a GitHub repository for the first time, and

then open a project from it. Visual Studio has integrated source control, and includes Git (https:
//git-scm.com/) support in-the-box. If you haven’t installed the extension of GitHub, you may

obtain it by downloading into your installed Visual Studio for free, as follow.
Downloading extension of Visual Studio.

To learn open (by cloning it locally) a GitHub project, please follow the given steps at URL https://
docs.microsoft.com/en-us/visualstudio/get-started/tutorial-open-project-from-repo?
view=vs-2019. Locate https://github.com/choojun/TCC123-VB.git as the GitHub reposi-

tory location before proceed to clone the source code of this course.
Cloning the remote repository.

52

Locate the remote repository of GitHub repository.

A solution file is available. It will appear in the ’Solutions Explorer’. Choose it, and Visual Studio opens
the solution.
3.7.8 Hands-on: To close the current solution

i. Click File on the menu bar.
ii. Click Close Solution.
Visual Studio stores your program in a group of files called a ’project’. The project file has an extension
of vbproj (.vbproj). There is another file with a sln extension (.sln). The sln file is a solution file that
contains one or more projects. Solution files are used to manage multiple related projects.
Suppose that sample program used in this course has a single project for each solution, so opening
the project file (.vbproj) has the same effect as opening the solution file (.sln). However, for multiple
related projects in a solution, you have to open the solution file (.sln) in order to view all the projects.
We advise you to open a solution file (.sln) rather than a project file (.vbproj).
Next, you will learn how to open a solution that was saved.
3.7.9 Hands-on: To open an existing solution
i. Click on the File menu, select Open Project/Solution. The Open dialog box appears for you

to choose your selected file. Another way is to click the link on the start page in the Recent
Projects information area, as shown as figure below.
Final output.

53

ii. Locate the .sln (solution) file and click the Open button. Try to locate the TCC123-VB folder
and double-click to open it. You will see the TCC123-VB solution file, i.e. TCC123-VB.sln. Your
screen may not display the file extensions. Refer to the above figure to identify the icon for the
.sln file.

iii. Double click the TCC123-VB solution file to open the solution, which consists of multiple projects.
To manipulate the created project, you need to choose ’Set as StartUp Project’ for the targeted
project.

3.7.10 Activity
Answer the following questions.
1. controls are used in an interface to display program output.

(A) PictureBox
(B) Label
(C) RadioButton
(D) Button

2. The function key will run Visual Basic program.

(A) <F2>

54

(B) <F3>
(C) <F7>
(D) <F5>

3. A control is used to perform an immediate action when clicked.

(A) PictureBox
(B) TextBox
(C) Button
(D) Label

4. State whether each of the following is true or false. If false, explain why.
i. A control can be added to a form by double clicking its control icon in the Toolbox. True/False?

ii. The Form, Label and PictureBox have identical properties. True/False?

iii. VB programmers usually create complex programs without writing any code. True/False?
iv. Sizing handles are visible during execution. True/False?
5. Fill in the blanks in each of the following statements:

i. The property specifies which image a PictureBox displays.

ii. The menu contains commands for arranging and displaying windows.

iii. The property determines a form’s or control’s background colour.

Activity - Suggested answer
1. B
2. D
3. C
4. Answers are as follows.
i. True
ii. False. Each type of control has a different set of properties, although controls can have
common properties.
iii. False. VB developers usually involves a combination of writing a portion of the program
code and having Visual Studio generate the remaining code.

55

iv. False. Sizing handlers are present only in design mode when a form or control is selected.
5. Answers are as follows.

i. Image
ii. Window
iii. BackColor

3.8 Naming convention

You need to be careful when changing the Name Property of a control. A control’s name must start
with a letter; it can include number and underline characters. Punctuation or spaces are not allowed.
We shall use the standard naming prefixes for the following controls throughout the course.

Table 7: Standard naming prefixes.

Control as in Toolbox Prefix Example
Form frm frmSalary
Button btn btnTotal
Label lbl lblGrossSalary
ListBox lst lstItem
TextBox txt txtOne
ComboBox cmo cmoCountry
CheckBox chk chkGender
RadioButton rdb rdbGender
PictureBox pic picActor

3.9 Event

An event is an action when user clicks on a control or press a key. You need to write instructions that
react to an event by performing some tasks. In this unit, we will write simple assignment statements
to change properties of a control or the form using this format:

controlName.property = setting
where controlName is the name of controls, such as Button, TextBox, Label and etc. property
is one of the properties of the control, such as Forecolor, Text.setting is a valid setting for that

property.

Take a look at the following three examples of assignment statements:

i. txtBox.Text = "Hello World"

//display the word ”Hello World” in the text box

ii. btnButton.Visible = False

//make the button invisible

56

iii. txtBox.Forecolor = Color.Green
//sets the character’s colour in the textbox called txtBox to green

The set of statements that tells an object of how to respond when an event occurred is called an event
procedure. Event procedure code is written in the Code Editor window.

3.9.1 To open the Code Editor window

i. Open the ’103Button’ project. (File menu, select Open Project/Solution - TCC123-VB, right-click
the required project and choose ’Set as StartUp Project’, double-click on the ’Form1.vb’).

ii. Double click the ’Please Press Me’ button. The Code Editor opens in the IDE. Notice that the
Code Editor window already contains some VB code. Private indicates that the event procedure
cannot be invoked by another form. The Button1 Click is objectName event (default name of
the method).

Congratulations! You managed to open a developed project with the Visual Studio here.

3.9.2 Hands-on: Demonstrate event procedures

In this exercise, you will learn to use two TextBox and a Button to demonstrate the event procedures,

as the video clip at https://youtu.be/wzXWrzjQK4g

We locate the following codes for the method ’txtOne TextChanged’, ’txtTwo TextChanged’, ’btnRe-
set Click’ and ’btnGreen Click’. Note that those method names are the name of the event proce-
dures.

1 Private Sub btnGreen_Click(sender As Object , e As EventArgs) Handles
btnGreen.Click

2 txtOne.ForeColor = Color.Green
3 txtTwo.ForeColor = Color.Green
4 End Sub

5

6 Private Sub btnReset_Click(sender As Object , e As EventArgs) Handles
btnReset.Click

7 txtOne.ForeColor = Color.Blue
8 txtTwo.ForeColor = Color.Red
9 End Sub

10

11 Private Sub tx tO ne_ Te xt Ch an ge d ( sender As Object , e As EventArgs )
Handles txtOne.TextChanged

12 txtOne . ForeColor = Color . Blue
13 End Sub

14

15 Private Sub tx tT wo_ Te xt Ch an ge d ( sender As Object , e As EventArgs )
Handles txtTwo.TextChanged

16 txtTwo . ForeColor = Color . Red
17 End Sub

57

Run the VB program, and click the Button btnGreen. Event procedure btnGreen Click is invoked
which changed the contents of the both TextBoxes to green colour.

3.10 Summary

You have taken about three to four hours to manage the IDE and using the Toolbox to add TextBox,
Button, Label, PictureBox and ListBox controls to your form. You used Visual Programming to

design the GUI program quickly and easily by dragging and dropping controls onto a form or by double
clicking controls in the Toolbox. You also made changes to these controls in the Properties window,
and explored the file in the Solution Explorer that made up your project. There was also an exercise
on a few simple codes.

In the next section, you will learn about variables, explore different data types and learn how to create
a procedure and function. You will create your first program that contains VB code that you write
yourself.

To summarise, you should now be familiar with:

i. The Integrated Development Environment (IDE).

ii. Adding controls to your form.

iii. Setting the properties of your controls.

iv. Adding code to your form in the code window.

3.10.1 Self-test

Answer the following questions.

1. The purpose of the control is to display text and you are not allowed to edit this when the
application is running.

(A) Button

(B) TextBox

(C) Label

(D) RadioButton

2. The caption displayed on a button control is stored in the control’s property.

(A) Caption

(B) Font

(C) Object

(D) Text

58

3. Actions of clicking and double clicking are called .

(A) action

(B) events

(C) activity

(D) happening

4. What effect will the following statement have?

lblName.Visible = False

(A) Enable lblName

(B) Make lblName visible

(C) Make lblName invisible

(D) It is not a valid of VB statement.

5. What shortcut key allows you to run the current program?

(A) <F4>

(B) <F5>

(C) <F6>

(D) <F7>

6. Which of the following statements is used to display the words ”Wawasan Open University” in a

label named lblWord?

(A) lblWord.Name = ”Wawasan Open University”

(B) WordLabel.Name.Wawasan Open University

(C) lblWord.Text = ”Wawasan Open University”

(D) ”Wawasan Open University” = lblLabel.Text

7. Which of the following is true about txtWord.Text?

(A) the property is txtWord.

(B) the property is Text.

(C) the object is Text.

(D) All are correct.

8. The contain buttons with down arrows that, when clicked, it will display additional com-
mands.

59

(A) MenuStrip
(B) Toolbar
(C) Icon
(D) Button
9. property in PictureBox scales the image to the size of the PictureBox.
(A) StretchImage
(B) Scale
(C) ScaleImage
(D) AutoSize

10. A Label’s property determines the appearance of the Label’s border.

(A) Fixed
(B) BorderStyle
(C) Border
(D) FixedSingle

Self-test - Suggested answers
1. C
2. D
3. B
4. C
5. B
6. C
7. B
8. A
9. A

10. B

60

3.11 Practice

3.11.1 Exercise 1
Create a VB program, i.e. under a new project of Windows Forms App (.Net framework) in VB, that

displays the state capital in a Label when a Button is clicked. Use the following state names: Ipoh,
Penang, Johor, and Selangor. The program shall use Button and Label controls in a Form. Create

the interface as follows.
State capitals.

To write the code in the code editor window, double-click on the Perak button. Locate the lines of
code. Repeat the same step for the rest of buttons.
1 Private Sub btnPerak_Click(sender As Object , e As EventArgs) Handles

btnPerak.Click
2 lblCapital.Text = "Ipoh"
3 End Sub

4

5 Private Sub btnPenang_Click(sender As Object , e As EventArgs) Handles
btnPenang.Click

6 lblCapital.Text = "George Town"
7 End Sub

8

61

Object Property Setting
Form1 Size
272, 244
Button1 Width, Height CenterScreen
Button2 Start Position State Capitals
Button3 Text btnPerak
Button4 Name Perak
Button5 Text btnPenang
Label1 Name Penang
Text btnJohor
Label2 Name Johor
Text btnSelangor
Name Selangor
Text btnExit
Name Exit
Text lblCap
Name True
AutoSize Capital:
Text lblCapital
Name True
AutoSize FixedSingle
BorderSize (blank - delete the text in the label)
Text MiddleCentre
TextAlign

9 Private Sub btnJohor_Click(sender As Object , e As EventArgs) Handles
btnJohor.Click

10 lblCapital . Text = " Johor Bahru "
11 End Sub

12

13 Private Sub b tnSela ngor_C lick ( sender As Object , e As EventArgs )
Handles btnSelangor.Click

14 lblCapital . Text = " Shah Alam "
15 End Sub

16

17 Private Sub btnExit_Click ( sender As Object , e As EventArgs ) Handles
btnExit.Click

18 Me . Close ()
19 End Sub

Note that the instruction Me.Close() in the Exit button’s click event procedure to instruct the computer
to close the current form. This method will be processed when the user clicks on the Exit button. A
method is a predefined VB that you can call when needed.

3.11.2 Exercise 2

In this exercise, you modify the State Capital solution program from above Exercise 1.

i. Copy and paste the contents of question 1 folder (including the hidden file) to a new folder.

62

ii. Modify the interface, as follows, by adding another label control to the Form.
updated State capitals.

Object Property Setting
Label1 Name lblDescription
AutoSize True
BorderSize FixedSingle
Text (blank - delete the text in the label)
TextAlign MiddleLeft

iii. Modify the program so that it displays the following messages:
When the user clicks the Perak button, the button’s click event procedure should display the
message ’Ipoh is famous for its food’, Penang button - ’Penang is famous for its belacan’, Johor
button - ’Johor is famous for its curry’, and Selangor button - ’Selangor is famous for its noodle’.

Tips: In order to prevent the control from being inadvertently moved in the IDE environment, lock
them by doing the following steps:

i. Right click the Form.

ii. Click ’Lock Controls’ on the context menu. You will notice a small lock appears in the upper-left
corner of the form.

iii. Click the Perak button. Here again, you will notice that a small lock appears in the upper-left
corner of the control.

63

iv. Try dragging one of the controls to a different location. You will not able to do so.
v. You can also unlock the Perak button by changing its Lock property to False.
Lock controls.

3.11.3 Exercise 3
In this exercise, you will add label and button controls to a Form. You will also change the properties
of the Form and its controls.

i. Click on the New Project icon to start a new program. Create a VB program, i.e. under a new
project of Windows Forms App (.Net framework) in VB.

ii. The Windows Form object’s title bar should be named as WOU. (Hint: Text property of the form)
iii. Center the Windows Form object on the screen. (Hint: StartPosition property)
iv. Add a label control to the form and give a label name as lblCompany. (Hint: use the Name

property)
v. Display the label control with the caption ’Wawasan Open University’. (Hint: Text property)
vi. Display the label text in italics using the Arial Font. Change the font size to 12 points. (Hint:

Font property)
64

vii. Add a button control and name it btnExit. (Hint: Name property)
viii. The button control displays the caption ’Exit’. (Hint: Text property)
ix. Display the Exit button’s caption using Arial Font with font size of 12. Increase the button size.

(Hint: Font property)
x. The Exit button should terminate the application when it is clicked. (Hint: Me.Close())

3.11.4 Exercise 4
Try the following exercises.

i. Describe the contents of the text box after the button is clicked.
1 Private Sub btnA_Click(sender As Object , e As EventArgs) Handles

btnA.Click
2 txtOutput.Text = "Hello World"
3 End Sub
ii. Describe the contents of the text box after the button is clicked.
1 Private Sub btnB_Click(sender As Object , e As EventArgs) Handles

btnB.Click
2 txtOutput.Text = "Hello World"
3 txtOutput.BackColor = Color.Blue

65

4 End Sub

iii. Describe the contents of the text box after the button is clicked.
1 Private Sub btnC_Click(sender As Object , e As EventArgs) Handles

btnC.Click
2 txtOutput.Text = "Hello World"
3 txtOutput.Visible = False
4 End Sub

iv. Describe the contents of the text box after the button is clicked.
1 Private Sub btnD_Click(sender As Object , e As EventArgs) Handles

btnD.Click
2 Form1.Text = "Hello World"
3 End Sub

v. Describe the contents of the text box after the button is clicked.
1 Private Sub btnE_Click(sender As Object , e As EventArgs) Handles

btnE.Click
2 txtOutput.Text = "Wawasan Open University"
3 txtOutput.ForeColor = Green
4 End Sub

vi. Describe the contents of the text box after the button is clicked.
1 Private Sub btnF_Click(sender As Object , e As EventArgs) Handles

btnF.Click
2 Form1.Color = Color.Red
3 End Sub

Exercise 4 - Suggested answers

i. The word ”Hello World”.
ii. The word ”Hello World” on blue colour background.
iii. The text box disappears; nothing is visible.
iv. Form1.Text should be replaced by Me.Text.

Form1.Text = ”Hello World” will not work.
The form is referred to by the keyword ’Me’.
Therefore the proper statement is Me.Text = ”Hello World”.
v. Green should be replaced with Color.Green.
vi. Form1.Color must be replaced by Me.ForeColor.

66

3.11.5 Exercise 5
In exercises (a) to (c), write a line (or lines) of code to carry out the task.

i. Display ’Welcome to WOU!’ in lblOne.
ii. Disable txtBox. (Hint: Enabled = False)
iii. Give the focus to btnTotal. (Hint: Focus())

Exercise 5 - Suggested answers
i. Sample lines of code.
1 Private Sub btnA_Click(sender As Object , e As EventArgs) Handles
btnA.Click
2 lblOne.Text = "Welcome to WOU!"
3 End Sub

ii. Sample lines of code.
1 Private Sub btnB_Click(sender As Object , e As EventArgs) Handles

btnB.Click
2 txtBox.Enabled = False
3 End Sub

iii. Sample lines of code.
1 Private Sub btnC_Click(sender As Object , e As EventArgs) Handles

btnC.Click
2 btnTotal.Focus()
3 End Sub

3.11.6 Exercise 6
The interface and initial properties are given as follows.
Disable and enable buttons.

67

Write the program to carry out the stated task. The user can disable or enable the text box by clicking
on the appropriate button. After the user clicks the Enable button, the text box should receive the
focus.

Exercise 6 - Suggested answer
The solution for both disable and enable buttons is as follows.
1 Private Sub btnEnable_Click(sender As Object , e As EventArgs) Handles

btnEnable.Click
2 txtBox.Enabled = True
3 txtBox.Focus()
4 End Sub

5

6 Private Sub btnDisable_Click(sender As Object , e As EventArgs)
Handles btnDisable.Click

7 txtBox.Enabled = False
8 End Sub

68

4 Topic 4: Elements of VB

4.1 Objectives

By the end of this section, you should be able to:
i. Write a simple program using Visual Basic.
ii. Explain and apply primitive data types including integers, strings, and dates.
iii. Use arithmetic and operators to perform calculations.

4.2 Introduction

This section will teach you the ways of declaring variables and various data types. As we know,
variables are temporary memory locations that store data, and the contents of the memory locations
can change while the program is running. Bear in mind that you need to tell VB the type of data that
should be stored in memory locations when you declare a variable. You will apply these data types

in arithmetic operations, and in string and DateTime methods. We will provide a few examples

of common arithmetic operator calculations according to precedence rules. We will also show you

a sample program to demonstrate several string member methods. Lastly, you will learn how to
perform concatenation and add a specific amount of time to DateTime methods.

Now, you will learn how to declare a variable and set its data type in the following section.

4.3 Declaring a variable

In VB, a variable is an object that stores a value. It must be declared (created) before it can be
used. To declare a variable, you start with the variable name you want it to hold followed by a data
type.

i. Dim interestRate As Double
ii. Dim total As Integer = 50
iii. Dim employeeName As String

employeeName = ”Steven”
String data type to store characters and digits cannot be used for arithmetic calculations. For example,
value of ”Steven”, ”seven” and ”50”. In VB, developer requires to declare the type of data that used
by variable, e.g. String, Date, Integer, Double, boolean, and Byte. Examples of valid and invalid of
variables:

For example: Dim total As Integer
The name of variable, i.e. total,

69

Variable name Valid or Invalid
ab43 Valid
43abd Invalid
tot amt Valid
tot-amt Invalid (- dash not allowed)
amt? Invalid (special symbols used)
balan e Invalid (void space or commas)
Integer Invalid, integer is a keyword in VB
Write Invalid, ”Write” is a method in VB

4.4 Naming convention

The following are the naming convention rules for a variable:

i. Choose a meaningful variable name. For example, Dim a1 As Integer. a1 is not a good

variable name.

ii. The first character of variable name identifier must begin with a lower case letter. The first
character in the name after the first word should begin with upper case letter. For example,

identifier employeeName has a capital N for Name. Identifier intEmpWorks has capital E for
Emp and W for Works.

iii. A variable name must begin with a letter or an underscore. For example, 1Employee is an
invalid variable name because it begins with number. A valid variable would be employee,
employee 1 or employee1.

iv. A variable name cannot contain spaces, periods or VB keywords. For example, employee
Name is an invalid variable name because it contains a space between employee and name.

In summary, identifiers are character strings used to name variables, methods, parameters, and a host
of other programming constructs. You can create self-documenting identifiers by concatenating mean-

ingful words into a single descriptive name, using upper case and lower case letters, e.g. cardDeck,
playStationModel, firstName, nricNumber. Certain characters are allowed or disallowed at

certain positions in an identifier.

i. The alphabetic and underscore characters (a through z, A through Z, and ) are allowed at any
position.

ii. Digits are not allowed in the first position but are allowed everywhere else.

iii. The @ character is allowed in the first position of an identifier but not at any other position.
Although allowed, its use is generally discouraged.

Keywords are the character string tokens used to define the VB language. There are important things

to know about keywords, as stated at URL https://docs.microsoft.com/en-us/dotnet/visual-basic/
language-reference/keywords/

70

4.4.1 Activity
Answer the following questions.
1. Which of the following are valid variable names?

(A) employee13
(B) emp 13
(C) employee

(D) All of the above.

2. Which of the following statements declares strSurName as a variable that can hold text?
(A) text mySurName;
(B) char mySurName;
(C) word mySurName;
(D) string mySurName;

3. Which of the following statements is an invalid rule for naming variables?
(A) Names may contain underscores.
(B) Names may contain letters.
(C) Names may contain digits.
(D) Names may contain spaces.

4. are temporary memory locations to store data.
(A) Literal Strings
(B) Constants
(C) Variables
(D) Data Type

Activity - Suggested answers
1. D
2. D
3. D
4. C

71

4.5 Data type

Data type determines the type of data that should be stored in the variable. For example, a declaration

of int total; specifies that the variable total is an integer type and stores integer values, e.g.

0, 11, -11, 138624. Note that data types are used to represent local variables, class data member
variables, method return values, and parameters. We list out 15 primitive data types in the table as
follows.

Data type Size in Values Example
boolean bits
Byte 16 True, False (default value) Dim flag As Boolean
SByte flag = True
Char 8 0 to 255 Dim mark As Byte
Date mark = 60
Decimal 8 -128 to 127 Dim negativeValue As SByte
Double negativeValue = -30
Integer 16 Any Unicode character in the range of 0 to Dim characters As Char
Long 65,535 characters = “C”
Short 64 1 January 0001 to 31 December 9999 Dim countdown as Date
Single 12:00:00 AM to 11:59:59 PM countdown = #22/9/2006#
String 128 Dim total As Decimal
Values up to ±79,228 × 1024 total = 19456.00
UInteger 64 Dim money As Double
ULong (floating point) -1.79769313486231E308 to money = 2344.50
UShort 32 1.79769313486231E308 Dim total As Integer
-2,147,483,648 to +2,147,483,647 total = 3600000
64 Dim distance As Long
-9,223,372,036,854,775,808 to distance = 48000000
16 9,223,372,036,854,775,807 Dim distance As Short
32 -32,768 to 32,767 Dim price As Single
-3.4028235E38 to 3.4028235E38 price = 100.99
16-bits Dim empName As String
per 0 to ∼ 2 billion 16-bit Unicode characters empName =“Steven”
char-
acter 0 to 4,294,967,295 Dim num As UInteger
32 0 to 18,446,744,073,709,551,615 num = 20000000
0 to 65,535 Dim stars As ULong
64 stars = 17000000000000
Dim days As UShort
16 Days = 30000

Note that string data type to store characters and digits cannot be used for arithmetic calculations.
For example, value of ’Steven’ and ’50’. Integer data type to store numbers can be used for arithmetic
calculations. For example, value of 50. Decimal or Double data type to store numbers that contain
decimal places can be used for arithmetic calculations. For example, value of 50.30.

72

4.5.1 Activity
Answer the following questions.
1. Which of the following statements is a valid declaration?

(A) integer quantity;
(B) int as quantity;
(C) quantity = int;
(D) int quantity;
2. Data types, such as string and int, are known as:

(A) Numeric data types.
(B) String data types.
(C) Fundamental data types.
(D) Boolean data types

3. Which of the following is the default value of the DateTime data type?

(A) 1/1/2001 12:00:00 AM
(B) 1/1/0001 12:00:00 AM
(C) 1/1/2001 12:00:00 PM
(D) 1/1/0001 12:00:00 PM

4. What is the default value of the boolean (bool) data type?

(A) Flag
(B) 1
(C) True
(D) False

Activity - Suggested answers
1. D
2. C
3. B
4. D

73

4.5.2 Hands-on: Displaying a single line of text with single statement
In this activity, you learn to create VB programs with the installed Visual Studio, which manipulate VB
data types. Recap the Hands-on in Week 1, i.e. Hello World program. You have learned to create a
Windows Console App (.Net framework) in VB.
1. Let us create another new project of Windows Console App (.Net framework) in VB.
2. Suppose that you have now created a VB project. In the Solution Explorer pane (View, choose
Solution Explorer), you can see that the project consists of a single VB source file, i.e. Module1.vb,
that should already be opened. Otherwise, you may double-click on the file in the Solution Explorer in
order to open it.
3. Write the required VB code to display your name to the Console window. Display a blank line before
and after your name. (Hint: use the WriteLine() method)
4. In the Main method of source file, i.e. Module1.vb, locate the following lines of VB code.
1 static void Main(string[] args)
2{
3 System.Console.WriteLine("")
4 System.Console.WriteLine("My Name is Wawasan Open University.")
5 System.Console.WriteLine("")
6}

Suppose that you try running the compiled program, it will show the required output.
Reminder:

i. System is a namespace of .Net framework.
ii. Console is a class name.
iii. WriteLine is a member name of class Console.

4.5.3 Hands-on: Rename class
You will learn to rename the VB class in this exercise. Let us try it out!
1. Open the created project for Hands-on above.
2. Name the VB class to ’MyVB’, by right-click the source file, i.e. Module1.vb, as follows.

74

3. Alter the program to display the text ”Visual Programming” to the Console window. Display a blank
line before and after the text.
4. Click on the ’Yes’ button if a message pop-up for further code alteration.

You should notice that the class name has been changed to ’MyVB’ as follows.

75

5. Suppose that you try running the compiled program, it will show the required output.

4.5.4 Hands-on: Displaying a single line of text with multiple statements
You learn to use two types of methods calls to produce the same output for the message ”Welcome

to Visual Programming.” You will notice the difference between the Write and WriteLine methods

in this exercise.
1. Let us create a new project of Windows Console App (.Net framework) in VB, with the installed
Visual Studio.
2. Suppose that you have now created a VB project. In the Solution Explorer pane (View, choose
Solution Explorer), you can see that the project consists of a single VB source file, i.e. Module1.vb,
that should already be opened. Otherwise, you may double-click on the file in the Solution Explorer in
order to open it.

3. Locate the following VB codes into the Main method. Suppose that you try running the compiled

program, it will show the required output.

76

Note that we are using Write method, the first character (”V”) of Visual appears immediately after the
last character is displayed (i.e., the space character after the word ”to” in line 5). Note that Console
is a class name. WriteLine is a member name of class Console.

4.5.5 Activity
Answer the following questions.
1. Write a program ’Display1to4.vb’ to display the numbers 1 to 4 on the same line, with each pair of
numbers separated by one space. Write the program using the following:

i. Use one Write statement.
ii. Use four Write statements.
Save your created Windows Console Application (with .Net framework).

Activity - Suggested answers
1. The solution is available at the remote GitHub repository.

77

4.6 Working with the int data type

The following program prompts a user to enter two numbers, calculates the sum of these two numbers
and displays the result. The purpose of this program is to teach you how to declare the Integer type
of variable and display the result. Create VB source, i.e. ’Module1.vb’, as follows.

1 Sub Main()
2 ’ variables used in addition calculation
3 Dim num1 , num2 , sum As Integer

4

5 ’ prompt the user to enter first number
6 System.Console.Write("Please enter first number: ")
7 num1 = System.Console.ReadLine()

8

9 ’ prompt the user to enter second number
10 System . Console . Write ( " Please enter second number : " )
11 num2 = System . Console . ReadLine ()

12

13 sum = num1 + num2 ’ add the numbers

14

15 ’ display the sum
16 System . Console . WriteLine ( " The sum is " & sum )
17 End Sub

Analysing the program

i. Line 3 is to declare variables num1, num2 and sum using Integer data type.

ii. Lines 5 and 9 prompt the user to enter the first and second numbers.

iii. Lines 7 and 11 are to obtain the numbers entered by the user and assign it to variables num1
and num2.

iv. The method ReadLine in lines 7 and 11 causes the program to pause and wait for user input.

v. In line 7, once the user has input the first number and pressed the <Enter> key, the string
number is parsed to int before assigning to variable num1 by an assignment, i.e. symbol ’=’.

vi. In line 13, the assignment statement computes the total of the variables num1 and num2, and

assigns the result to the variable sum.

vii. Line 16 displays the total of two values. The argument to method WriteLine, and also uses

the string concatenation operator, i.e. symbol ’&’, to combine the literal ”The sum is ” and the
value of the variable sum. The string concatenation operator is used to combine two strings,
i.e. to join two strings together.

Output:

78

Methods of class Convert is used to explicitly convert data from one type to another using the word
To, followed by the name of the type to which the method converts its argument. For example, to
convert a String input by the user to type Integer, use the statement as follows.

number = System.Convert.ToInt64(Console.ReadLine())

Examine the implementation as the following VB source.
1 Sub Main()
2 Dim number As String = ""
3 Console.WriteLine("Before conversion , the string representation

of number Is " \& number)
4 System.Console.Write("Enter a number:")
5 ’Converts the specified String representation of
6 ’a number to an equivalent 64-bit signed integer
7 number = System.Convert.ToInt64(Console.ReadLine())
8 number = number + 1
9 Console.WriteLine("")
10 Console . WriteLine ( " After conversion , the integer value after

calculation Is " \& number)
11 End Sub

4.6.1 Activity

Answer the following questions.

1. Create a new project of Windows Console App (.Net framework) in VB. Declare and assign a value
to the following variable to calculate the profit of a company:

i. Declare the variables of revenue, costs and profits.

ii. Assign the value 1,000 to the variable revenue.

iii. Assign the value 800 to the variable costs.

iv. Assign the difference between the variables revenue and costs to the variable profits.

79

2. Create a new project of Windows Console App (.Net framework) in VB. Declare and assign a
value to the following variables to calculate the profit, i.e. revenue - cost, of the stationery items
purchased:

i. Declare the variables of unitPrice, quantity and totalCost.
ii. Assign the value 2.00 to the unitPrice.
iii. Assign the value 10 to the quantity.
iv. Assign the product of unitPrice and quantity to the variable totalCost.
v. Assign the value 10 to the revenue.

Activity - Suggested answers
1. The solution is available at the remote GitHub repository.

4.7 Arithmetic

Most application programs involve arithmetic calculations. A list of selected common arithmetic oper-
ators is shown in the following table.

Table 8: Arithmetic operators

Operator Arithmetic operator Algebraic expression VB expression
Addition + b+7 b+7
Subtraction - b-7 b-7
Multiplication * bc b*c
Division / b/c b/c
Modulus % b%c
Power b Mod c
Exponent (inverse of Log) Math.Pow bc Math.Pow(b,c)
Unary minus Math.Exp ec Math.Exp(c)
Unary plus
Logarithm - -b -b
+ +b +b
Math.Log log c Math.Log(c)

Read more on available constants and static methods for trigonometric, and other mathematical func-

tions at the URL https://docs.microsoft.com/en-us/dotnet/api/system.math?view=netframework-4.
7.2

A common use of the assignment and arithmetic operators is to operate on a variable and then to
save the result back into that same variable. These operations can be shortened with the combined
assignment operators.

1 Sub Main()
2 Dim x As Integer = 25
3 System.Console.WriteLine("When x = " & x)

80

4 x += 5 ’ x = x+5
5 System.Console.WriteLine("x += 5 , the answer is " & x)
6 x -= 5 ’ x = x-5
7 System.Console.WriteLine("x -= 5 , the answer is " & x)
8 x *= 5 ’ x = x*5
9 System.Console.WriteLine("x *= 5 , the answer is " & x)
10 x /= 5 ’ x = x /5
11 System . Console . WriteLine ( " x /= 5 , the answer is " & x )
12 System . Console . WriteLine ()
13 End Sub

Output:

4.7.1 Rules of operator precedence

VB uses the arithmetic operators according to the rules of operator precedence, which is summarised
in the following table.

Table 9: Precedence of arithmetic operators

Operator Operation Order of evaluation (precedence)
Exponentiation 1
∧ Sign operations 2
+, − Multiplication and division 3
∗, / Integer division 4
Modulus 5
M od Addition and subtraction 6
+, −

The following example (algebra) contains modulus(%), multiplication, division, addition and subtrac-
tion operations.

Algebra: a = b c % d + e / f - g

Note that the multiplication and division operators are evaluated first. The % operator is evaluated
next. The addition and subtraction operators are applied last.

81

4.7.2 Program to demonstrate arithmetic operation

The following VB program is to demonstrate arithmetic operations using precedence rules. The pur-
pose of this program is to teach you how to declare the variable using the double data type.

1 Sub Main()
2 ’ Declare variable
3 Dim a, b, c, d, e, f, g As Double
4 ’ Assign a value to variable
5 a = 2.0
6 b = 3.0

7

8 ’ Display the results
9 System.Console.WriteLine("When a = " & a &
10 " , b = " & b )
11 System . Console . WriteLine ()
12 System . Console . WriteLine ( " 5 * b + 1 = " &
13 (5 * b + 1) )
14 System . Console . WriteLine ( " a Mod b + 1 = " &
15 ( a Mod b + 1) )
16 System . Console . WriteLine ( " Math . Pow (a , b ) + 0.8 = " &
17 ( Math . Pow (a , b ) + 0.8) )
18 System . Console . WriteLine ( " Math . Log (1) = " &
19 Math . Log (1) )
20 System . Console . WriteLine ( " Math . Log ( a /2) + 0.8 = " &
21 ( Math . Log ( a / 2) + 0.8) )
22 System . Console . WriteLine ( " Math . Exp (0) = " &
23 Math . Exp (0) )
24 System . Console . WriteLine ( " Math . Exp (b -3) + 0.8 = " &
25 ( Math . Exp ( b - 3) + 0.8) )
26 System . Console . WriteLine ()
27 ’ Assign a value to variable
28 c = 4.0
29 d = 5.0
30 e = 6.0
31 f = 6.0
32 g = 8.0
33 System . Console . WriteLine ( " b * c Mod d + e / f - g = " &
34 ( b * c Mod d + e / f - g ) )

35

36 System . Console . WriteLine ()
37 System . Console . WriteLine ( " Math . PI = " & Math . PI )
38 Dim angle As Double = ( b * 10) * (180 / Math . PI )
39 System . Console . WriteLine ( " The angle = " & angle )
40 Dim radius As Double = angle * ( Math . PI / 180)
41 System . Console . WriteLine ( " The radius = " & radius )
42 End Sub

Output:

82

4.7.3 Activity
Answer the following questions.

1. Given algebraic b = 5f 5–x where variables b, f and x are declared in double, state the required

VB code for your development with the Visual Studio.
2. Indicate the order of evaluation for the following expressions, and find the value of x.

i. x = 5 + 3 ∗ 4/2 − 2

ii. x = 4%4 + 4 ∗ 2 − 2/2

iii. x = (1 ∗ 4 ∗ (1 + (3 ∗ 3/(3))))

3. Write a Windows Console VB program that prompts the user to enter two numbers and calculates
the sum, product, difference and quotient. Display the results on the Console window.

Activity - Suggested answers
1. Sample codes of answer.
1 double b, f, x;
2 b = 5 * Math.Pow(5, f) - x;

2. Obtain the value of x as follows.
i. Sample working steps.
x=5+3*4/2-2
= 5 + 12 / 2 - 2
=5+6-2

83

= 11 - 2
=9

ii. Sample working steps.
x=4%4+4*2-2/2
=0+4*2-2/2
=0+8-2/2
=0+8-1
=8-1
=7

iii. Sample working steps.
x = (1 * 4 * (1 + (3 * 3 / 3)))
= (1 * 4 * (1 + (9 / 3)))
= (1 * 4 * (1 + 3))
= (1 * 4 * 4)
= (4 * 4)
= 16

3. The solution is available at the remote GitHub repository.

4.8 Using a message dialogue to display a message

The program’s output can be displayed on a message dialogue instead of displaying it in the Console
window. Message dialogues are windows that display messages to the user. The following program
uses a message dialogue to display the square root of 2.
1 Imports System.Windows.Forms

2

3 Module MsgBox

4

5 Sub Main()
6 Dim root As Double = Math.Sqrt(2)
7 MessageBox.Show("Square root of 2 is " & root)
8 End Sub

9

10 End Module

Take note that in the result of VB program, the square root of 2 is displayed with many decimal places.
In the next program, we will modify the program to display only a few decimal places.

Reminder: Class MessageBox must be added to the project before you execute the program. Other-

wise, it gives a compilation error.

84

4.8.1 Adding a Reference to an assembly

You need to add a Reference to the assembly before the class MessageBox can be used in your

program. We list out the following five steps as follows:
1. First, view the project’s References folder, as in Solution Folder, to check which assemblies are
currently referenced in a project.
2. Click on the ’+’ sign to expand the References folder. You will notice that the System.Windows.Forms
reference is not listed.
3. You can add System.Windows.Forms by right-click on the target project’s name, and select Add
then Reference.

4. Scroll down the list in the target .NET, and select System.Windows.Forms, then click OK.

85

5. System.Windows.Forms is listed in the References folder after you click OK. Edit your code by
adding the line 1, as shown as above, before run the VB program.

Output:

86

4.9 Rounding value

The previous VB program has been modified. It includes the Math.Round method to display only a
few digits of the decimal place.

i. Math.Round(1.4142135623731) is 1 // No decimal place

ii. Math.Round(1.4142135623731, 2) is 1.41 // round up to 2 decimal places

iii. Math.Round(1.4142135623731, 3) is 1.414 // round up to 3 decimal places

iv. Math.Round(1.4142135623731, 4) is 1.4142 // round up to 4 decimal places

As above examples, you notice that Math.Round method round up the results into required decimal

places, also known as factional digits. Try to run the program and observe the results, as follows.

1 Imports System.Windows.Forms

2

3 Module MsgBox

4

5 Sub Main()
6 Dim pi As Double = Math.PI
7 MessageBox.Show(pi & "", "pi")
8 MessageBox.Show(Math.Round(Math.PI , 2) _
9 & "", "pi with 2 decimal place")
10 MessageBox . Show ( Math . Round ( Math . PI , 3) _
11 & " " , " pi with 3 decimal place " )
12 MessageBox . Show ( Math . Round ( Math . PI , 4) _
13 & " " , " pi with 4 decimal place " )
14 End Sub

15

16 End Module

4.9.1 Activity

Answer the following question.

1. Refer to the question 3 in Activity 4.7.3. Add the coding to your existing program to display the
output in a message dialogue box.

87

Activity - Suggested answers

1. The solution is available at the remote GitHub repository.

4.10 Working with the string data type

A string is a single unit of characters and we use double quotation to mark its beginning and end. A

string variable is a name used to refer to a piece of text. You can assign a string literal to a string

variable in the form as follows.

i. Dim varName As String = "value";

ii. Dim empName As String = "Yeap Chor Ee";

The declaration of later example initialises string variable empName to refer to the string literal object
Yeap Chor Ee. The following program demonstrates concatenation using strings. Concatenation

means joining two strings together, one after the other.

1 Imports System.Windows.Forms

2

3 Module StringDataType
4 Sub Main()
5 Dim stringOne , stringTwo , stringOutput As String
6 stringOne = "Welcome to"
7 stringTwo = " Visual Programming"
8 stringOutput = stringOne + stringTwo
9 MessageBox.Show("The string is : " & stringOutput ,

"Concatenation")
10 End Sub
11 End Module

In line 8, we use the + operator to concatenate the two strings and assign the results of the concate-

nation to stringOutput variable. So stringOutput holds stringOne and stringTwo values. Whereas in
line 9, stringOutput will be equal to ”Welcome to Visual Programming” once you call the Message-
Box.Show method. The string ”Concatenation” becomes the title bar of the MessageBox.

Output:

4.10.1 Activity
Answer the following questions.

88

1. Create a VB program to concatenate (join) your surname and last name into one string. Display
your output using MessageBox.Show.

2. Identify the errors in the following code.

i. Study these codes properly, and find their mistake/s.

Dim hPhoneNumber As Integer
hPhoneNumber = "012-3456789"
MessageBox.Show("Telephone number is: " & hPhoneNumber)

ii. Study these codes properly, and find their mistake/s.

Dim msg As String
msg = Visual Programming is fun
MessageBox.Show(msg & "!")

iii. Study these codes properly, and find their mistake/s.

Dim if As String
if = "Visual Programming is fun"
MessageBox.Show(if)

Activity - Suggested answers

1. The solution is available at the remote GitHub repository.

2. Sample solutions for identified mistake/s.

i. Variable hPhoneNumber should be declared as

String, not Integer.

ii. The sentence in the second line should be surrounded by quotation marks.

msg = "Visual Basic is fun".
iii. The if is a keyword and cannot be used as a variable name.

4.11 Manipulating with string data

System.String provides a number of methods you would expect from such a utility class, including

methods that return the length of the character data, find sub-strings within the current string, and
convert to and from uppercase/lowercase. The following VB program demonstrates the selected
operations.

i. Length property, which returns the number of characters in a string. Characters can include

spaces and punctuation marks.

ii. Substring method, which extracts a sequence of consecutive characters from the string. For

example, it starts at position 0 and extracts 5 characters.

89

iii. IndexOf method, which locates the first occurrence of a character in a String. IndexOf returns

the index of the specified character in the String if it finds a character which starts with position
0; otherwise, IndexOf returns -1.

iv. Replace method, which searches for a specified String and substitutes another string in its

place.

v. ToUpper method, to convert character to its upper case equivalent.

vi. ToLower method, to convert character to its lower case equivalent.

vii. Contains method, to determines whether a string contains a specific substring.

1 Sub Main()
2 Dim stringOne As String
3 stringOne = "Hello World"

4

5 ’ return the length of a string
6 System.Console.WriteLine("The length of stringOne is " _
7 & stringOne.Length & " characters")
8 ’ return the first 5 characters
9 System.Console.WriteLine("The first 5 characters are " _
10 & stringOne . Substring (0 , 5) )
11 ’ Find the index location of l
12 System . Console . WriteLine ( " The first ’l ’ located at index " _
13 & stringOne . IndexOf ( " l " ) )
14 ’ Replace the ’ Hello ’ to ’ Goodbye ’
15 System . Console . WriteLine ( " The Hello replaced by " _
16 & stringOne . Replace ( " Hello " , " Goodbye " ) )
17 ’ Convert ’ Hello World ’ to uppercase
18 System . Console . WriteLine ( " The Hello World in uppercase " _
19 & stringOne . ToUpper () )
20 ’ Convert ’ Hello World ’ to lowercase
21 System . Console . WriteLine ( " The Hello World in lowercase " _
22 & stringOne . ToLower () )
23 ’ Determines whether a string contains a specific substring
24 Console . WriteLine ( " stringOne contains the letter r ?: {0} " ,
25 stringOne . Contains ( " r " ) )
26 End Sub

Output:

90

Reading:

To learn more about String manipulation, please read the material at URL https://docs.microsoft.
com/en-us/dotnet/api/system.string?view=netframework-4.7.2

4.11.1 Activity
Answer the following questions.

1. Determine the output displayed from the following code.
i. Console.WriteLine(”whippersnapper”.IndexOf(”pp”, 5));

ii. Console.WriteLine(”VCC 5001”.ToLower)

iii. Console.WriteLine(”Visual Studio”.IndexOf(”k”))

iv. Console.WriteLine(”18.18”.Length)

v. Console.WriteLine(”Fitman”.Substring(3))
2. Determine the output displayed from the following code.

i. Study these codes properly.

Dim orenQuantity As Integer = 8826
Console.WriteLine(orenQuantity.IndexOf("2"))

ii. Study these codes properly.

Dim appleQuantity As Integer = Double
Console.WriteLine(appleQuantity.Length)

Activity - Suggested answers
1. The solutions are available at the remote GitHub repository.
2. Sample outputs.

i. The IndexOf method cannot be applied to an integer, only a string.
ii. An integer does not have a Length property, only a string has a Length property.

91

4.12 Working with the DateTime data type

Dates are similar to the string type where you can perform concatenation. It is also similar to integer
type where you can perform addition or subtraction. Examine the below VB program, and you notice
the listed items as follows.

i. Assigning a DateTime value, either with required date or current date.

ii. Displaying the date

iii. Manipulating the date and time

iv. Retrieving the interval between two existing dates or times

1 Sub Main()
2 Dim dteDateOfBirth As Date = #9/22/2006#
3 Dim dteMerdekaDay As Date = #8/31/1957#
4 Console.WriteLine("My birthday is " & dteDateOfBirth)
5 Console.WriteLine()

6

7 Dim dteDate As Date = Date.Now
8 Console.WriteLine("Today is " & dteDate)
9 Console.WriteLine()

10

11 Dim dteDate1 As Date = dteDate
12 Dim dteDate2 As Date = dteDate
13 Dim dteDate3 As Date = dteDate
14 Dim dteDate4 As Date = dteDate
15 Dim dteDate5 As Date = dteDate
16 ’ To add 5 months
17 dteDate1 = dteDate1 . AddMonths (5)
18 Console . WriteLine ( " 5 months later : new date is " & dteDate1 )
19 ’ To add 2 years
20 dteDate2 = dteDate2 . AddYears (2)
21 Console . WriteLine ( " 2 years later : new date is " & dteDate2 )
22 ’ To add 2 minutes
23 dteDate3 = dteDate3 . AddMinutes (2)
24 Console . WriteLine ( " 2 mins later : new date is " & dteDate3 )
25 ’ To add 2 days
26 dteDate4 = dteDate4 . AddDays (2)
27 Console . WriteLine ( " 2 days later : new date is " & dteDate4 )
28 ’ To add 2 hours
29 dteDate5 = dteDate5 . AddHours (2)
30 Console . WriteLine ( " 2 hours later : new date is " & dteDate5 )
31 Console . WriteLine ()

32

33 ’ Returns the number of days - after 5 months
34 Console . WriteLine ( " 5 months later : " & ( dteDate1 -

dteDate).TotalDays _
35 & " days , " & ( dteDate1 - dteDate ) . TotalHours &

" hours")
36 ’ Return the number of days - after 2 years

92

37 Console . WriteLine ( " 2 years later : " & ( dteDate2 -
dteDate).TotalDays _

38 & " days , " & ( dteDate2 - dteDate ) . TotalHours &
" hours")

39 ’ Return the number of days - after 2 minutes
40 Console . WriteLine ( " 2 mins later : " & ( dteDate3 -

dteDate).TotalDays _
41 & " days , " & ( dteDate3 - dteDate ) . TotalSeconds

& " seconds")
42 ’ Return the number of days - after 2 days
43 Console . WriteLine ( " 2 days later : " & ( dteDate4 -

dteDate).TotalDays _
44 & " days , " & ( dteDate4 - dteDate ) . TotalSeconds

& " seconds")
45 ’ Return the number of days - after 2 hours
46 Console . WriteLine ( " 2 hours later : " & ( dteDate5 -

dteDate).TotalDays _
47 & " days , " & ( dteDate5 -

dteDate).TotalMilliseconds & " milliseconds")
48 End Sub

Output:

4.12.1 Activity
Answer the following question.
1. Create a program that prompts a user to enter a valid date of birth. Use the date methods to
calculate the age of the user.

Activity - Suggested answers
1. The solution is available at the remote GitHub repository.

93

4.13 Summary
You have learnt how to display the output on the Console window using the WriteLine and Write
methods, and also how to accept user data input through the ReadLine method. Variables were

introduced and we looked closely at types of variable. You have also learnt how to use arithmetic
operators to perform calculations according to the rules of operator precedence. We gave coding
examples in guiding you to understand the elements of VB.
In the coming section, you will learn various ways using a program to make decisions and performing
loop with control statements. These are important statements for building and manipulating objects.
To summarise, you should now be familiar with:

i. How to declare and assign variables.
ii. How to use arithmetic operators to perform calculations.

iii. How to use the string data type and its properties and methods.
iv. How to use the int, DateTime data types and their individuals methods.

4.13.1 Self-test 1

Answer the following questions.
1. Write Visual Basic statements to accomplish the following tasks.

i. Display the message ”Visual Programming” using the class MessageBox.
ii. Assign the sum of variable number1 and number2 to variable total.

iii. Write a comment ”This program performs a simple arithmetic calculation”.
2. What will be displayed in the message dialog when each of the following statements is exe-

cuted? Assume that the value of y = 4 and value of z = 5.
i. MessageBox.Show(y + "", "Y");
ii. MessageBox.Show((y + y) + "", "(y + y)");
iii. MessageBox.Show("y + z");

3. Write a program that prompts a user to input the radius of a circle and display the circle’s

diameter, circumstance and area. Use the following formulas: diameter = 2r; circumference =

2πr; area = πr2 and π = 3.14159. Assume that r is the radius.

4. Write a program to calculate the squares and cubes of the numbers from 1 to 4 and display the
results in the following table format:

5. Write a program to concatenate (join) a string with a number. The output should be displayed
as ”The keyboard has 128 keys”. Use the following variables:

94

Table 10: Keywords, adopted from [2]

Number Square Cube
1 1 1
2 4 8
3 9 27
4 16 64

stringOne = "The keyboard has "
numberKey = 128

6. Determine the output of the following code.
1 int a = 4;
2 int b = 2;
3 string c = "Visual";
4 string d = "Basic";
5 Console.WriteLine(c.Length);
6 Console.WriteLine(c.ToLower());
7 Console.WriteLine(c.Substring(a, b - 1));
8 Console.WriteLine(c.IndexOf(d));

7. Write a program to add 2 months to today’s date and determine the interval days between these
two dates.

Self-test 1 - Suggested answers

1. Sample solutions.

i. MessageBox.Show("Visual Programming")

ii. total = number1 + number2

iii. ’ This program performs a simple arithmetic calculation

2. The solutions are available at the remote GitHub repository.

3. The solution is available at the remote GitHub repository.

4. The solution is available at the remote GitHub repository.

5. The solution is available at the remote GitHub repository.

6. The solution is available at the remote GitHub repository.

7. The solution is available at the remote GitHub repository.

95

5 Topic 5: Manipulation with VB

5.1 Objectives

By the end of this section, you should be able to:
i. Apply code selection and repetition statement
ii. Create and apply methods to a program

5.2 Introduction

All statements of a program execute from top to bottom. We can observed this in previous section,
where program is developed in a sequence structures. Statements of program are executed one
after another in the order in, which they are written. We control the flow of execution by the following
approaches:

i. Decision Operators
ii. Decision Structure
iii. Loops Structure
iv. Jump Statements
Control flow helps our program to execute or skip a code block, helps us to repeat a code until a
condition is satisfied, and helps our control to jump anywhere in the code.
In this section, we will concentrate on the selection and repetition (loops) structures. These structures
are also called control statements, and they are more complex than sequence structures. These
structures enable you to control the flow of the building blocks so that decisions can be made. For

example, if marks > 50, then the program will print ’Pass’, otherwise it will print ’Fail’. This is known

as a branching or a selection (decision) structure. Later on, we will look at how to make the program
loop a specified number of times until all the conditions are satisfied.

5.3 Decision Structure

Decision structures lets a program run only in certain conditions. Normally our program runs in a
simple flow which executes all code from top to bottom without skipping any code. However in the real
world, our application helps us decide what code to execute in certain conditions.
For example, you’re making a program that checks a person’s age and decides whether or not a
person has reached his retirement age. In such a case, Microsoft introduce decision structures to let
the its application decide whether a person has reached his retirement age or not. VB .Net has some
decision structures that we can use listed below.

i. If...Then

96

ii. If...Then...Else

iii. Select...Case

These statements in VB operates only on Boolean expressions, not ad-hoc values, such as -1 or 0.
These statements typically involve the use of the VB operators to obtain a literal Boolean value, as
follows.

Table 11: VB Relational and Equality Operators.

Equality / Example Usage Descriptions
Relational
Operator IF age = 25 THEN Returns true only if each expression is the same.
IF myStr ! = ”WOU” THEN Returns true only if each expression is different.
= IF (fees < 1000 THEN Returns true if expression A (fees) is less than to expression B
!= (1000)
Returns true if expression A (fees) is greater than to expression B
< (1000)
Returns true if expression A (fees) is less than or equal to
> IF fees > 1000 THEN expression B (1000)
Returns true if expression A (fees) is greater than or equal to
<= IF fees <= 1000 THEN expression B (1000)

>= IF fees >= 1000 THEN

The following table explains these structures of selection statement.

Table 12: Decision Structure.

Structure Descriptions
It performs an action or sequence of actions if a condition is true, or skips the action or
If...Then sequence of actions if the condition is false. It is a single-selection statement because it selects
If...Then...Else or ignores a single action or sequence of action.
Select...Case It performs an action or sequence of actions if a condition is true, else it performs a different
action or sequences of actions if the condition is false. It is a double-selection statement
because it selects between two different actions or sequences of actions.
It performs one of many different actions or sequences of actions, depending on the value of an
expression. It is a multiple-selection statement because it selects among many different actions
or sequences of actions.

5.3.1 Hands-on: If structure - Even number

If statement helps us to control the flow of a program. It executes a program only when a certain

condition returns true. Let us write a code that prints a message ”Even Number” only when a number
is even. Now we will walk through the following steps to create the VB program.
1. Create a new project of Windows Console App (.Net framework) in VB with the installed Visual
Studio.
2. In the source file, i.e. Module1.vb, locate the following lines of VB code.

97

1 Sub Main()
2 Dim number As Integer = 128
3 If number Mod 2 = 0 Then
4 Console.WriteLine("Even Number")
5 End If
6 End Sub

3. Suppose that you try running the compiled program, by pressing <F5>, it will show the message

”Even Number”.

4. Click on Save All icon to save the work.

5.3.2 Hands-on: If Else structure

In real application, we find ourselves in a right or wrong situation. For example, if we enter a right
username the system will log in. But if we enter an invalid username the system will pop an error. In
such situations, we write code inside if-else statements. Let us walk through the following steps to
create the VB program.

1. Create a new project of Windows Console App (.Net framework) in VB with the installed Visual
Studio.

2. In the source file, i.e. Module1.vb, locate the following lines of VB code.
1 Sub Main()
2 Dim username As String = "Wawasan"
3 If username = "Wawasan" Then
4 Console.WriteLine("Passed. Login Successful")
5 Else
6 Console.WriteLine("Login failed")
7 End If
8 End Sub

3. Suppose that you try running the compiled program, by pressing <F5>, it will show the message

”Login Successful”.

4. Click on Save All icon to save the work.

5.3.3 Activity

1. Rewrite the saved program in Hands-on 5.3.1 with If Else structure. The program prints

either message ”Even Number” or ”Odd Number” when a number given by your user.

2. Write a program to prompt a user to input two numbers and find the larger of two numbers. Use

If Else{} structure.

3. Determine the output of the following codes:

98

i. CGPA program

1 Sub Main()
2 Console.Write("What is your current CGPA: ")
3 Dim cgpa As Double
4 cgpa = Console.ReadLine()
5 ’ Clear() Is used to erase the whole console
6 Console.Clear()

7

8 If (cgpa >= 3.67) Then
9 Console.Write("A distinction ")
10 End If
11 Console . WriteLine ( " Student in WOU ! " )
12 End Sub

(Assume that the student enters 3.4)

ii. Arithmetic program

1 Sub Main()
2 Dim x As Integer = 4
3 Dim y As Integer = 2
4 Dim z As Integer = 1
5 If (x + y) < z Then
6 y=9
7 Else
8 y=x*z
9 End If
10 Console . WriteLine ( y )
11 End Sub

iii. EligibleStudy program

1 Sub Main()
2 Console.Write("Please enter your age: ")
3 Dim age As Double = Console.ReadLine()

4

5 If (age >= 21) Then
6 Console.WriteLine("You are eligible to study at WOU")
7 Else
8 Console.WriteLine("You are eligible to study in " &

(21 - age) & " years")
9 End If
10 End Sub

(Assume that the user enters 18)

Activity - Suggested answers

All solutions are available at the remote GitHub repository.

99

5.3.4 Hands-on: If ElseIf structure - Type of person

Chain of multiple If and Else makes If ElseIf. It helps a program to look into multiple conditions

(options) to execute a specific block of code. Let us make a program that checks your age and prints
on output screen whether you’re a child, teenager, adult, or an old man.

1. Create a new project of Windows Console App (.Net framework) in VB with the installed Visual
Studio.

2. In the source file, i.e. Module1.vb, locate the following lines of VB code.

1 Sub Main()
2 Console.WriteLine("Enter your age")
3 ’ Dim age As Integer = Console.ReadLine()
4 age = Console.ReadLine()
5 If (age > 0) Then
6 Console.WriteLine("You have entered {0}", age)
7 Else
8 Console.WriteLine("Invalid input")
9 End If

10

11 If ( age < 11) Then
12 Console . WriteLine ( " You ’ re a child ! " )
13 ElseIf ( age < 18) Then
14 Console . WriteLine ( " You ’ re a teenager ! " )
15 ElseIf ( age < 50) Then
16 Console . WriteLine ( " You ’ re an adult ! " )
17 Else
18 Console . WriteLine ( " You ’ re an old person " )
19 End If
20 End Sub

3. Suppose that you try running the compiled program, by pressing <F5>, it will show the message

for type of person based on the entered age.

4. Click on Save All icon to save the work.

5.3.5 Hands-on: If ElseIf structure - Marks and grade

Suppose that you want to test more than one condition, you need to use an ElseIf structure. As

the first condition is evaluated to be true, its actions will be executed, and no other conditions will be
evaluated. However, as the first condition is evaluated to be false, the second conditional expression
is evaluated. Suppose that the second condition is true, the second block of actions is executed. As

none of the conditions are true, the final Else’s action is executed.

Let us compose a program to show the following message under required condition:

i. ”A” for exam marks greater than or equal to 80

ii. ”B” for marks greater than or equal to 70

100


Click to View FlipBook Version