Prog 2 VB. Net Module v2
Prog 2 VB. Net Module v2
PROGRAMMING II
This is a property of
PRESIDENT RAMON MAGSAYSAY STATE UNIVERSITY
NOT FOR SALE
Republic of the Philippines
President Ramon Magsaysay State University
COLLEGE OF COMMUNICATION AND INFORMATION TECHNOLOGY
Copyright. Republic Act 8293 Section 176 provides that “No copyright shall subsist in
any work of the Government of the Philippines. However, prior approval of the
government agency or office wherein the work is created shall be necessary for
exploitation of such work for profit. Such an agency of office may, among other things,
impose as a condition the payment of royalties.
Borrowed materials included in this module are owned by their respective copyright
holders. Every effort has been exerted to reach and seek permission to use these
materials from their respective copyright owners. The University and authors do not claim
ownership over them.
Chapter 10 Arrays
TABLE OF CONTENTS
CHAPTER 7: FUNCTIONS
Lesson 1: MsgBox() Function Page 53
Lesson 2: InputBox() Function Page 56
Lesson 3: String Functions Page 57
Lesson 4: Formatting Functions Page 61
COURSE OVERVIEW
Introduction
development using the VB.NET programming language. This course builds upon
introductory programming concepts and delves into more advanced topics, focusing on
Students will explore the full lifecycle of application development, from designing intuitive
interfaces to writing efficient and maintainable code, managing data, and integrating
projects, students will enhance their problem-solving abilities and prepare for complex
Create intuitive and user-friendly graphical interfaces using Windows Forms and
basic controls, emphasizing usability and user experience design principles.
CHAPTER 1
INTRODUCTION TO VISUAL BASIC
almost similar to Visual Basic 6.0, but has added many new features. Visual Basic has gone
through many phases of development since the days of BASIC that was built for DOS. BASIC
stands for Beginners' All-purpose Symbolic Instruction Code. The program code in Visual
Different software companies had produced many different versions of BASIC for DOS,
such as Microsoft QBASIC, QUICKBASIC, GWBASIC, and IBM BASICA and more. Then,
Microsoft launched the first graphical BASIC, Visual Basic Version 1 in 1991. It is GUI based and
especially developed for MS window. Since then Microsoft slowly phased out the DOS versions
Visual Basic was initially a functional or procedural programming language until the
popular Visual Basic 6. Then, Microsoft transformed Visual Basic into a more powerful object
oriented programming language by launching Visual Basic.Net, from Visual Studio 2002 to the
caught up with other OOP languages such as C++, Java, C# and others. However, you do not
have to know OOP to learn VB.Net. In fact, if you are familiar with Visual Basic 6, you can learn
VB.Net effortlessly because the syntax and interface are almost similar. Visual Studio 2022
Community Edition is available for free download from the Microsoft site as shown below:
https://visualstudio.microsoft.com/downloads/
When you launch Visual Studio 2022, you can see the start page of the Integrated
Recent/Older pane shows the list of projects that you have created recently.
Open a local folder option to open your code in Visual Studio to develop code
The Continue without code option will open the Visual Studio development
environment without any specific project or code loaded. You might choose this
The Create a new project window opens and shows several project templates. A
template contains the basic files and settings required for a given project type. Here, you
can search, filter, and pick a project template. The Create a new project window also
shows a list of your recently used project templates as shown in the figure below.
Forms Application. In the Configure your new project window, you can change the
In the Additional information window, ensure that .NET 8.0 appears in the
Framework dropdown menu, and then select Create. The project will then be created and
The VS2022 IDE Designer interface is shown in figure below. The Designer
consists of the Menu bar, the Toolbars, an empty Form, the Solution Explorer and the
Properties Window.
The Designer Environment that appears on your PC or laptop might not be the
same here, depending how you customize it. You can customize your interface by
dragging the windows and dock them or let them float. You can also hide them. To dock
a window, you drag its title bar and drag it to the side, top or bottom of the workspace or
another window. You can also resize the docked window by dragging the side of the
window. To free up and float the docked window, you just drag its title bar and move it
away from the edge of the workspace. If you do not see a particular window such as the
properties window, you can click on the View menu and click the name of the window, that
Form-The Form is the first place to build your application. It is the place to design the user
interface.
Solution Explorer -The solution explorer displays a list of projects, files and other
components that you can easily browse and access. For example, it displays My Project
Properties Window- This is the place to set the properties of the objects in your
application. The objects include the default form and the controls you place in the form.
The main difference between VB.Net and Visual Basic 6 is that it is a full Object Oriented
Programming Language while VB6 may have OOP capabilities, it is not fully object oriented. In
order to qualify as a fully object oriented programming language, it must have three core
functions to the data. These user-defined data types are called classes. Each class
contains data as well as a set of methods, which manipulate the data. The data
components of a class are called instance variables and one instance of a class is an
object. For example, in a library system, a class could be member, and John and Sharon
Inheritance. Classes are created according to hierarchies, and inheritance allows the
structure and methods in one class to be passed down the hierarchy. That means less
the bottom of a hierarchy, then only the processing and data associated with that unique
step needs to be added. Everything else about that step is inherited. The ability to reuse
created whose exact type is not known until runtime. For example, a screen cursor may
change its shape from an arrow to a line depending on the program mode. The routine to
move the cursor on screen in response to mouse movement would be written for "cursor,"
and polymorphism allows that cursor to take on whatever shape is required at run time. It
VB.Net is a fully Object Oriented Programming Language, just like other OOP such as
C++ and Java. It is different from the earlier versions of VB because it focuses more on the data
itself while the previous versions focus more on the actions. Previous versions of VB are
VB.Net allows users to write programs that break down into modules. These modules
represent the real-world objects; we also call them classes or types. An object can be created out
of a class, it is an instance of the class. A class can also comprise subclass. For example, apple
tree is a subclass of the plant class and the apple in your backyard is an instance of the apple
tree class.
Another example is student class is a subclass of the population class while a student with
the name John is an instance of the student class. A class consists of data members as well as
methods. In VB.Net, the program structure to define a population class can be written as follows:
After you have created the population class, you can create a subclass that inherits the
attributes or data from the population class. For example, you can create a student class that is
a subclass of the population class. Under the student class, you do not have to define any data
fields that were already defined under the population class; you only have to define the data fields
that are different from an instance of the population class. For example, you may want to include
StudentID and Address in the student class. The program code for the StudentClass is as follows:
Activity Sheet
1. Create a timeline highlighting the evolution of Visual Basic.Net. Include major versions
and significant changes in each version.
2. Draw the Visual Studio IDE and describe ten (10) features or tools.
CHAPTER 2
DESIGNING THE INTERFACE
controls to the form and then set their properties. You can add
controls from the Toolbox. To see the Toolbox window, you can
form, just drag the particular control and drop it into the form. After
putting it into the form, you can change its size and position easily.
You can add as many controls as you want, but avoid crowding
the form.
To customize the interface to the users, you need to set the properties of the controls,
from the form itself to the controls you add to the form. You can set the properties of the controls
in the properties window at design time or by using the code. We shall learn how to set the control
name is also Form1. You can change the title of the text to
name that you like, simple click in the box on the right of
In this example, we will create a simple program that will display a welcome message
when you load the form. First, change the properties of the form as follows:
PROPERTY VALUE
Name Form1
Backcolor (Select a background color of your choice)
Font Microsoft Sans Serif Size 10 and Bold
Forecolor White (The color of the displayed text)
Maximizebox False (Cannot be maximized)
Text Visual Studio 2022
Next, insert a label into the form and set its properties as follows:
PROPERTY VALUE
AutoSize False
Name Msglbl
BackColor (Select a background color of your choice)
BorderStyle FixedSingle
Font Microsoft Sans Serif Size 10 and Bold
ForeColor Black
Size 239, 32
Text (Remove or Blank It)
Now press F5 to run the program, you will see the message displayed on the label, as
You can also change the properties of the object using code. The syntax to manipulate
For Example:
The above code sets the text property of TextBox1 to display the text “Welcome to VB.Net”
and set the value of TextBox2 to 100. Other properties you can change to give special effects at
runtime are color, shape, animation effect and so on. For example, the following code will change
the form color to yellow every time the form is loaded. VB.Net uses RGB (Red, Green, Blue) to
determine the colors. The RGB code for yellow is 255, 255, 0. Me in the code refers to the current
form and Backcolor is the property of the form's background color. The formula to assign the RGB
color to the form is Color.FormArbg (RGB code). Now, click on the form to go into the code
window. Next, enter the following code between the opening statement Private Sub and the
Now Press F5 and you will see a form appear with a yellow background.
same effect:
Here are some of the common colors and the corresponding RGB codes. You can always
experiment with other combinations, but remember the maximum number for each color is 255
and the minimum number is 0. The figure below shows some of the common colors with their
corresponding codes.
Activity Sheet
1. Design a user interface for a basic application by adding various controls like buttons, text
boxes, and labels to the form.
2. Customize the appearance of the controls added in the previous activity by modifying
properties like size, color, and text through the Properties window.
3. Write code to dynamically change the properties of controls based on user interactions,
such as changing the color of a button when clicked.
CHAPTER 3
WRITING THE CODE
System.Windows.Forms.Form.
The other events associated with the Form1 class are click, DoubleClick, DragDrop, Enter
and more, as shown in Figure below (It appears when you click on the upper right pane of the
code window).
Now you are ready to write the code for the event procedure so that it will do something
more than loading a blank form. The structure of the code takes the following form:
You have to enter the code between Private Sub and End Sub.
When you press F5 to run the program, the output is shown in Figure below:
The first line of the code will change the title of the form to “My First VB.Net Program”, the
second line will change the foreground object to yellow( in this case, it is a label that you insert
into the form and change its name to Foreground) and the last line changes the background to
blue color. The equal sign in the code is to assign something to the object, like assigning yellow
color to the foreground of the Form1 object (or an instance of Form1). Me is the name given to
the Form1 class. We can also call those lines as Statements. Therefore, the actions of the
program will depend on the statements entered by the programmer. Here is another example:
In this example, you insert one command button into the form and rename its caption as
Show Hidden Names. The keyword Dim is to declare variables name1, name2 and name3 as
string, which means they can only handle text. The function MsgBox is to display the names in a
message box that are joined together by the "&" signs. The output is shown in Figure below:
Activity Sheet
1. Create a form with different controls (buttons, text boxes, etc.) and implement event
handlers for different events (click, text change) to understand how event-driven
programming works.
CHAPTER 4
MANAGING VB.NET DATA
In our daily life we come across many types of data. For example, we need to handle data
such as names, addresses, money, dates, stock quotes, statistics and more every day. Similarly,
in Visual Basic.Net, we have to deal with all sorts of data; some are numeric in nature while some
are in the form of text or other forms. VB.Net divides data into different types so that it is easier to
Visual Basic classifies the information mentioned above into two major data types; namely
Numeric data types are types of data that consist of numbers, which you can compute
them mathematically with various standard operators such as add, minus, multiply, divide and so
on. Examples of numeric data types are your examination marks, your height and your weight,
the number of students in a class, share values, price of goods, monthly bills, fees and more.
In Visual Basic, we divide numeric data into seven types, depending on the range of values
they can store. Calculations that only involve round figures or data that do not need precision can
use Integer or Long integer in the computation. Programs that require high precision calculation
need to use Single and Double decision data types, we also call them floating-point numbers. For
currency calculation, you can use the currency data types. Lastly, if even more precision is
required which involve many decimal points, we can use the decimal data types.
Nonnumeric data types are data that cannot be manipulated mathematically using
standard arithmetic operators. The non-numeric data comprises text or string data types, the Date
data types, the Boolean data types that store only two values (true or false), Object data type and
Literals are values that you assign to a data. In some cases, we need to add a suffix
behind a literal so that VB.NET can handle the calculation more accurately. For example, we can
In addition, we need to enclose string literals within two quotations and date and time
literals within two # sign. Strings can contain any characters, including numbers. The following
memberName="Turban, John."
TelNumber="1800‐900‐888‐777"
LastDay=#31‐Dec‐00#
ExpTime=#12:00 am#
Lesson 2: Variables
Variables are like mail boxes in the post office. The contents of the variables change every
now and then, just like the mail boxes. In term of VB.NET, variables are areas allocated by the
computer memory to hold data. Like the mail boxes, each variable must be given a name. To
Variable Names
No spacing is allowed
Examples of valid and invalid variable names are displayed in Table below:
VALID INVALID
My_Name My.Name
ThisDate 1NewDate
Long_Name_Can_beUSE His&Her
Declaring Variables
In Visual Basic, one needs to declare the variables before using them by assigning names
and data types. If you fail to do so, the program will show an error. They are normally declared in
the general section of the codes' windows using the Dim statement.
Example:
You may also combine them in one line, separating each variable with a comma, as follows:
For string declaration, there are two possible formats, one for the variable-length string and
another for the fixed-length string. For the variable-length string, just use the same format as
example 4.1 above. However, for the fixed-length string, you have to use the format as shown
below:
Example:
After declaring various variables using the Dim statements, we can assign values to those
variables.
The variable can be a declared variable or a control property value. The expression could
be a mathematical expression, a number, a string, a Boolean value (true or false) and more. The
Lesson 3: Constants
Constants are different from variables in the sense that their values do not change during
Example:
Activity Sheet
1. Develop a small application that demonstrates the use of different data types (e.g., Integer,
String, Boolean) and allows users to input and display values.
2. Write a program that performs basic arithmetic operations using variables and displays
the results. Include input from the user to practice variable assignment.
3. Create a program that uses constants for fixed values (e.g., mathematical constants).
CHAPTER 5
MATHEMATICAL OPERATIONS AND STRING MANIPULATIONS
Computers can perform mathematical calculations much faster than human beings.
However, the computer itself will not be able to perform any mathematical calculations without
receiving instructions from the programmer. In VB.NET, we can write code to instruct the
division and other kinds of arithmetic operations. In order for VB.NET to carry out arithmetic
calculations, we need to write code that involves the use of various arithmetic operators. The
VB.NET arithmetic operators are very similar to the normal arithmetic operators, only with slight
variations. The plus and minus operators are the same while the multiplication operator use the *
symbol and the division operator use the / symbol. The list of VB.NET arithmetic operators are
Example:
In this program, you need to insert two Textboxes, four labels and one button. Click the
button and enter the code as shown below. When you run the program, it will perform the four
basic arithmetic operations and display the results on the four labels.
that come in the form of non-numeric types such as name, address, city, book title and etc.
Strings can be manipulated using the & sign and the + sign, both perform the string
concatenation which means combining two or more smaller strings into a larger string. For
example, we can join "Visual" and "Basic" into "Visual Basic" using "Visual"&"Basic" or "Visual
Example:
This code will produce an error because of data mismatch. However, using & instead of + will be
all right. You can also combine more than two strings to form a larger string, like the following
example:
A function is similar to a normal procedure but the main purpose of the function is to accept
a certain input and return a value, which is passed on to the main program to finish the execution.
VB.NET has numerous built-in string manipulation functions but we will only discuss a few here.
Len Function
The length function returns an integer value that is the length of a phrase or a
sentence, including the empty spaces. The format is: Len (“Phrase”)
Example:
The output:
Right Function
The Right function extracts the right portion of a phrase. The format for Visual
Basic 6 is: Right (“Phrase”, n) where n is the starting position from the right of the phase
For example:
However, this format is not applicable in VB.NET. In VB.NET, we need to use the following
format:
The reason of using the full reference is because many objects have the Right
properties so using Right on its own will make it ambiguous to VB.NET. The program
below will return four right most characters of the phrase entered into the textbox:
Left Function
The Left function extract the left portion of a phrase. The format is:
For example:
Activity Sheet
1. Design a simple calculator application that performs basic arithmetic operations (addition,
subtraction, multiplication, division) and displays the results.
2. Write a program that concatenates strings using both + and & operators and compares
their outputs.
3. Create a text processing program that uses built-in functions to manipulate and format
strings.
CHAPTER 6
VB.NET - BASIC CONTROLS
An object is a type of user interface element you create on a Visual Basic form by using a
toolbox control. In fact, in Visual Basic, the form itself is an object. Every Visual Basic control
All the Visual Basic Objects can be moved, resized or customized by setting their
properties. A property is a value or characteristic held by a Visual Basic object, such as Caption
or Fore Color.
Properties can be set at design time by using the Properties window or at run time by
where
For example:
You can set any of the form properties using Properties Window. Most of the properties
can be set or read during application execution. You can refer to Microsoft documentation for a
complete list of properties associated with different controls and restrictions applied to them.
variable. There are mainly two categories of methods you will use in your classes:
If you are using a control such as one of those provided by the Toolbox, you can call any
of its public methods. The requirements of such a method depend on the class being used.
If none of the existing methods can perform your desired task, you can add a method to a
class.
For example, the MessageBox control has a method named Show, which is called in the code
snippet below:
An event is a signal that informs an application that something important has occurred.
For example, when a user clicks a control on a form, the form can raise a Click event and call a
procedure that handles the event. There are various types of events associated with a Form like
Following is the default structure of a form Load event handler subroutine. You can see
this code by double clicking the code which will give you a complete list of the all events
event. Similar way, you can check stub code for click, double click. If you want to initialize some
variables like properties, etc., then you will keep such code inside Form1_Load() subroutine.
Here, important point to note is the name of the event handler, which is by default Form1_Load,
but you can change this name based on your naming convention you use in your application
programming.
VB.Net provides a huge variety of controls that help you to create rich user interface.
Functionalities of all these controls are defined in the respective control classes. The control
classes are defined in the System.Windows.Forms namespace. The following table lists some
TOOL DESCRIPTION
Forms The container for all the controls that make up the user interface.
TextBox It represents a Windows text box control.
Label It represents a standard Windows label.
Button It represents a Windows button control.
ListBox It represents a Windows control to display a list of items.
ComboBox It represents a Windows combo box control.
RadioButton It enables the user to select a single option from a group of choices
when paired with other RadioButton controls.
CheckBox It represents a Windows CheckBox.
PictureBox It represents a Windows picture box control for displaying an image.
ProgressBar It represents a Windows progress bar control.
This program consists of four (4) Common Controls in the Toolbox with two (2)
message that includes the text entered in the TextBox. The MessageBox
MESSAGE BOX".
btnClear button is clicked. It clears the text from the TextBox using either
the Clear method or the Null String (“”). It then sets the Focus back to
the TextBox.
This program is a simple pizza order form that allows the user to select the variety,
size, and crust style of a pizza. The selected options are then displayed in labels on the
selected item in the ComboBox changes. Updates the lblVariety label to display
item in the ListBox changes. Updates the lblSize label to display the selected
pizza size.
clicked. Resets the selection of cboVariety, lstSize, and the RadioButtons for
This program uses different visual basic tools that can be used when dealing with
Date and Time. It consists of four separate sub-programs that will be discussed below.
This code snippet is an event handler that updates a label to display a formatted date
Event Handler subroutine is triggered when the value of the DateTimePicker control is
changed by the user. It formats the selected date from the DateTimePicker and displays
it in a label.
dtpBday - This is the DateTimePicker control where the user selects a date.
lblBday - This is the label control where the formatted date will be displayed.
Format(dtpBday.Value, "dddd, MMMM dd, yyyy") - This function formats the date
When the user selects a new date in the DateTimePicker, the label will be updated to
This code snippet handles the DateChanged event of a MonthCalendar control. When
the selected date range in the calendar changes, it updates two labels to display the start
Handler subroutine is triggered when the date selection in the MonthCalendar1 control
changes. It updates the labels to show the start and end dates of the selected range.
MonthCalendar1. This is the MonthCalendar control that allows the user to select
lblFrom. This label displays the start date of the selected range.
lblTo. This label displays the end date of the selected range.
When the user selects a new date range in the MonthCalendar, the lblFrom label is
updated with the start date of the selection, and the lblTo label is updated with the end
This code snippet handles the Tick event of a Timer control. It updates a label to display
the current date and time every time the timer ticks. Unlike the other tools, the Timer is
not visible in the Form during the design and the runtime. This is because VB.Net controls
like the Timer runs in the background. As shown in the figure below, the Timer control
The tmrDateTime_Tick Event Handler subroutine is triggered every time the Timer ticks,
which occurs at intervals specified by the timer's Interval property. Then updates the text
tmrDateTime. This is the Timer control that generates Tick events at regular
intervals.
lblDateTime. This is the label control that will display the current date and time.
Format(Date.Now). This function formats the current date and time as a string. By
default, Format will use the general date/time pattern (short date and long time).
This last code snippet handles the event of a button that sets the System Date and Time
txtTime.Text. This retrieves the text from the txtTime textbox, which should
This code snippet provides functionality that allows the user to browse for an Image File
triggered when the "Browse Picture" button (btnBrowse) is clicked. It opens a File Dialog
(ofdPicture) to allow the user to select an image file. After the user selects an image file,
the ImageLocation property of the PictureBox (picProfile) is set to the selected file's path,
This code snippet handles the Scroll events of Horizontal and Vertical Scroll Bars to
dynamically adjust the Width and Height of the PictureBox. When the user scrolls the
Horizontal Scroll Bar (hsbWidth), the width of the PictureBox (picProfile) changes
according to the current value of the scroll bar. If hsbWidth.Value is 200, the width of
picProfile will be set to 200 pixels. Similarly, when the user scrolls the vertical scroll bar
(vsbHeight), the height of the PictureBox (picProfile) changes according to the current
value of the scroll bar. If vsbHeight.Value is 300, the height of picProfile will be set to 300
pixels. This functionality allows the user to dynamically resize the PictureBox by adjusting
Activity Sheet
1. Create a program with a variety of basic controls and implement functionality to showcase
how each control can be used in a real application.
CHAPTER 7
FUNCTIONS
A function is similar to a normal procedure but the main purpose of the function is to accept
a certain input and return a value, which is passed on to the main program to finish the execution.
There are two types of functions, the built-in functions (or internal functions) and the functions
The objective of MsgBox is to produce a pop-up message box and prompt the user to click
The first argument, Prompt, displays the message in the message box. The Style Value
determines the type of command buttons appear on the message box, as shown in Table below.
The Title argument will display the title of the message board.
STYLE
NAME CONSTANT BUTTONS DISPLAYED
VALUE
0 vbOkOnly Ok button
1 vbOkCancel Ok and Cancel buttons
2 vbAbortRetryIgnore Abort, Retry and Ignore buttons
3 vbYesNoCancel Yes, No and Cancel buttons
4 vbYesNo Yes and No buttons
5 vbRetryCancel Retry and Cancel buttons
We can use named constant in place of integers for the second argument to make the programs
more readable.
In fact, VB will automatically shows up a list of names constant where you can select one of them.
For example:
and
Note: yourMsg is a variable that holds values that are returned by the MsgBox() function.
The type of buttons being clicked by the users determines the values. It has to be declared
as Integer data type in the procedure or in the general declaration section. The table below
STYLE
NAME CONSTANT BUTTON CLICKED
VALUE
1 vbOk Ok button
2 vbCancel Cancel button
3 vbAbort Abort button
4 vbRetry Retry button
5 vbIgnore Ignore button
6 vbYes Yes button
7 vbNo No button
To make the message box looks more sophisticated, you can add an icon besides the message.
There are four types of icons available in VB.NET as shown in Table below.
16 vbCritical
32 vbQuestion
48 vbExclamation
64 vbInformation
Example:
An InputBox( ) function allows the user to enter a value or a message in a text box. The
format is as follows:
userMsg is a variant data type but typically it is declared as string, which accepts the message
default-text - The default text that appears in the input field where the user may change
x-position and y-position - the position or the coordinates of the input box.
Example:
The Mid function is to retrieve a part of text from a given phrase. The format of the Mid
Function is:
where:
position is the starting position of the phrase from which the retrieving process
begins.
Example:
The Right function extracts the right portion of a phrase. The format is:
where n is the starting position from the right of the phase where the portion of the phrase
is to be extracted.
Example:
The Left function extracts the left portion of a phrase. The format is:
where n is the starting position from the left of the phase where the portion of the phrase
is to be extracted.
Example:
The Trim function trims the empty spaces on both side of the phrase. The format is:
For example:
The Ltrim function trims the empty spaces of the left portion of the phrase. The format is:
For example:
The Rtrim function trims the empty spaces of the right portion. The format is:
For example:
The InStr function looks for a phrase that is embedded within the original phrase and
returns the starting position of the embedded phrase. The format is:
Where n is the position where the Instr function will begin to look for the embedded phrase.
For example:
The Ucase function converts all the characters of a string to capital letters. On the other
hand, the Lcase function converts all the characters of a string to small letters.
For example:
The Chr function returns the string that corresponds to an ASCII code while the
Asc function converts an ASCII character or symbol to the corresponding ASCII code.
ASCII stands for “American Standard Code for Information Interchange”. Altogether
there are 255 ASCII codes and as many ASCII characters. Some of the characters may
not be displayed as they may represent some actions such as the pressing of a key or
The Format function is a very powerful formatting function that can display the numeric
values in various forms. A pre-defined format function is built into the software and does not need
to be created by a programmer. Pre-defined functions often exist to carry out common tasks, such
as: finding an average number or determining the length of a string. The format of the pre-defined
Where n is a number and the list of style arguments is given in the table below.
STYLE
DESCRIPTION EXAMPLE
ARGUMENT
General Displays the number without having Format(8972.234, “General
Number separators between thousands Number”)=8972.234
Displays the number without having
Format(8972.2,
Fixed separators between thousands and
“Fixed”)=8972.23
rounds it up to two decimal places.
Displays the number with separators or
Format(6648972.265,
Standard separators between thousands and
“Standard”)= 6,648,972.27
rounds it up to two decimal places.
Display the number with the dollar sign
in front has separators between Format(6648972.265,
Currency
thousands as well as rounding it up to “Currency”)= $6,648,972.27
two decimal places.
Converts the number to the percentage
Format(0.56324,
Percent form, displays a % sign, and rounds it up
“Percent”)=56.32%
to two decimal places.
Example:
Other than using the Format function, VB.Net has introduced the ToString method to
format output. It is used together with the standard numeric format specifiers such as “c” which
stand for currency. Some of the most common numeric specifiers are listed in the table below:
FORMAT
DESCRIPTION EXAMPLES
SPECIFIER
- Displays a currency value. The
default is the US currency $ and in Dim myNum as Single =2011.123456
two decimal places.
- To display other currency, add a myNum.ToString("C")= $2011.12
culture code that specifies a country.
"C" For example, for Great Britain, you myNum.ToString("C4")= $2011.1234
add en-GB using the keyword
“CultureInfo.CreateSpecificCulture” myNum.ToString("C3", CultureInfo.
- Displays number of decimal digits by CreateSpecificCulture(”en-GB”))=
placing the digit after C, for example, £2011.123
C4 for decimal places.
Express a Number with in integer form
Dim myNumber As Integer = 2012.2344
"D" or "d" with specified number of digits. For
myNumber.ToString("D4")=2012
example, D4 means four-digit integer.
Express a number in exponential form
Dim myNumber As Double = 2012.2344
"E" or "e" with specified number of decimal
myNumber.ToString("e3")= 2.012e+003
places.
Mutiply a number by 100 and displayed Dim myNumber As Double = 0.23456
"P" or "p"
with a percentage symbol %. myNumber.ToString("P2")= 23.46%
Dim myNumber As Double=0.23456
"F" or "f" Specifies number of decimal points. myNumber.ToString(“F”)=0.23
myNumber.ToString(“F3”)=0.235
The ToString method together with the currency specifier “C” displays the output with the currency
sign $ and in two decimal places. The default currency is the currency used by your computer
system; in this case, it is the US currency. If you are not sure of what default currency your
computer uses, you can add the keyword “CultureInfo.CurrentCulture” to the ToString method as
Activity Sheet
1. Develop a program that uses the MsgBox() function to display different types of message
boxes (e.g., information, warning, question) based on user interactions.
2. Write a program that prompts the user for input using the InputBox() function and
processes the input to perform a specific task.
3. Create a program that demonstrates various string functions (e.g., Length, Trim, Split) and
their usage for manipulating and analyzing strings.
4. Develop a program that uses formatting functions (e.g., Format(), ToString()) to display
numbers and dates in different formats.
CHAPTER 8
CONDITIONAL STATEMENTS
Decision making process is an important part of programming because it will help solve
practical problems intelligently so that it can provide useful output or feedback to the user. For
example, we can write a program that can ask the computer to perform certain task until a certain
condition is met, or a program that will reject non-numeric data. In order to control the program
flow and to make decisions, we need to use the conditional operators and the logical operators
The Conditional Operators are powerful tools that can compare values and then decide
what actions to take, whether to execute a program or terminate the program and more. They are
also known as numerical comparison operators. Normally we use them to compare two values to
see whether they are equal or one value is greater or less than the other value. The comparison
will return true or false result. These operators are shown in table below.
OPERATORS MEANING
= Equal To
> Greater Than
< Less Than
>= Greater Than or Equal To
<= Less Than or Equal To
<> Not Equal To
Sometimes we might need to make more than one comparison before a decision can be
made and an action taken. In this case, using numerical comparison operators alone is not
sufficient, we need to use additional operators, and they are the logical operators. The logical
OPERATORS MEANING
AND Both conditions must be True
OR One condition must be True
NOT Negates Truth
Normally the above operators are used to compare numerical data. However, you can
also compare strings with the above operators. In making strings comparison, there are certain
rules to follows: Upper case letters are less than lowercase letters, "A"<"B"<"C"<"D"...<"Z" and
Lesson 1: If … Then
This is the simplest control structure which ask the computer to perform a certain
action specified by the VB expression if the condition is true. However, when the condition
is false, no action will be performed. The general format for the if...then... statement is:
Example:
This code snippet handles the FormClosing event of a form. When the form is about to close, it
displays a message box asking the user for confirmation. If the user chooses "No," the form
This functionality is useful for preventing accidental closure of the application, giving the user a
Using just If...Then statement is not very useful in programming and it does not provides
choices for the users. In order to provide a choice, we can use the If...Then...Else Statement. This
control structure will ask the computer to perform a certain action specified by the VB expression
if the condition is true. When the condition is false, an alternative action will be executed. The
Example:
This code snippet handles the CheckedChanged event for a CheckBox (chkEULA). If the user
checks the CheckBox, the Button (btnSubmit) is enabled, allowing the user to proceed with
submission. Otherwise, if the user unchecks the checkbox, the btnSubmit button is disabled.
If there are more than two alternatives, using just If...Then...Else statement will not be
enough. In order to provide more choices, we can use the If...Then...ElseIf Statement or the
Ladderized If’s. The general format for the if...then... Else statement is:
Example:
This code snippet handles the Click event of a button. When the button is clicked, it checks the
value entered. The If, ElseIf, and Else statements are used to check the value of the TextBox.
Depending on the value, the Label is set to the corresponding day of the week. However, if the
value is not between 1 and 7, a message box with the message "INVALID INPUT" is displayed.
Lesson 4: Nested If
conditions. It involves placing one If statement inside another If statement. This allows the
program to evaluate multiple layers of conditions and execute the corresponding actions based
on whether the conditions are true or false. The general format for a Nested If statement is:
The nested If statement is particularly useful when more than two conditions need to be tested,
and the conditions depend on each other. This control structure enables the programmer to create
Example:
The code snippet demonstrates the use of a nested If statement to evaluate eligibility for an
incentive based on user input. In the outer If Statement, it checks if the text in the ComboBox. If
the condition is true, it proceeds to the nested If statement. Otherwise, it displays a Message Box
stating that the user is not eligible for the incentive. Inside the outer If block, it checks the next
condition. If true, it displays a Message Box stating the user is eligible for the incentive. If false, a
The revised code below utilizes Exit Sub to avoid duplicate Message Boxes for not being eligible.
After displaying the Message Box stating that the user is eligible for the incentive, it then exits the
subroutine using the Exit Sub. However, if one of the conditions are not met, it does not do
anything and proceeds to the next part of the code, the Message Box for ineligibility.
Alternatively, the Nested If can be converted into a simpler If Statement through the use of the
Logical Operators. The code below checks both conditions at the same time using the AND
operator. Using this operator, both the conditions must be met to display the Message Box for the
The Select Case control structure is slightly different from the If...ElseIf control structure.
The difference is that the Select Case control structure basically only make decision on one
expression or dimension while the If...ElseIf statement control structure may evaluate only one
expression. Each If...ElseIf statement may also compute entirely different dimensions. Select
Case is preferred when there exist many different conditions because using If...Then...ElseIf
statements might become too messy. The Select Case ...End Select control structure is:
Example:
This code snippet uses a Select Case statement to show the equivalent description of a value
entered in the TextBox. It compares the value of the expression against each Case condition in
the list. If the value does not match any of the specified cases, the Case Else block executes.
Here’s another example of using the Select Case Statement with range of values:
Activity Sheet
1. Write a program that uses simple If … Then statements to make decisions based on user
input.
2. Create a program that uses If … Then … Else statements to handle multiple conditions
and provide different outputs based on those conditions.
4. Write a program that uses nested If statements to handle complex conditions and
scenarios.
5. Create a program that uses the Select Case statement to manage multiple choices or
conditions that is more efficient than the ladderized If statements.
CHAPTER 9
LOOPING STATEMENTS
Visual Basic allows a procedure to repeat many times as long as the processor could
support. We call this looping. Looping is required when we need to process something repetitively
until a certain condition is met. For example, we can design a program that adds a series of
numbers until it exceed a certain value, or a program that asks the user to enter data repeatedly
until he or she keys in the word 'Finish'. In Visual Basic, we have three types of Loops, they are
the For...Next loop, the Do loop and the While...End While loop.
The For...Next loop is a control flow statement for specifying iteration, which allows code
to be executed repeatedly. The loop iterates over a range of values, executing the statements
within the loop for each value in the range. The format is:
Example:
In the above example, the For...Next loop is used to iterate from 1 to 10. The For...Next loop in
operates by initializing a loop variable x to a starting value, in this case, 1. It then evaluates a
condition to check if the current value of x is less than or equal to an end value, here 10. If the
condition is true, the loop executes the statements within its body, concatenating the current value
of x to the lblOutput.Text property along with a space. After executing the loop body, the loop
variable x is incremented by the step value, which is 1. The condition is re-evaluated, and if x is
still less than or equal to 10, the loop runs again. This process continues until x exceeds 10, at
Sometimes the user might want to get out from the loop before the whole repetitive process is
completed. The command to use is Exit For. To exit a For….Next Loop, you can place the Exit
For statement within the loop; and it is normally used together with the If…..Then… statement.
The While...End While loop in VB.NET repeatedly executes a block of code as long as a
specified condition remains true. Unlike the For...Next loop, this loop does not have a built-in
that affect the loop's condition must be explicitly defined within the loop. The format is:
Example:
In this example, the While...End While loop begins by initializing the value of x to 1, then evaluating
a condition. If the condition evaluates to True, the program enters the loop and executes the block
of statements inside it. After executing these statements, the loop returns to the beginning and
re-evaluates the condition. If the condition is still True, the loop runs the block of code again. This
cycle of checking the condition and executing the code continues until the condition evaluates to
False. Once the condition becomes False, the loop terminates. If we run the program, we will
Lesson 3: Do Loop
The structure of a Do Loop is very similar to the While….End While. However, there are
numerous variations in this kind of loop. Following are the different Do Loop formats:
Example:
This program demonstrates four different Do loop formats: Do While, Do Loop While, Do Until,
and Do Loop Until. In the Do While loop, the condition is evaluated before the loop starts, and it
continues running as long as the condition is true. The Do Loop While loop, on the other hand,
executes its statements at least once before checking the condition at the end of the loop,
continuing if the condition is true. The Do Until loop evaluates the condition before the loop starts,
running until the condition becomes true. Conversely, the Do Loop Until loop executes its
statements at least once before checking the condition at the end, repeating until the condition is
true. All four loops in the program increment the variable x from 1 to 10, just like in the For and
While loop, but they differ in when they evaluate their respective conditions relative to the loop's
execution.
Loops can be placed inside another loop, allowing for more complex iteration processes.
In a nested loop, the inner loop executes completely for each iteration of the outer loop. This
structure is useful for tasks that involve multiple dimensions, such as iterating through a two-
dimensional array or performing repeated actions within repeated actions. Nested loops can be
of the same type (e.g., a For loop inside another For loop) or different types (e.g., a While loop
inside a For loop), providing flexibility for various scenarios. However, it's important to manage
them carefully to avoid excessive computational complexity and ensure the logic is clear and
efficient.
Example:
In this program, two For loops are nested to create a multiplication table. The outer loop iterates
through the numbers 1 to 10, representing the multiplicands, while the inner loop iterates through
the numbers 1 to 10, representing the multipliers. For each combination of x (the multiplicand)
and y (the multiplier), the product x * y is calculated and attached with the contents of the TextBox,
followed by a Tab character for formatting. After the inner loop completes, a newline character
(vbCrLf) is added to the TextBox to move to the next line for the row of the multiplication table to
be properly formatted.
The program above can also be created using different loop formats just like the code below,
which demonstrates the same multiplication table using While and Do loop:
Activity Sheet
2. Write a program that uses a While…End While loop to perform actions until a specific
condition is met.
3. Create a program that uses a Do Loop to continuously perform an action until a condition
changes.
4. Implement a program that uses nested loops to perform tasks involving multiple levels of
repetition.
CHAPTER 10
ARRAYS
By definition, an array is a list of variables with the same data type and name. When we
work with a single item, we only need to use one variable. However, if we have a list of items,
which are of similar type to deal with, we need to declare an array of variables instead of using a
variable for each item. For example, if we need to enter one hundred names, it is difficulty to
declare 100 different names; this is a waste of time and efforts. Therefore, instead of declaring
one hundred different variables, we need to declare only one array. We differentiate each item in
the array by using subscript, the index value of each item, for example name(0), name(1),name(2)
.......etc. , which will make declaring variables streamline and much systematic.
We can use Public or Dim statement to declare an array just as the way we declare a
single variable. The Public statement declares an array so that it can be used throughout the
entire application while the Dim statement declares an array that can be used only in a local
procedure.
of items or a table that consists of one row of items or one column of items. The table below
Example 1.1:
Example 1.2:
The statement above declares an array that consists of the first element starting from
This program uses a one-dimensional array to store and display names entered by the user.
When the Button is clicked, the user is prompted to enter names into the array using an InputBox.
After all names are entered, each are assigned to specific indexes in the array as shown in the
table below:
Index 0 1 2 3 4
Value Juan Pedro Maria Dan Chris
When the Button is clicked, the names stored in the array are displayed in the ListBox.
A two-dimensional array in Visual Basic is like a table or a matrix with rows and columns.
It is useful for storing and manipulating data that naturally fits into a grid-like structure, such as a
spreadsheet or a game board. You can declare a two-dimensional array by specifying the number
of rows and columns it will have. The general format to declare a two dimensional array is:
The total number of elements will be (sub1+1)x(sub2+1). For example, Dim Score(2,3) will
In this example, we want to key in the examination marks for five students and four subjects.
Since we are handling two variables here, i.e. name and subject, we declare a two dimensional
array (Scores (4,3). The first dimension represents student names and the second dimension
represents the subjects. Combining both produces the scores for each student for each subject.
For example, the score for the first student for the first subject will be score (0, 0). We let the user
enter the student names, subject titles as well as the scores. Then, we used two nested loops
involving the For...Next structure. The first loop gets the students’ names and the second loop
gets the students’ scores for the four subjects. To achieve the purpose, we introduced a one
dimensional array StudentName(4) to store the names of the five students. We also introduced a
one dimensional array Mark(3) to store the mark of every subject for every student .After entering
the name of the students and their scores, we get something like this:
Activity Sheet
1. Develop a program that uses a one-dimensional array to store and manipulate a series of
related values.
2. Create a program that uses a two-dimensional array to represent and manipulate data in
a grid format.
CHAPTER 11
MENUS AND TOOLBAR
Menus and toolbars remain as the standard features of all windows applications despite
the development of more sophisticated GUI. The menu bar contains menus, which contain groups
of menu items that the user can used to execute certain commands to perform certain tasks like
opening a file, saving a file, printing a page, formatting a page and more. On the other hand, a
standard toolbar displays icons that can be used to open a file, save a file, viewing a document,
In this chapter, I will show you how to add Menus and icons to the toolbar of your
applications. We will use the text editor and execute the commands using the menus and the
toolbar icons. We shall also make this program more powerful by enabling it to format the text as
well as to print out the text from the text file. For this project, we will add MenuStrip1, ToolStrip1,
First, drag the Menu Strip from the toolbox and position it at the top part of the form. Add
the first top-level menu by typing it in the textbox that appears with a blurred text “Type Here”.
The first menu you will add is File, but you type it with the ampersand sign in front, like this, &File.
The reason is the ampersand sign will underline the letter F, File at runtime so that the user can
The second top-level menu that we shall add is Format, which we type it as &Format. The
next step is to add menu items to the File and the Format Menu. The three menu items that we
are going to add to the File menu are Open, Save, Print and Exit, type them as &Open, &Save,
&Print and E&xit. The menu items that we will add to the Format menu are Font (type it as Fo&nt),
Font Color (type it as Font &Color) and Background Color (type it as &Background Color). The
menu items can be moved upward or downward easily by dragging them. They can be deleted
easily by pressing the right mouse button and then click deleted in the pop-up dialog.
When we run the finished design, we shall see a window application that comprises menus
and menu items, as shown in Figure below. Notice the underlined characters of the menu items.
The menu item Open should execute a command that will allow the user to choose a file
from a storage source and open it via a pop-up dialog. The code is the same as the code to read
text file in the previous chapter. It involves the use of the OpenFileDialog control. Now, double
click on the Open menu item and enter the code as follows:
Remember place the statement Imports System.IO before Public Class Form1 so that the
program is able to read the file. The open dialog is shown in Figure below.
Menu item Save executes command that writes file to the computer storage unit. The code is the
same as the code for writing file in the previous chapter. Click on the Save menu item and enter
Writing code for the Print command requires the use of the PrintDialog control. It comprises two
parts, the first part is to presents a print dialog for the user to set the options to print and second
part is to print the document. Click on the print menu item and enter the following codes:
Still using the same file, we shall now add some toolbar items in form of icons. You can
look up for some free icons sites in Google to download the icons you intend to place on your
toolbar. To add icon to the menu, right click on the menu and choose properties window from the
dropdown list, then proceed to change the default image by clicking the three-dot button on the
right of the image property. Choose an icon or image file from your hard drive that you wish to
First, add the ToolStrip from the toolbox to the form. To add items to the toolbar, click on
the small icon on the leftmost corner of the toolbar and choose Button from the dropdown list, as
Using the same method in the MenuStrip, configure the toolbar item and set their Image or Icon
properties as well as the ToolTipText to “Save File”. The ToolTipText is to display text when the
user places his or her mouse over the toolbar icon as shown in the figure below. The purpose is
to provide information about the action that can be executed by clicking the icon.
Next, we shall include all commands that we have in our MenuStrip and write code for every item
on the tool bar. Additional codes for the other button are provided below:
Font Color
Background Color
Activity Sheet
1. Design a form with a menu strip and add various menu items to it. Implement functionality
for each menu item to demonstrate how menus can be used in an application.
2. Create a form with a toolbar and add icons for common actions. Implement event handlers
to perform actions when toolbar buttons are clicked.
CHAPTER 12
WORKING WITH DATABASE
Applications communicate with a database, firstly, to retrieve the data stored there and
present it in a user-friendly way, and secondly, to update the database by inserting, modifying
and deleting data. Microsoft ActiveX Data Objects.Net ADO.Net is a model, a part of the .Net
framework that is used by the .Net applications for retrieving, accessing and updating data.
ADO.Net object model is nothing but the structured process flow through various
The data residing in a data store or database is retrieved through the data provider.
Various components of the data provider retrieve data for the application and update data. An
Datasets store data in a disconnected cache and the application retrieves data from it.
Data readers provide data to the application in a read-only and forward-only mode.
A data provider is used for connecting to a database, executing commands and retrieving
data, storing it in a dataset, reading the retrieved data and updating the database. The data
3) DataReader. Data reader is used to retrieve data from a data source in a read-only and
forward-only mode.
4) DataAdapter. This is integral to the working of ADO.Net since data is transferred to and
from a database through a data adapter. It retrieves data from a database into a dataset
and updates the database. When changes are made to the dataset, the changes in the
The .Net Framework data provider for SQL Server - provides access to Microsoft SQL
Server.
The .Net Framework data provider for OLE DB - provides access to data sources exposed
The .Net Framework data provider for ODBC - provides access to data sources exposed
by ODBC.
The .Net Framework data provider for Oracle - provides access to Oracle data source.
The EntityClient provider - enables accessing data through Entity Data Model EDM
applications.
Lesson 3: DataSet
that are retrieved from a database. When a connection is established with the database, the data
adapter creates a dataset and stores data in it. After the data is retrieved and stored in a dataset,
the connection with the database is closed. This is called the 'disconnected architecture'. The
dataset works as a virtual database containing tables, rows, and columns. The following diagram
The DataSet class is present in the System.Data namespace. The following table describes all
DataTableCollection. It contains all the tables retrieved from the data source.
set.
dataset. It is used to relate two DataTable objects to each other through the DataColumn
objects.
DataRow. It represents a row in the DataTable. The DataRow object and its properties
and methods are used to retrieve, evaluate, insert, delete, and update values in the
DataTable. The NewRow method is used to create a new row and the Add method adds
Here, dbCON is the connection object, and Open() is called to initiate the connection,
B. Displaying Records
DataAdapter. The DataAdapter uses an SQL SELECT statement to retrieve all records
from the tblINVENTORY table and fills the DataSet. The data is then bound to a data grid
This method not only displays the records but also updates text boxes with the first
The application includes navigation buttons that allow users to move through
records in the dataset. The RecPointer variable keeps track of the current record index.
The btnMF, btnMP, btnMN, and btnML correspond to buttons for moving to the first,
These methods call Display_Records() to update the display based on the new
RecPointer value. If we run the program, we will have the sample output as shown below.
Here, we will delve into the core functionalities of managing inventory records within the
vb.net program. We will cover essential operations such as adding new records, editing existing
ones, searching for specific entries, and deleting records from the database. These actions are
To add a new record, we will be using the "Add" button (mnuAdd). This button
unlocks the text boxes for data entry and prepares the interface for inputting a new record.
The text boxes are cleared to prevent any existing data from being overwritten, and the
mnuSave button's text is changed to "Save" to indicate that the data will be saved as new
The Unlock_Textboxes method enables the text boxes for user input, and
Clear_Textboxes ensures that the text boxes are empty, preparing the form for new data
entry. The entered data is inserted into the database using an INSERT INTO SQL
command.
B. Updating Records
To modify an existing record, the user needs to select the record and click the
"Edit" button (mnuEdit). This will unlock the text boxes for editing and sets the mnuSave
button's text to "Update," indicating that changes will be saved to the existing record.
The PCode variable stores the current product code for reference. This ensures that the
correct record will be updated in the database. After making the necessary changes, the
program uses an UPDATE SQL command to modify the existing record in the database,
C. Searching Records
This features a search function that enables users to quickly locate specific records
by entering criteria such as a product code or name. This function uses a SQL SELECT
The LIKE operator allows partial matches, making the search flexible. If records are found,
they are displayed. Otherwise, a message box informs the user, and the database
connection is reset.
D. Deleting Records
To remove a record, the user selects it and clicks the "Delete" button (mnuDelete).
The application confirms the deletion action to prevent accidental data loss. If confirmed,
it executes a DELETE FROM SQL command to remove the record from the database.
from the database. However, it must be used cautiously, as deleted records cannot be
These four fundamental database operations (ADD, EDIT, SEARCH, and DELETE), also
known as CRUD (Create, Read, Update, Delete), describe the basic and core operations of
database management. They form the foundation upon which all other database manipulations
Additional Methods
Lock_Textboxes. This method is used to disable text boxes, preventing users from
modifying data unless explicitly allowed (e.g., during add or edit operations).
Unlock_Textboxes. This method enables text boxes for data entry or editing, ensuring
that users can interact with the form only when appropriate.
Clear_Textboxes. This method clears the contents of all text boxes, used primarily when
Activity Sheet
References
Du, P. O. J. (2019). Visual Studio 2019 in depth: Discover and make use of the powerful
features of the Visual Studio 2019 IDE to develop better and faster mobile, web, and
desktop applications. BPB Publications.
Zak, D. (2022). Programming with Microsoft Visual Basic 2019/2022. Course Technology.
https://youtube.com/playlist?list=PLRfBNGC4M6otChZ0dokEZsO9fnXTCp86r&si=nW12EztIKfb_AL6Y