Visual Basic 2022 Made Easy A Comprehensive Guide To Visual Basic 2022 Programming
Visual Basic 2022 Made Easy A Comprehensive Guide To Visual Basic 2022 Programming
Visual Basic 2022
Made Easy
By Dr.Liew
Disclaimer
Visual Basic 2022 Made Easy is an independent publication and is not
affiliated with, nor has it been authorized, sponsored, or otherwise approved
by Microsoft Corporation.
Trademarks
Microsoft, Visual Basic, Excel and Windows are either registered
trademarks or
trademarks of Microsoft Corporation in the United States and/or other
countries.
All other trademarks belong to their respective owners.
Liability
The purpose of this book is to provide basic guides for people interested in
Visual
Basic 2022 programming. Although every effort and care has been taken to
make
The information as accurate as possible, the author shall not be liable for
any error,
Harm or damage arising from using the instructions given in this book.
Copyright ® 2023 Liew Voon Kiong
All rights reserved. No Part of this e-book may be reproduced in any form
or by any means, without permission in writing from the author.
Acknowledgement
I would like to express my sincere gratitude to the many people who have
made their contributions in one way or another to the successful publication
of this book.
My special thanks go to my children Xiang, Yi and Xun who have
contributed their ideas and help in editing this book. I would also like to
appreciate the support provided by my beloved wife Kim Huang and my
youngest daughter Yuan. I would also like to thank the millions of readers
who have visited my Visual Basic Tutorial website at vbtutor.net for their
support and encouragement.
About the Author
Dr. Liew Voon Kiong holds a bachelor’s degree in Mathematics, a master’s
degree in Management and a doctorate in Business Administration. He has
been involved in Visual Basic programming for more than 20 years. He
created the popular online Visual Basic Tutorial at www.vbtutor.net, which
has attracted millions of visitors since 1996. It has consistently been one of
the highest ranked Visual Basic websites.
To provide more support for Visual Basic students, teachers, and hobbyists,
Dr. Liew has written this book to complement the free Visual Basic 2022
tutorial with much more content. He is also the author of the Visual Basic
Made Easy series, which includes Visual Basic 6 Made Easy, Visual Basic
2008 Made Easy, Visual Basic 2010 Made Easy, Visual Basic 2013 Made
Easy, Visual Basic 2015 Made Easy, Visual Basic 2017 Made Easy ,
Visual Basic 2019 Made Easy and Excel VBA Made Easy. Dr. Liew’s
books have been used in high school and university computer science
courses all over the world.
Preface
This book is a comprehensive guide to learning Visual Basic 2022 for
beginners. It is also an excellent reference text for high school and college-
level computer science courses. Reading this book will allow you to:
Understand the basic concepts of Visual Basic 2022
programming.
Create your own Visual Basic 2022 applications from scratch
effortlessly.
Obtain inspiration and ideas for your assignments and projects
from many interesting examples.
Modify the code samples easily to suit your needs.
Learn how to package and distribute your applications.
Besides that, you can also use the book in many ways, such as:
As a source of reference for your programming hobby.
As a source of reference for your school, college projects or even
commercial applications.
As teaching material if you are a schoolteacher or college
lecturer who teaches computer programming.
Teach your kids how to program in VB if you are a parent.
Table of Contents
Chapter 1 Introduction
1.1 A Brief History of Visual Basic
1.2 Installation of Visual Studio 2022
1.3 Creating a Visual Basic 2022 Project
Chapter 7 Arrays
7.1 Introduction to Arrays
7.2 Dimension of an Array
7.3 Declaring Arrays
Example 7.1 To Find the Length of an Array
Example 7.2 Find the length of Non-zeroth Array
Example 7.3 Declaring Two-Dimensional Array
Example 7.4 Creating an Array via an Input Box
Chapter 12 Looping
12.1 For...Next Loop
Example 12.1 Adding Numbers to a List Box
Example 12.2 Summation of Numbers using a For Next Loop
Example 12.3 Negative Increment in a For Next Loop
Example 12.4 Exit For
12.2 Do Loop
Example 12.5 Adding Numbers in a Do Loop
Example 12.6 Adding Numbers in a Do Loop
12.3 While...End While Loop
Example 12.7 Summation of Numbers using a While End While Loop
Chapter 14 Functions
14.1 Creating a User-Defined Function
Example 14.1: BMI Calculator
Example 14.2: Future Value Calculator
14.2 Passing Arguments by Value and by Reference
Example 14.3 Square Root Function
Clicking the link brings up the Visual Studio 2022 download page, as
shown in Figure 1.1
Figure 1.1
You can choose the free Visual Studio Community 2022 or the Full-featured
Professional 2022 and Enterprise 2022 to download, as shown in Figure
1.2.
Figure 1.2
Upon clicking Community 2022, you will be directed to the download page,
as shown in Figure 1.3. You can download Visual Studio Community for
Windows, Visual Studio for Mac or the stand-alone source code editor
Visual Studio Code.
Figure 1.3
The free version provides full-featured IDE for students, open-source
community and individuals. Since this book was written based on the free
version, proceed to download the free Visual Studio 2022 Community,
select community and download the installer file. The downloaded installer
file will appear on your Windows taskbar. Clicking the Visual Studio 2022
Installer will start downloading, unpacking and installing the files necessary
for the installation of Visual Studio 2022, as shown in Figure 1.4
Figure 1.4
You will see several status screens that show the progress of the installation.
After the installer has finished installing, it is time to pick the feature set
that you wish to install, as shown in Figure 1.4. Since we are focusing on
developing Visual Basic 2022 desktop app, we will select the .NET desktop
development component. After making your selections, click install.
Figure 1.4
Upon completion of the installation, you are now ready to launch Visual
Studio 2022 and start programming in Visual Basic 2022
1.3 Creating a Visual Basic 2022 Project
To create a Visual Basic 2022 project, launch Microsoft Visual Studio 2022
to bring up the Visual Studio 2022 Start Page, as shown in Figure 1.5
The Toolbox is not shown until you click the Toolbox tab. When you click
the Toolbox tab or use the shortcut keys Ctrl+Alt+x, the common controls
Toolbox will appear, as shown in Figure 1.9. You can drag and move your
toolbox around and dock it to the right, left, top or bottom of the IDE.
Figure 1.9 Visual Basic 2022 Toolbox
Next, we shall proceed to show you how to create your first VB2022
application. First, change the text of the form to ‘My First VB 2022
Application’ in the properties window; it will appear as the title of the
application. Next, insert a button and change its text to OK. The design
interface is shown in Figure 1.10
Figure 1.10 The Design Interface
Now click on the OK button to bring up the code window and enter the
following statement between Private Sub and End Sub procedure, as
shown in Figure 1.11.
MsgBox("My First Visual Basic 2022 App")
Clicking the Start button on the toolbar or press F5 to run the application
will launch the runtime interface, as shown in Figure 1.12. Executing the
application by clicking the OK button will bring up a dialog box that
displays the “My First Visual Basic 2022 App" message, as shown in
Figure 1.13. The function MsgBox is a built-in function of Visual Basic
2022 which can display the text enclosed within the brackets.
Figure 1.11 Visual Basic 2022 Code Window
Summary
● In section 1.1, you have learned about the history of Visual Basic 2022
● In section 1.2, you have learned how to install and launch Visual Basic
Studio 2022
● In section 1.3, you have learned how to launch the new project dialog
and the Visual Basic 2022 IDE. You have also learned how to write
your first program.
Chapter 2 Designing the User Interface
To design a graphical user interface, you may customize the default form by
changing its properties at design phase and at runtime, including its name,
title, background color and so forth. After customizing the default form,
you may proceed to add controls from the toolbox to the form and then
define their properties.
2.1 Customizing the Form
When you start a new Visual Basic 2022 project, the VB2022 IDE will
display the default form along with the Solution Explorer window and the
Properties window, as shown in Figure 2.1. The name of the default form is
Form1. The properties window displays all the properties associate with
Form1 and their corresponding attributes or values. You can change the
name of the form, the title of the form using the text property, the
background color, the foreground color, size and more. Try changing the
properties as shown in Table 2.1
Table 2.1
Property Value
Name MyForm
Text My First VB2022 App
BackColor LavenderBlush
ForeColor Crimson
MaximizeBox False
You do not have to type in the color manually, you can select a color from
the color drop-down list that comprises three tabs, Custom, Web, and
System, as shown in Figure 2.1. Clicking the drop-down arrow will bring
out a color palette or a list of color rectangles where you can select a color.
Figure 2.1
Another method of setting the colors is to manually type the RGB color
code or the hex color code. The values of R, G and B ranges from 0 to 255,
therefore, by varying the values of the RGB we can obtain different colors.
The hex color code system uses a six-digit, three-byte hexadecimal number
to represent colors. The bytes represent the red, green and blue components
of the color. One byte represents a number ranging from 00 to ff, or 0 to 255
in decimal notation. For example, #0000ff represents the cyan color.
However, when you type the Hex color code in the properties window, it
automatically converts the color to RGB color. Figure 2.2 shows a list of
Hex color codes and the corresponding colors.
Figure 2.2 Hex Color Codes
The design interface is shown in Figure 2.3 and the runtime interface is
shown in Figure 2.4. On the runtime interface, notice that the title has been
changed from Form1 to My First VB 2022 Application, background color
changed to Lavender Blush, the text OK color is Crimson and the window
cannot be maximized.
Figure 2.3 Design UI
ObjectName.property
For example, setting the background of the form to blue using the following
code:
Me.BackColor=Color.Blue
In addition, you can use the FromArgb method to specify the color using
the RGB codes, as follows:
Me.BackColor = Color.Turquoise
Me.ForeColor = Color.Ivory
MyBtn.BackColor = Color.DodgerBlue
Me.MaximizeBox = False
Me.MinimizeBox = True
End Sub
To runtime UI is shown in Figure 2.5. Notice that it is now different from
that shown in Figure 2.4,
Figure 2.5
In the place of Turquoise , you can use RGB code as follows:
In addition, you can specify the size, the opacity and the position of the
default form using the code, as in Example 2.2
Example 2.2 Customizing the Form
Me.BackColor =Color.Beige
Me.MaximizeBox = False
Me.MinimizeBox = True
Me.Opacity = 0.85
Me.CenterToParent()
End Sub
The property Opacity sets the degree of transparency. The runtime interface
is as shown in Figure 2.6
Figure 2.6
2.2 Adding Controls to the Form
In section 2.1, we have learned how to build an UI by customizing the
default form. Next, we shall continue to build the UI by adding some
controls to the form. The controls are objects that consist of three elements,
namely properties, methods, and events. We can add them to the form from
the Toolbox. Among the controls, the most used ones are button, label,
textbox, list box, combo box, picture box, check box, radio button and
more. These controls can be made visible or invisible at runtime. However,
some controls will only run in the background and never be seen at runtime,
one such control is the timer.
The Toolbox is usually hidden when you start Visual Basic 2022 IDE, you
must click View on the menu bar and then select Toolbox to reveal the
toolbox, as shown in Figure 2.6. You can also use shortcut keys Ctrl+w+x
to bring out the toolbox.
Adding a control to the form is an easy task, what you must do is double
click it or drag it onto the form. You can drag the control around the form
and resize it.
To demonstrate how to add the controls and then change their properties,
we shall design a picture viewer. First, change the title of the default form
to Picture Viewer in its properties window. Next, insert a picture box on the
form and change its background color to white. To do this, right click the
picture box and select properties in the popup menu, then look for the
BackColor Property as shown in the properties window in Figure 2.9.
Finally, add two buttons to the form and change the text to View and Close
in their respective properties’ windows. The picture viewer is not functional
yet until we write code for responding to events triggered by the user. We
will deal with the programming part in the coming chapters.
Figure 2.9
Summary
● In section 2.1, you have learned how to customize the form by changing
the values of its properties.
● In section 2.2, you have learned how to add controls to the form and
change their properties at design phase and at runtime.
Chapter 3 Writing the Code
In this chapter, we shall learn how to write code for all the controls enabling
them to interact with the events triggered by the users. Before learning how
to write Visual Basic 2022 code, let us delve into the concept of event-
driven programming.
3.1 The Concept of Event-Driven Programming
Visual Basic 2022 is an event-driven programming language, meaning that
the code is executed in response to events triggered by the user like clicking
the mouse or pressing a key on the keyboard. Some other events are
selecting an item from a drop-down list, typing some words into a text box
and more. It may also be an event that responds to some other events. Some
of the common events in Visual Basic 2022 are load, click, double-click,
drag-drop, keypress and more.
Every control you place on the form has a set of events associate with it. To
view the events, double-click the control on the form to enter the code
window. The default event will appear at the top right side of the code
window. You must click the default event to view other events associated
with the control. The code appears on the left side is the event procedure
associated with the load event. Figure 3.1 illustrates the event procedure
Load associated with the Form and Figure 3.2 shows the events associated
with the button.
Figure 3.1: Events associated with Form
End Sub
End Class
MsgBox is a built-in function that displays a message in a pop-up message
box. The MsgBox function comprises a few arguments, the first is the
message that is displayed and the third one is the title of the message box.
When you run the program, a message box displaying the phrase "My First
Visual Basic 2022 APP" will appear, as shown in Figure 3.3.
Figure 3.3
You will notice that above the Private Sub structure there is a preceding
keyword Public Class Form1 . This has to do with the concept of the
object-oriented programming language. When we start a windows
application in Visual Basic 2022, we will see a default form with the name
Form1 appear in the IDE, it is the Form1 Class that inherits from the Form
class System.Windows.Forms.Form .
Now, let us write a code that perform arithmetic calculation, as in Example
3.2
Example 3.3 Arithmetic Calculations
End Sub
*The symbol & (ampersand) is to perform string concatenation. The output
is as shown in Figure 3.4
Figure 3.4
Summary
● In section 3.1, you have learned the concepts of event driven
programming.
● In section 3.2, you have learned how to write code for the controls.
Chapter 4 Working with Controls
In this chapter, we shall learn how to work with some common controls and
write codes for them. Some of the commonly used controls are Label,
TextBox, Button, ListBox and ComboBox. In this chapter, we shall only
deal with TextBox , Label, ListBox and ComboBox. We shall deal with the
other controls later.
4.1 TextBox
TextBox is the standard control for accepting inputs from the user as well as
to display the outputs. It can handle string and numeric data but not images
In this program, add two text boxes and a button on the form. The two text
boxes are for accepting inputs from the user. Besides that, we program the
button to calculate the sum of the two numbers using the plus operator. The
value in a text box is stored using the syntax TextBox1.Text , where Text
is one of the properties of TextBox.
The following code will add the value in TextBox1 and the value in
TextBox2 and displays the sum in a message box. The runtime interface is
illustrated in Figure 4.1.
End Sub
Figure 4.1
After clicking the Add button, you will obtain the answer in a message box,
as shown in Figure 4.2.
Figure 4.2
4.2 Label
Label is used for multiple purposes like providing instructions and guides to
the users, displaying outputs and more. It is different from the TextBox
because it is read only, which means the user cannot edit its content at
runtime. Using the syntax Label.Text , it can display string as well as
numeric data. You can change its text property in the properties window or
at runtime by writing an appropriate code.
Example 4.2 Display the output on a Label
Based on Example 4.1, we add two Labels, one is for displaying the text
Sum= and the other Label is to display the answer of the Sum. For the first
Label, change the text property of the label by typing Sum= over the default
text Label1. Further, change its font to bold and its font size to 10. For the
second label, delete the default text Label2 and change its font to bold and
the font size to 10. Besides that, change its background color to white.
In this program, instead of showing the sum in a message box, we display
the sum on the Label.
The Code
End Sub
*The function Val is to convert text to numeric value. Without using Val ,
you will see that two numbers are joined without adding them.
The output is as shown in Figure 4.3
Figure 4.3
4.3 ListBox
ListBox is a control that displays a list of items. It allows the user to click
and select the items from the list. Items can be added by the programmer at
design time or at runtime using a code. We can also write code to allow the
user to add items to the ListBox or remove the items from it.
4.3.1 Adding Items to ListBox
To demonstrate how to add items at design time, start a new project and
insert the ListBox control on the form. Next, right-click on the list box to
of the Item property to open the String Collection Editor . In the Editor, enter
one item at a time, pressing the Enter key after each item, as shown in Figure
4.4. After clicking the OK button, the items will be displayed in the list box,
Figure 4.5
b) Adding Items using the Add () Method
Items can also be added at runtime using the Add() method. Before we
proceed further, we should know that Visual Basic 2022 is an object-oriented
programming language. Therefore, visual basic 2022 comprises objects. All
objects have methods and properties. They can be differentiated and
connected by a hierarchy. For ListBox, an Item is an object subordinated to
the object ListBox . The Item object comprises a method call Add() that is
used to add items to the list box. To add an item to the list box, use the
following syntax:
ListBox.Item.Add("Text")
In this example, running the program will add the item “Vivo” to the end of
the list, as shown in Figure 4.6
This program allows the user to add items via an input box. First, we create a
variable myitem and then assign a value to it via the InputBox function.
We use the Add () method to add the user’s item into the list box. The code
is as follows:
MyListBox.Items.Add(myitem)
End Sub
The runtime interface is as shown in Figure 4.7
Figure 4.7
After typing the item ‘Vivo” in the input box, the item will be added to the
list box, as shown in Figure 4.8.
.
Figure 4.8
Example 4.5 Geometric Progression
n-1
The formula to find the nth term of the geometric progression is ar ,
x = TxtFirst.Text
r = TxtCR.Text
n = 1
Do
x = x * r
n = n + 1
End Sub
MyList.Items.Clear()
End Sub
The output is as shown in Figure 4.9
To remove items at design time, simply open the String Collection Editor
and delete the items line by line or all at once using the Delete key. To
remove the items at runtime, you can use the Remove method, as illustrated
in Example 4.6.
In this example, add a button and label it “Remove Items”. Click on this
button and enter the following code
You can allow the user to choose an item to delete via an input box. To add
this capability, insert a button at design time and change its text to Delete
Item. Click on the button and enter the following statements in the code
window:
MyListBox.Items.Remove(myitem)
End Sub
The runtime interface is as shown in Figure 4.11. After entering the item
iPhone in the input box and press OK, the item iPhone will be deleted from
the list box.
Figure 4.11
To remove a selected item from the list box, using the following syntax:
Listbox1.Items.Remove(ListBox1.SelectedItem)
Figure 4.13
To remove multiple selected items from the list box, you must use the
If...End If statements together with the For...Next loop. Besides that, you
must ensure that the list box allows multiple selection. To enable multiple
selection, set the selection mode to MultipleSimple in the ListBox
properties window. The code is as shown in Example 4.8.
Example 4.8 Delete Multiple Selected Items from ListBox
In this example, add an extra button to the previous example and label it as
Clear Selected Items. Key in the following code:
MyListBox.Items.Remove(MyListBox.SelectedItems(n))
Next n
End If
End Sub
To clear all the items at once, use the clear method, as illustrated in
Example 4.8.
Example 4.9 Clear All Items from ListBox
In this example, add a button and label it “Clear the List”
MyListBox.Items.Clear()
End Sub
When you run the program and click the “Clear the List” button, all the items
will be cleared. The design interface for removing the items from the list box
is as shown in Figure 4.14
Figure 4.14
4.4 ComboBox
The function of the combo box is to present a list of items where the user
can click and select the items from the list. However, in contrast to the list
box, combo box only displays one item at runtime and the user needs to
click on the handle (small arrowhead) on the right of the combo box to see
all the items that are presented in a drop-down list.
4.4.1 Adding Items to ComboBox
In order to add items to the combo box at design time, use the String
display an item as the default text in the combo box when you run the
program, enter the name of the item by replacing the text property of the
combo box.
Figure 4.15
Clicking the handle of the right side of the combo box at runtime reveals
the items, as shown in Figure 4.16
Figure 4.16
Besides that, you may add items using the Add() method, as shown in
Example 4.10.
Example 4.10 Adding an Item to ComboBox
Figure 4.17
You can allow the user to add items via an input box, as in Example 4.11
Example 4.11 Adding an Item to ComboBox via an Input Box
MyComboBox.Items.Add(myitem)
End Sub
The runtime interface is as shown in Figure 4.18
Figure 4.18
After you type the item ‘Xiaomi’ and click Ok, the item will be added to the
combo box, as shown in Figure 4.19.
Figure 4.19
4.4.2 Removing Items from a Combo box
To remove items from the combo box at design stage, simply open the
String Collection Editor and delete the items line by line or all at once using
To remove the items at runtime, you can use the Remove method, as
illustrated in the Example 4.12. In this example, add a second button and
label it “Remove Items”.
Example 4.12 Delete an Item from ComboBox
To clear all the items at once, use the clear method, as illustrated in
Example 4.14
Example 4.14 Remove All Items from ComboBox
Figure 5.1
Figure 5.2
The next step is to select a local resource and click on the Import button to
view the available image files in your local drives, as shown in Figure 5.3.
Finally, select the image you like and then click the open button, the image
will be displayed in the picture box, as shown in Figure 5.4
Figure 5.3
Figure 5.4
5.1.2 Loading an Image at Runtime
MyPicBox.Image = Image.FromFile(OFGSelectImage.FileName)
End If
End Sub
Press F5 to run the program and click the View button, a dialog box
showing all the image files will appear, as shown in Figure 5.6
Figure 5.6
Notice that the default image file is JPEG as we have placed it in the first
position in the Filter property. Selecting and opening an image file will load
it in the picture box, as shown in Figure 5.7
Figure 5.7
Summary
● In section 5.11, you have learned how to load an image at design time
using the properties window.
● In section 5.1.2, you have learned how to load an image at runtime.
● In section 5.2, you have learned how to load an image using the
OpenFileDialog control.
Chapter 6 Working with Data
We deal with all kinds of data in our daily life like names, phone numbers,
addresses, money, date, stock quotes, statistics and more. Similarly, in
Visual Basic 2022, we must deal with all sorts of data. Some data can be
mathematically calculated while some are non-numeric in nature. In Visual
Basic 2022, data can be stored as variables, constants, or arrays. The values
of data stored as variables always change, just like the contents of a
mailbox or the storage bin while the value of a constant remains the same
throughout.
6.1 Visual Basic 2022 Data Types
Visual Basic 2022 classifies information into two major data types, numeric
data types and non-numeric data type.
6.1.1 Numeric Data Types
Numeric data types are types of data comprising numbers that can be
calculated mathematically. Examples of numeric data types are examination
marks, height, body weight, number of students in a class, share values, the
price of goods, monthly bills, fees, bus fares and more.
Numeric data are divided into seven types based on the range of values they
can store. Calculations that only involve round figures or data that do not
need high precision can use Integer or Long integer. Programs that require
high precision calculation must use Single and Double precision data types;
they are also called floating point numbers. For currency, you can use the
currency data types. If even more precision is required to perform
calculations that involve many decimal points, we can use the decimal data
types. These data types are summarized in Table 6.1.
Table 1 Numeric Data Types
TYPE STORAGE RANGE
Byte 1 byte 0 to 255
Integer 2 bytes -32,768 to 32,767
Long 4 bytes -2,147,483,648 to 2,147,483,648
Single 4 bytes -3.402823E+38 to -1.401298E-45 for
negative values
4.94065645841247E-324 to
1.79769313486232e+308 for positive
values.
Currenc 8 bytes -922,337,203,685,477.5808 to
y 922,337,203,685,477.5807
Decimal 12 bytes +/-
79,228,162,514,264,337,593,543,950,3
35 if no decimal is use
+/- 7.9228162514264337593543950335
(28 decimal places).
Literals are values that you assign to data. In some cases, we must add a
suffix behind a literal so that VB2022 can handle the calculation more
accurately. For example, we can use num =1.3089# for a Double type data.
The suffixes are summarized in Table 6.3.
Table 6.3 Suffixes and Data Types
Suffix Data type
& Long
! Single
# Double
@ Currency
In addition, we must enclose string literals within two quotations whereas
date and time literals must be enclosed within two # sign. Strings can
contain any characters, including numbers. The following are a few
examples:
memberName="Turban, John."
TelNumber="1800-900-888-777"
LastDay=#31-Dec-00#
ExpTime=#12:00 am#
6.2 Variables and Constants
In the previous section, we have learned about data and various data types.
mailboxes in the post office. The content of the variables changes every
My_Computer My.Computer
Smartphone123 123Smartphone
Long_Name_Can_beUSE LongName&Canbe&Use
*& is not acceptable
assigning names and data types. If you fail to do so, the program will show
an error. Variables are usually declared in the general section of the code
If you want to declare more variables, you can declare them in separate
lines or combine them in one line, separating each variable with a comma,
as follows:
End Sub
You may also combine the above statements in one line, separating each
variable with a comma, as follows:
Integer,.............
For the string declaration, there are two possible forms, one for the
variable-length string and another for the fixed-length string. For the
variable-length string, just use the same syntax as Example 6.2.
Example 6.2 Declaring a String Variable
Button1.Click
MsgBox(YourMessage)
End Sub
When you run the program, a message box shows the text “Happy
Birthday!” will appear, as shown in Figure 6.1
Figure 6.1
For the fixed-length string, you must use the syntax as shown below:
firstNumber=100
secondNumber=firstNumber-99
userName="John Lyan"
userpass.Text = password
Label1.Visible = True
Command1.Visible = false
Label4.text = textbox1.Text
ThirdNumber = Val(usernum1.Text)
X=sqr (16)
Num=Int(Rnd*6)+1
An error will occur when you try to assign a value to a variable of
incompatible data type. For example, if you have declared a variable as an
integer but you assigned a string value to it, an error occurred, as shown in
Example 6.5.
Example 6.5 Error Assigning a Variable
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles
Button1.Click
MsgBox(YourMessage)
End Sub
When you run the program, the following error messages will appear in a
dialog box, as shown in Figure 6.2.
You can either quit the program or continue to run the program.
Figure 6.2
6.2.4 Scope of Declaration
Other than using the Dim keyword to declare the data, you can also use
other keywords to declare the data. Three other keywords are Private,
Static and Public , as follows:
The above keywords indicate the scope of declaration. Private declares a
local variable, or a variable that is local to a procedure or module. However,
Private is rarely used; we normally use Dim to declare a local variable.
The Static keyword declares a variable that is being used multiple times,
even after a procedure has been terminated. It means the static keyword
preserves the value of a variable even after the procedure is
terminated. Public is the keyword that declares a global variable, which
means it can be used by all the procedures and modules of the whole
program.
Constants are different from variables in the sense that their values do not
change during the running of the program. The syntax to declare a constant
Dim R As Single = 10
AreaCircle = Pi * R ^ 2
MsgBox("Area of circle with " & "radius" & R & "=" & AreaCircle)
End Sub
Dim R As Single = 10
AreaCircle = Pi * R ^ 2
MsgBox("Area of circle with " & "radius" & R & "=" & AreaCircle)
End Sub
Running the program and clicking the OK button will produce the
following message, as shown in Figure 6.3
Figure 6.3
Summary
● In section 6.11, you have understood numeric data types.
● In section 6.1.2, you have understood non-numeric data types.
● In section 6.1.3, you have learned how to use suffixes for literals.
● In section 6.2.1, you have understood rules that govern variable names.
● In section 6.2.2, you have learned how to declare variables.
● In section 6.2.3, you have understood the scope of declaration of
variables.
● In section 6.2.3, you have learned how to declare a constant.
Chapter 7 Arrays
7.1 Introduction to Arrays
An array is a group of variables (elements) with the same data type. When
we work with a single item, we only use one variable. However, if we have
a list of items which are of similar type, we must declare an array of
variables instead of using a variable for each item.
Table 7.2 Two-Dimensional Array
SName(0,0) SName(0,1) SName(0,2) SName(0,3)
SName(1,0) SName(1,1) SName(1,2) SName(1,3)
SName(2,0) SName(2,1) SName(2,2) SName(2,3)
SName(3,0) SName(3,1) SName(3,2) SName(3,3)
7.3 Declaring Arrays
We can use Public or Dim statements to declare an array, just as the way
we declare a single variable. The Public statement declares an array that
can be used throughout an application while the Dim statement declares an
array that could be used only in a local procedure or module. The statement
to declare a one-dimensional array is as follows:
To find out the length of the array, you can write the following code:
MsgBox(CusName.Length)
End Sub
Running the program will produce a message box that displays the length of
the array i.e. 11, as shown in Figure 7.1
Figure 7.1
You might also declare an array with a non-zero starting index by
initializing an index value other than zero, as follows:
MyBase.Load
MsgBox(CusName.Length)
End Sub
The message box will display the length as 3. The statement to declare a
two-dimensional array is as follows, where m and n indicate the last indices
in the array. The number of elements or the length of the array is (m+1) x
(n+1)
MyBase.Load
MsgBox(CusName.Length)
End Sub
The program produces a message box will display 42, as shown in Figure
7.2
Figure 7.2
Example 7.4 Creating an Array via an Input Box
MyBase.Load
For num = 0 To 5
ListBox1.Items.Add(CusName(num))
Next
End Sub
This program will prompt the user to enter names in an input box for a total
of 6 times and the names will be entered into a list box, as shown in Figure
7.3 and Figure 7.4
Figure 7.3
Figure 7.4
Summary
● In section 7.1, you have understood the concept of arrays.
● In section 7.2, you have understood dimension in arrays.
● In section 7.3, you have learned how to declare an array.
Chapter 8 Mathematical Operations
Computers can perform mathematical calculations much faster than human
beings do. However, the computer itself cannot perform any mathematical
calculations without receiving instructions from the user.
8.1 Mathematical Operators
The Visual Basic 2022 mathematical operators are like the normal
arithmetic operators, only with some 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 Visual Basic 2022
mathematical operators is shown in Table 8.1.
Table 8.1 Mathematical Operators
Operator Mathematical function Example
+ Addition 1+2=3
- Subtraction 10-4=6
^ Exponential 3^2=9
* Multiplication 5*6=30
/ Division 21/7=3
Mod Modulus(returns the remainder of an 15 Mod
integer division) 4=3
\ Integer Division(discards the decimal 19/4=4
places)
8.2 Writing Code that Performs Mathematical
Operations
It is easy to write code that can perform mathematical operations in
VB2022. First you must think of a mathematical problem and equations as
well as formulas that are required for solving it then write the code using
those formulas and equations.
Example 8.1 Standard Arithmetic Calculations
In this program, you must insert two text boxes, 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 displays
the results on four labels. This program performs standard arithmetic
operations involving addition, subtraction, multiplication and division. The
Code is as shown in Example 8.1.
Example 8.1 Performing Arithmetic Operations
num1 = TextBox1.Text
num2 = TextBox2.Text
sum=num1+num2
difference=num1-num2
quotient=num1/num2
LblSum.Text=sum
LblDiff.Text=difference
LblPro.Text = product
LblQt.Text = quotient
End Sub
c^2=a^2+b^2
Dim a, b, c As Single
a = TextBox1.Text
b = TextBox2.Text
c= (a^2+b^2)^(1/2)
Label3.Text=c
End Sub
A lot of people are obese now and that could affect their health seriously.
Obesity has been proven by medical experts to be one of the main factors
that brings many adverse medical problems, including cardiovascular
disease. If your BMI is more than 30, you are considered obese.
The BMI calculator is a program that can calculate the body mass index, or
BMI of a person based on the body weight in kilograms and the body height
in meters. BMI can be calculated using the formula weight/( height )^2,
where weight is measured in kg and height in meters. If you only know
your weight and height in lb. and feet, then you must convert them to the
metric system. The code is as follows:
height = TxtBoxHgt.Text
weight = TxtBoxWgt.Text
bmi = (weight) / (height ^ 2)
LblBMI.Text = bmi
If bmi > 26 Then
LblComment.Text = "Your are overweight"
ElseIf bmi <= 26 And bmi > 18 Then
LblComment.Text = "Your weight is normal"
Else
LblComment.Text = "Your are underweight"
End If
End Sub
The output is shown in Figure 8.1 below. In this example, your height is
1.80m (about 5 foot 11), your weight is 75 kg (about 168Ib), and your BMI
is about 23.14815. The reading suggests that you are healthy.
Figure 8.1
Summary
● In section 8.1, you have recognized all mathematical operators in
VB2022.
● In section 8.2, you have learned to write code that perform arithmetic
operations.
Chapter 9 String Manipulation
String manipulation means manipulating characters like names, addresses,
text1 = "Visual"
text2 = "Basic"
text3 = "2022"
MsgBox(text4)
End Sub
Figure 9.1
Example 9.2 Data Mismatch
text1 = "Visual"
text2 = 22
MsgBox(text3)
End Sub
This code will produce an error because of data mismatch. The error
message appears as shown in Figure 9.2.
Figure 9.2
However, using & instead of + will be alright.
text1 = "Visual"
text2 = 22
MsgBox(text3)
Figure 9.3
9.2 String Manipulation Using Built-in Functions
A function is like a normal procedure. The main purpose of the function is
to accept an input and return a value which is passed on to the main
procedure to finish the execution. There are numerous string manipulation
functions that are built into Visual Basic 2022.
9.2.1 The Len Function
The Len function returns an integer value which is the length of a phrase or
a sentence, including the empty spaces. The syntax is:
Len("Phrase")
Example 9.3 Using the Len Function to find the Lenth of a Phrase
MsgBox(Len(MyText))
End Sub
The Right function extracts the right portion of a phrase. The syntax is
Microsoft.VisualBasic.Right("Phrase",n)
MsgBox(Microsoft.VisualBasic.Right(MyText, 4))
End Sub
Executing the above code returns four right most characters of the phrase
entered in the text box.
The Output is as shown in Figure 9.5
Figure 9.5
9.2.3 The Left Function
The Left function extracts the left portion of a phrase. The syntax is:
Microsoft.VisualBasic.Left("Phrase",n)
n is the starting position from the left of the phase where the portion of the
phrase will be extracted. For example,
The Mid function is used to retrieve a part of text from a given phrase. The
syntax of the Mid Function is
Mid(phrase, position,n)
In the Mid function, phrase is the string from which a part of text is to be
retrieved, position is the starting position of the phrase from which the
retrieving process begins, and n is the number of characters to retrieve.
Example 9.5 Using the Mid Function to Extract a Part of a Phrase
Private Sub BtnShow_Click(sender As Object, e As EventArgs) Handles
BtnShow.Click
LblPhrase.Text = myPhrase
blExtract.Text = Mid(myPhrase, 2, 6)
End Sub
* In this example, when the user clicks the button, an input box will pop up
prompting the user to enter a phrase. After a phrase is entered and the OK
button is pressed, the label will show the extracted text starting from
position 2 of the phrase and the number of characters extracted is 6. For
example, if you entered the phrase "Visual Basic 2022", the extracted text is
isual .
You can also let the user decide the starting position of the text to be
extracted as well as the number of characters to be extracted, as shown in
the following code:
Handles BtnExtract.Click
n = TxtNumber.Text
End Sub
The Trim function trims the empty spaces on both sides of the phrase. The
syntax is
Trim("Phrase")
Label1.Text = Trim(myPhrase)
End Sub
9.2.6 Ltrim Function
The Ltrim function trims the empty spaces of the left portion of the phrase.
The syntax is
Ltrim("Phrase")
For example,
Ltrim("Visual Basic 2022") = Visual basic 2022
9.2.7 The Rtrim Function
The Rtrim function trims the empty spaces of the right portion of a phrase.
The syntax is
Rtrim("Phrase")
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 syntax
is
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.
The syntaxes are
Microsoft.VisualBasic.UCase(Phrase)
Microsoft.VisualBasic.LCase(Phrase)
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 produce a
beep sound. The syntax of the Chr function is:
Chr(charcode)
and the syntax of the Asc function is
Asc(Character)
The followings are some examples:
If condition Then
End If
myNumber = TextBox1.Text
End If
End Sub
* When you run the program and enter a number that is greater than 100,
you will see the "You win a lucky prize" message. On the other hand, if the
number entered is less than or equal to 100, you do not see any message.
10.3.2 If...Then…Else Statement
Using If...Then statement alone does not provide choices for the users. To
provide choices, we use the If...Then...Else Statement. This control
structure will ask the computer to perform a certain action specified by the
expression if the condition is met. And when the condition is false, an
alternative action will be executed. The syntax for the If...Then...Else
statement is
If condition1 Then
Expression1
Figure 10.2
If the generated number is greater than the lucky number, the message
“Your number is too big" will appear. If the generated number is smaller
than the lucky number, the message “Your number is too small" will be
displayed. Otherwise, the message "Congratulations! You strike the lucky
number" will be displayed. The outcomes are shown in Figure 10.3, 10.4
and 10.5.
Figure 10.3
Figure 10.4
Figure 10.5
Example 10.3 Another Lucky Draw Program
Private Sub BtnDraw_Click(sender As Object, e As EventArgs) Handles
BtnDraw.Click
myAge = TxtAge.Text
myName = TxtName.Text
LblNum.Text = myNumber
LblMsg.Text = " Congratulation " & myName & ",You won a lucky
prize!"
Else
LblMsg.Text = " Sorry " & myName & ", you did not win any prize"
End If
End Sub
End Class
The outcomes are shown in Figure 10.6 and Figure 10.7
Figure 10.6
Figure 10.7
10.3.3 If...Then...ElseIf Statement
If there are more than two alternative choices, using just If...Then...Else
statement will not be enough. In order to provide more choices, we can use
the If...Then...ElseIf Statement. The syntax is
If condition Then
Else
End If
Mark = Val(TxtMark.Text)
If Mark>=80 Then
Grade="A"
Else
Grade="D"
End If
Figure 10.8
Clicking the OK produces shows the grade, as shown in Figure 10.9
Figure 10.9
Summary
● In section 10.1, you have learned about the conditional operators.
● In section 10.2, you have learned about the logical operators.
● In section 10.3, you have learned how to write code involving
If...Then…Else.
Chapter 11 Select Case
In this chapter, you will learn how to use the Select Case structure to
control the program flow. 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 makes decisions on one
expression or dimension whereas 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
are multiple conditions.
The structure of the Select Case control structure in Visual Basic 2022 is as
follows:
Select Case test expression
Case Else
End Select
This program displays the examination results based on the grade obtained.
The test expression here is grade. In this program, we insert a textbox for
entering the grade, rename it as txtGrade. Next, insert a label to display the
result, rename it as LblResult. Lastly, we insert a button, rename it as
BtnCompute then enter the following code:
grade=txtGrade.Text
Case "A"
LblResult.Text="High Distinction"
Case "A-"
LblResult.Text="Distinction"
Case "B"
LblResult.Text="Credit"
Case "C"
LblResult.Text="Pass"
Case Else
LblResult.Text="Fail"
End Select
End Sub
When the user runs the program, enters grade, and clicks the ‘Compute’
button, the output is as shown in Figure 11.1.
Figure 11.1
Example 11.2 Using Case Is
This example is like the previous example, but we use the Case IS keyword
and the conditional operator >= to compute the results.
mark = TxtMark.Text
Case Is >= 85
LblRemark.Text= "Excellence"
Case Is >= 70
LblRemark.Text= "Good"
Case Is >= 60
Case Is >= 50
LblRemark.Text= "Average"
Case Else
End Select
End Sub
Figure 11.2
'Examination Marks
mark = TxtMark.Text
Case 0 to 49
Case 50 to 59
LblRemark.Text = "Average"
Case 60 to 69
Case 70 to 84
LblRemark.Text = "Good"
Case 85 to 100
LblRemark.Text= "Excellence"
Case Else
End Select
End Sub
'Examination Marks
mark = TextBox1.Text
Case 0 To 49
Label1.Text = "E"
Case 50 To 59
Label1.Text = "D"
Case 60 To 69
Label1.Text = "C"
Case 70 To 79
Label1.Text = "B"
Case 80 To 100
Label1.Text = "A"
Case Else
End Select
End Sub
The output is as shown in Figure 11.3
Figure 11.3
Summary
● In section 11.1, you have learned about the Select Case structure.
● In section 11.2, you have learned how to write code using Select Case
structure together with the conditional operators.
Chapter 12 Looping
could support. For example, we can design a program that adds a series of
numbers until the sum exceeds a certain value, or a program that asks the
user to enter data repeatedly until he or she enters the word ‘Finish’. In
Visual Basic 2022, there are three types of Loops, the For...Next loop,
Next
To exit a For...Next Loop, we place the Exit For statement within the
loop.
Example 12.1 Adding Numbers to a List Box
For counter=1 to 10
ListBox1.Items.Add (counter)
Next
*This loop will enter number 1 to 10 into the list box, as shown in Figure
12.1
Figure 12.1
Example 12.2 Summation of Numbers using a For Next Loop
sum += counter
ListBox1.Items.Add (sum)
Next
The first loop results in 1+11=12, the second loop will be 12+21=33 and so
forth.
The output is as shown in Figure 12.2.
Figure 12.2
Example 12.3 Negative Increment in a For Next Loop
Dim counter, sum As Integer
sum = 1000
sum - = counter
ListBox1.Items.Add(sum)
Next
Notice that increments can be negative. The program will compute the
subtraction as follow:
1000-100 - 95 - 90 -……….
The output is as shown in Figure 12.3.
Figure 12.3
Dim n As Integer
For n=1 to 10
If n>6 then
Exit For
Else
ListBox1.Items.Add (n)
End If
Next
The process will stop when n is greater than 6, as shown in Figure 12.4.
Figure 12.4
12.2 Do Loop
The Do Loop structures are:
a)
Do While condition
Loop
b)
Do
Loop
d)
Do
counter +=1
ListBox1.Items.Add (counter)
Loop
This will keep on adding until counter >100, as shown in Figure 12.5
Figure 12.5
The following example produces the same output as in Example 12.5
Do
TextBox1.Text=counter
counter+=1
MyListBox.Items.Add("---------------")
Do
n += 1
sum += n
If n = 100 Then
Exit Do
End If
Loop
End Sub
* The loop in the above example can be replaced by the following loop:
Do Until n = 10
n += 1
sum += n
Loop
The output is as shown in Figure 12.6
Figure 12.6
12.3 While...End While Loop
The structure of a While...End While Loop is very similar to the Do
While conditions
End While
The loop is illustrated in Example 12.7
Example 12.7 Summation of Numbers using a While End While Loop
ListBox1.Items.Add("---------------")
While n <> 10
n += 1
sum += n
End While
End Sub
Summary
● In section 12.1, you have learned how to write code using the For…
Next Loop
● In section 12.2, you have learned how to write code using the Do Loop
In section 12.3. you have learned how to write code using the While...End
While Loop
Chapter 13 Sub Procedures
A sub procedure is a procedure that performs a specific task and to return
values, but it does not return a value associated with its name. Sub
procedures are usually used to accept input from the user, display
information, print information, manipulate properties or perform some other
tasks. It is a program code by itself, but it is not an event procedure because
it is not associated with a runtime procedure or a control such as a button. It
is called by the main program whenever it is required to perform a certain
task.
A sub procedure begins with a Sub keyword and ends with an End Sub
keyword. The main program can reference a procedure by using its name
together with the arguments in parentheses. The program structure of a sub
procedure is as follows:
Sub ProcedureName(arguments)
Statements
End Sub
The Sub procedure adds two numbers displays its sum on a Label. Under
the calculate procedure, we define two variables x and y and accept inputs
from the users. The program calculates the sum of the values entered by the
user by calling the Sum sub procedure.
Private Sub BtnCompute(sender As Object, e As EventArgs) Handles
MyBase.Load
Dim x, y As Single
x = Val(TxtX.Text)
y = Val(TxtY.Text)
Sum(x, y)
End Sub
Figure 13.1
Example 13.2: Password Cracker
The Timer1.Enabled property is set to False so that the program will only
start generating the passwords after you click on the Generate button. Rnd
is a Visual Basic 2022 function that generates a random number between 0
and 1. Multiplying Rnd by 100 will obtain a number between 0 and 100.
I nt is a function that returns an integer by ignoring the decimal part of the
number.
Timer1.Enabled = True
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles
Timer1.Tick
generate()
Timer1.Enabled = False
LblCrackPass.Text = crackpass
End If
End Sub
Sub generate()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles
MyBase.Load
password = 123
End Sub
Executing the program and clicking the Generate password will start
generating the passwords until it gets the actual password. The output is as
shown in Figure 13.2
Figure 13.2
Summary
● In section 13.1, you have learned about the concept of a sub procedure
● In section 13.2, you have learned how to write code for a sub procedure
Chapter 14 Functions
A function is like a sub procedure in the sense that both are called by the
main procedure to fulfil certain tasks. However, there is one difference; a
function returns a value whereas a sub procedure does not. There are two
types of functions, the built-in function and the user-defined functions.
14.1 Creating a User-Defined Function
To create a user-defined function in Visual Basic 2022, you can type the
function procedure directly into the code window as follows:
Public Function functionName (Argument As dataType,..........) As
dataType
or
The keyword Public indicates that the function is applicable to the whole
project wheareas the keyword Private indicates that the function is only
applicable to a certain module or procedure. Argument is a parameter that
can pass a value back to the function. You can include as many arguments
as you like.
Example 14.1: BMI Calculator
This BMI calculator is a program that can calculate the body mass
index(BMI) of a person based on the body weight in kilograms and the
body height in meters. BMI can be calculated using the formula weight/(
height )2, where weight is measured in kg and height in meters. If you only
know your weight and height in lb. and feet, then you must convert them to
the metric system. If your BMI is more than 30, you are considered obese
The Code
End Function
h = Val(TxtHeight.Text)
w = Val(TxtWeight.Text)
Figure 14.1
Example 14.2: Future Value Calculator
The concept of future value is related to time value of money. For example,
if you deposit your money in a bank as a savings account or a fixed deposit
account for a certain period, you will earn an amount of money based on the
compound interest, and this amount is added to the principal if you continue
to keep the money in the bank. Interest for the following period is now
computed based on the initial principal plus the interest. Subsequent
interests are computed in the same way.
For example, let us say you deposited $1000 in a bank and the bank is
paying you 5% compound interest annually. After the first year, you will
earn an interest of $1000×0.05=$50 . Your new principal will be
$1000+$1000×0.05=$1000(1+0.05)=$1000(1.05)=$1050.
After the second year, your new principal is $1000(1.05)
x1.05=$1000(1.05)2 =$1102.50. This new principal is called the future
value.
Following the above calculation, the future value after n years will be
FV = PV * (1 + i / 100)^n
Where PV represents the present value, FV represents the future value, i is
the interest rate and n is the number of periods (Normally months or years).
The Code
FV = pv * (1 + i / 100) ^ n
End Function
PresentVal = TxtPV.Text
interest = TxtInt.Text
period = TxtN.Text
End Sub
The function FV receives pv by value, i by reference and n by reference.
Notice that although ByRef is not used to pass n, by default it is passed by
reference.
Example 14.3 Square Root Function
In this example, we create two functions that compute the square root of a
number, the first uses the keyword ByRef and the second uses the keyword
ByVal.
The Code
sqroot = x
End Function
y = y ^ 0.5
sqroot1 = y
End Function
Dim u As Single
u = 9
End Sub
Dim u As Single
u = 9
End Sub
The Outputs
Case 1: Passing arguments using ByRef (As shown in Figure 14.3)
Figure 14.3
Notice that the value of u has been changed to 3.
Case 2: Passing arguments using ByVal( as shown in Figure 14.4)
Figure 14.4
Notice that the value of u remains unchanged.
Summary
● In section 14.1, you have learned how to create a user-defined function.
● In section 14.2, you have learned about the difference between passing
arguments using ByVal and ByRef.
Chapter 15 Mathematical Functions
In previous chapters, we have learned how to write code that perform
mathematical operations using standard mathematical operators. However,
for more complex mathematical calculations, we must use the built-in math
functions in Visual Basic 2022. There are numerous built-in mathematical
functions in Visual Basic 2022 which we shall introduce them one by one in
this chapter.
15.1 The Abs Function
The Abs function returns the absolute value of a given number. The syntax
is
Math.Abs(number)
* The Math keyword here indicates that the Abs function belongs to the
Math class. However, not all mathematical functions belong to the Math
class.
BtnComp.Click
LblAbs.Text = Math.Abs(Val(TxtNum.Text))
End Sub
The output is shown in Figure 15.1
Figure 15.1
15.2 The Exp function
The Exp function returns the exponential value of a given number. For
example, Exp(1)=e=2.71828182
The syntax is
Math.Exp(number)
Example 15.2 Compute Exponential Value
This program computes exponential value.
The Code
BtnComp.Click
LblExp.Text = Math.Exp(Val(TxtNum.Text))
End Sub
the largest integer smaller than the number. However, when the number is
negative, it returns the smallest integer larger than the number. Fix does not
belong to the Math class therefore we do not use the Math keyword.
BtnComp.Click
LblFixNum1.Text = Fix(Val(TxtPosNum.Text))
LblFixNum2.Text = Fix(Val(TxtNegNum.Text))
End Sub
The Output is shown in Figure 15.3
Figure 15.3
15.4 The Int Function
The Int is a function that converts a number into an integer by truncating its
decimal part and the resulting integer is the largest integer that is smaller
than the number. For example
Int(2.4)=2, Int(6.9)=6 , Int(-5.7)=-6, Int(-99.8)=-100
15.5 The Log Function
The Log function returns the natural logarithm of a number.
BtnComp.Click
LblLog.Text = Math.Log(Val(TxtNum.Text))
End Sub
Figure 15.4
15.6 The Rnd( ) Function
We use the Rnd function to write code that involves chance and probability.
The Rnd function returns a random value between 0 and 1. To generate a
random integers ranging from 1 to 6, we use this formula Int(Rnd*6)+1.
Example 15.5 Generating Random Integers
LblRnd.Text = Int(VBMath.Rnd() * 6) + 1
End Sub
Notice that the Rnd() function belongs to the VBMath class in Visual
Basic 2022. This is different from Visual Basic 2012, where you can omit
the VBMath keyword.
In this example, Int(Rnd*6) will generate a random integer between 0 and
5 because the function Int truncates the decimal part of the random number
and returns an integer. After adding 1, you will get a random number
between 1 and 6 every time you click the command button. For example,
let's say the random number generated is 0.98, after multiplying it by 6, it
becomes 5.88, and using the integer function Int(5.88) will convert the
number to 5; and after adding 1 you will get 6.
The Output is shown in Figure 15.5
Figure 15.5
15.7 The Round Function
The Round function is the function that rounds up a number to a certain
2) =7.26
Label1.Text = Math.Round(Val(TextBox1.Text), n)
End Sub
The Output is shown in Figure 15.6
Figure 15.6
Summary
In section 15.1, you have learned how to use the Abs function
In section 15.2, you have learned how to use the Exp function
In section 15.3, you have learned how to use the Fix function
● In section 15.4, you have learned how to use the Int function
In section 15.5, you have learned how to use the Log function
● In section 15.6, you have learned how to use the Rnd function
In section 15.7, you have learned how to use the Round function
Chapter 16 The Format Function
The Format function is used to display numbers as well as date and time in
various formats.
16.1 Format Function for Numbers
There are two types of Format functions for numbers; one of them is the
built-in or predefined format while another one can be defined by the user.
Example 16.1 Formatting Numbers
Handles BtnFormat.Click
End Sub
Figure 16.1
Example 16.2 Using User-Defined Formats
Handles BtnFormat.Click
End Sub
Figure 16.2
16.2 Formatting Date and Time
There are two types of Format functions for Date and time one of them is
the built-in or predefined format while another one can be defined by the
user.
Format Description
Handles BtnDisplay.Click
End Sub
Figure 16.3
You can display dates and time in real-time using a timer and set its
property Enabled to true and interval 100. The code is as follows:
Timer1.Tick
End Sub
Besides using the predefined formats, you can also use the user-defined
formatting functions. The syntax of a user-defined format for date and time
is
Format(expression,style)
Table 16.4 User-Defined Formats
Format Description
Format (Now, "mmm,d,yyyy") Displays current date in the Month, Day, Year Format
Timer1.Tick
End Sub
check box or check boxes concerned. For example, in the Font dialog box
many checkboxes under the Effects section such as that shown in the
diagram below. The user can choose underline, subscript, small caps,
superscript, blink and more. In VB 2022, you may create a shopping cart
where the user can click on checkboxes that correspond to the items they
intend to buy, and the total payment can be computed at the same time.
In this example, we add a few labels, two buttons and six checkboxes. We
declare the price of each item using the Const keyword. If a checkbox is
being ticked, its state become True else its state is False . To calculate the
total amount of purchase, we use the mathematical operator +=. For
example, sum+=IPhone is sum =sum+IPhone . Finally, we use the
ToString method to display the amount in currency. The code is shown
overleaf.
The Code
Private Sub BtnCal_Click(sender As Object, e As EventArgs) Handles
BtnCal.Click
sum += IPhone
End If
sum += Samsung
End If
sum += Huawei
End If
sum += Xiaomi
End If
sum += Vivo
End If
sum += Oppo
End If
LblTotal.Text = sum.ToString("c")
End Sub
CheckBox1.Checked = False
CheckBox2.Checked = False
CheckBox3.Checked = False
CheckBox4.Checked = False
CheckBox5.Checked = False
CheckBox6.Checked = False
End Sub
sum += large
End If
sum += medium
End If
sum += small
End If
Label5.Text = sum.ToString("c")
End Sub
In this example, the text on the label can be formatting using the three
check boxes that represent bold, italic and underline.
The Code
If ChkBold.Checked Then
Else
End If
End Sub
If ChkItalic.Checked Then
Else
End If
End Sub
If ChkUnder.Checked Then
Else
End If
End Sub
will retain the original font type but change it to italic font style.
will also retain the original font type but change it to regular font style. (The
other statements employ the same logic)
In this example, the user can only choose one T-shirt color. To design the
interface, add three radio buttons and name them as RadioRed, RadioGreen
and RadioYellow respectively. Besides that, add a button to confirm the
chosen color and a label control to display the chosen color. Name the
button as BtnConfirm and the label as LblDisplay. We use the
If...Then...Else decision-making structure to construct the program. The
state of the radio button is indicated by its checked property.
The code
Handles BtnConfirm.Click
If RadioRed.Checked Then
LblDisplay.ForeColor = Color.Red
LblDisplay.ForeColor = Color.Green
LblDisplay.ForeColor = Color.Blue
ElseIf RadioPink.Checked Then
LblDisplay.ForeColor = Color.Pink
ElseIf RadioOrange.Checked Then
LblDisplay.ForeColor = Color.Orange
Else
LblDisplay.ForeColor = Color.Yellow
End If
LblDisplay.Text = Tcolor
End Sub
Although radio buttons only allow the user to select one item at a time,
he/she may make more than one selection if those items belong to different
categories. For example, the user wishes to choose T-shirt size and color, he
needs to select one color and one size, which means one selection in each
category. In this case, we must group the radio buttons together according
to the categories. This is easily achieved in using the Groupbox control
under the container's categories.
After inserting the Groupbox from the toolbox into the form, you can
proceed to insert the radio buttons into the Groupbox . Only the radio
buttons inside the Groupbox are mutually exclusive, they are not mutually
exclusive with the radio buttons outside the Groupbox. In this example, the
user can select one color and one size of the T-shirt. To design the interface,
insert two group boxes. In the first group box, add four radio buttons and
name them as RadioXL, RadioL, RadioM and RadioS respectively. In the
second group box, add three radio buttons and name them RadioRed,
RadioBlue and RadioBeige respectively. Besides that, insert two Label
controls to display the chosen size and color, name them LblSize and
LblColor respectively. Finally, add a button and name it as BtnConfirm. In
the code, we shall declare the variable TSize to indicate the T-shirt size. We
also write code to change the background color of LblColor to match the
selected color.
The Code
Handles BtnConfirm.Click
If RadioXL.Checked Then
TSize = "XL"
TSize = "L"
TSize = "M"
End If
If RadioRed.Checked Then
LblColor.BackColor = Color.DarkRed
ElseIf RadioBlue.Checked Then
LblColor.BackColor = Color.Blue
ElseIf RadioGreen.Checked Then
LblColor.BackColor = Color.Green
ElseIf RadioPink.Checked Then
LblColor.BackColor = Color.DeepPink
ElseIf RadioOrange.Checked Then
LblColor.BackColor = Color.DarkOrange
Else : LblColor.BackColor = Color.Yellow
LblSize.Text = TSize
End Sub
Summary
● In section 17.1, you have learned how to use the check box.
● In section 17.2, you have learned how to use the radio button
Chapter 18 Errors Handling
Error handling is an essential procedure in Visual Basic 2022 programming
because it helps make a program error-free. Error-free code not only
enables the program to run smoothly and efficiently, but it can also prevent
all sorts of problems from happening like program crashes or system hangs.
Errors often occur due to incorrect input from the user. For example, the
user might make the mistake of attempting to enter text (string) to a box
that is designed to handle only numeric values such as the weight of a
person, the computer will not be able to perform arithmetic calculation for
text therefore will create an error. These errors are known as synchronous
errors.
Visual Basic 2022 has improved a lot in its built-in errors handling
capabilities compared to Visual Basic 6. For example, when the user
attempts to divide a number by zero, Visual Basic 2022 will not return an
error message but gives the ‘infinity’ as the answer (although this is
mathematically incorrect, because it should be undefined)
18.1 Using On Error GoTo Syntax
Visual Basic 2022 still supports the VB6 errors handling syntax that is the
error handling method, we shall deal with that later. We shall now learn how
to write error handling code in Visual Basic 2022. The syntax for error
handling is
The Code
BtnCal.Click
Lbl_ErrMsg.Visible = False
firstNum = TxtNum1.Text
secondNum = TxtNum2.Text
Exit Sub 'To prevent error handling even the inputs are valid
error_handler:
Lbl_Answer.Text = "Error"
Lbl_ErrMsg.Visible = True
again!"
End Sub
*Please note that division by zero in Visual Basic 2022 no longer gives an
Try
statements
End Try
Lbl_ErrMsg.Visible = False
Try
firstNum = TxtNum1.Text
secondNum = TxtNum2.Text
LblAnswer.Text = answer
Catch ex As Exception
LblAnswer.Text = "Error"
Lbl_ErrMsg.Visible = True
End Try
End Sub
Figure 18.2
Summary
● In section 18.1, you have learned the concept of errors handling.
● In section 18.2, you have learned how to handle errors using On Error
Goto Syntax
● In section 18.3, you have learned how to handle errors using Try…
Catch…End Try Structure
Chapter 19 Object-Oriented Programming
19.1 Concepts of Object-Oriented Programming
In all the preceding chapters, you have learned how to write the program
code in Visual Basic 2022, but we have not discussed the concepts of
object-oriented programming that forms the foundation of Visual Basic
2022. Now, let us get down to learning the basic concepts of object-oriented
programming.
(a) Encapsulation
(b) Inheritance
(c) Polymorphism
'Data Members
'Methods
MessageBox.Show(Name)
MessageBox.Show(Birthdate)
MessageBox.Show(Gender)
MessageBox.Show(Age)
End Sub
End Class
Another Example:
'Data Members
'Methods
MessageBox.Show(Brand)
MessageBox.Show(Model)
MessageBox.Show(Year Made)
MessageBox.Show(Capacity)
End Sub
End Class
Let us look at one example on how to create a class. The following example
shows you how to create a class that can calculate your BMI (Body Mass
Index).
The default class Class1.vb will appear as a new tab with a code window.
Rename the class as MyClass.vb. Rename the form as MyFirstClass.vb.
Now, in the MyClass.vb window, create a new class MyClass1 and enter the
following code
End Function
End Class
Now you have created a class (an object) called MyClass1 with a method
known as BMI. To use the BMI class, insert a button into the form and click
on the button to enter the following code.
Dim h, w As Single
MessageBox.Show(MyObject.BMI(h, w))
End Sub
When you run this program and click the button, the user will be presented
with two input boxes to enter his or her height and weight subsequently and
the value of BMI will be shown in a pop-up message box, as shown in the
figures below:
Figure 19.2
Figure 19.3
Figure 19.4
Example 19.2 Examination Class
We create the examination class to compute the grades of an examination.
Create a new class and rename it ExamCalss. Enter the code as follows.
Public Class ExamClass
Public Function grade(ByVal mark As Integer) As String
Select Case mark
Case 0 To 19
grade = "F"
Case 20 To 29
grade = "E"
Case 30 To 39
grade = "D"
Case 40 To 59
grade = "C"
Case 60 To 79
grade = "B"
Case 80 To 100
grade = "A"
Case Else
grade = "Error!"
End Select
End Function
End Class
Having create the ExamGrade class, we can use this class by creating the
windows form program, as follows.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles
Btn_Compute.Click
Dim mrk As Integer
Dim myGrade As New ExamClass
mrk = Txt_Mark.Text
Lbl_Grade.Text = myGrade.grade(mrk)
End Sub
The Output
Figure 19.2
Example 19.3 Future Value Class
The calculation is based on the investment amount (Also known as present
value or simply PV), the compound interest rate and the number of years
from now. The formula to calculate this future value is
FV = PV * (1 + i / 100)n)
We will use a class to create the function(method) to calculate the FV based
on three arguments, PV, interest rate and number of years. Insert a class and
name it as ClsFV. Enter the following code for ClsFV.
Public Function FV(ByVal PV As Double, ByVal Num_Year As Single,
ByVal Int_Rate As Single)
FV = Format(PV * (1 + Int_Rate / 100) ^ Num_Year, "$#,##0.00")
End Function
Next, design a form to compute the future value. Insert three text boxes to
accept the values for present value, number of years and interest rate. In
addition, insert a label to display the value of the future value. Enter the
code as follows.
Private Sub Btn_Cal_Click(sender As Object, e As EventArgs) Handles
Btn_Cal.Click
Dim PVal As Double
Dim num_y, i As Single
Dim FValue As New ClsFV
PVal = Txt_PV.Text
num_y = Txt_NumYear.Text
i = Txt_Interest.Text
Lbl_FV.Text = FValue.FV(PVal, num_y, i)
End Sub
The Output
Figure 19.3
Summary
● In section 19.1, you have learned the concepts of object-oriented
programming.
● In section 19.2, you have learned how to create a class.
Chapter 20 Creating Graphics
20.1 Introduction to Graphics Creation
Creating graphics is easy in earlier versions of Visual Basic because they
have built-in drawing tools. For example, In Visual Basic 6, the drawing
tools are included in the toolbox where the programmer just needs to drag
the shape controls into the form to create a rectangle, square, ellipse, circle
and more. However, its simplicity has the shortcomings; you do not have
many choices in creating customized graphics.
To draw graphics on the default form, you can use the following statement:
You can also use the text box as a drawing surface, the statement is:
The Graphics object that is created does not draw anything on the screen
until you call the methods of the Graphics object. In addition, you must
create the Pen object as the drawing tool. We shall examine the code that
myPen is a Pen variable. You can use any variable name instead of myPen.
The first argument of the pen object defines the color of the drawing line
and the second argument defines the width of the drawing line. For
example, the following code created a pen that can draw a dark magenta
line and the width of the line is 10 pixels:
Where the first argument defines the color and the second argument is the
width of the drawing line.
Having created the Graphics and the Pen objects, you are now ready to
First, launch Visual basic 2022. In the startup page, drag a button into the
form. Double click on the button and key in the following code.
BtnDraw.Click
End Sub
The second line of the code creates the Graphics object and the third and
fourth line create the Pen object. The fifth draws a line on the Form using
the DrawLine method. The first argument uses the Pen object created by
you, the second argument and the third arguments define the coordinate the
starting point of the line, the fourth and the last arguments define the ending
Figure 20.1
20.5 Drawing Lines that Connect Multiple Points
In section 20.4, we have learned to draw a straight line that connects two
points. Now we shall learn how to draw straight lines that connect multiple
points. The method is Drawlines and the syntax is:
Graphics.DrawLines(Pen, Point())
Notice that the method to draw a straight line is DrawLine whilst the
method to draw multiple lines is Drawlines, by adding an extra s. The
points can be defined using the Point() array with the following syntax:
Handles BtnDrawLine.Click
point6, point7}
End Sub
The output interface is as shown in Figure 20.2
Figure 20.2
20.6 Drawing a curve that Connect Multiple
Points
We have learned how to draw straight lines that connect multiple points.
Now, we shall learn how to draw a curve that connects multiple points. To
draw a curve, we use the DrawCurve() method and the syntax is
Graphics.DrawCurve(Pen, Point())
The points can be defined using the Point() array with the following syntax:
Handles BtnDrawCurve.Click
point6, point7}
End Sub
The output interface is as shown in Figure 20.3
Figure 20.3
20.7 Drawing a Quadratic Curve
In this section, we shall learn how to draw a quadratic curve. However, we
must adjust the coordinate system of the drawing surface. The default origin
of the drawing surface of the VB2022 object such as the form or the picture
box is at the upper left corner. We can move its origin to another point using
follows:
MyGraphics.TranslateTransform(dx:=x1, dy:=y1)
where (x1,y1) is the new origin.
Example 20.3 Drawing the Quadratic
y=x2-3x+1
First, we insert a picture box as a drawing canvas. Set its size to 500, 300
which means its width=500 pixels and height=300 pixels. We wish to move
the origin to the middle of x-axis and close to x-axis, so we set its origin
using the following syntax:
myGraphics.TranslateTransform(dx:=250, dy:=295)
Next, we must declare a point array so that we can use the For...Next loop
to generate points for the quadratic equation. After generating the points,
we can use the DrawCurve method to draw the curve.
The equation x = i - 250 is to make sure the point starts from -250 and
ends at 250. The equation y =300 - (x ^ 2 - 3 * x + 1) is to ensure the point
starts from the bottom instead of the top of the drawing canvas. We divide it
by 200 to reduce the values of the y-coordinates so that it will not go out of
bounds.
The Code
Handles BtnDrawCurve.Click
x = i - 250
Next
myGraphics.DrawCurve(myPen, p)
myGraphics.Dispose()
End Sub
The output is as shown in Figure 20.4.
Figure 20.4
20.8 Drawing a Sine Curve
The Sin function returns the sine value of an angle. We must convert the
angle to radian as Visual Basic 2022 cannot deal with an angle in degrees.
The conversion is based on the following equation:
π radian= 180º
so 1º=π/180 radian
To get the exact value of π, we use the arc sine function, i.e. is Asin. Using
the equation sin(π/2)=1, so Asin(1)=π/2, therefore, π=2Asin(1). Therefore,
The syntax of the Sin function in Visual Basic 2022 is
Math.Sin(Angle in radian)
In this example, we insert a picture box and fix its size as 600, 300 which
means its width is 600 and its height is 300. We shift the origin to (300,
180) using the TranslateTransform method. The sine function is:
y = -(Math.Sin((pi * x) / 180)) * 80
The Code
Handles BtnDrawCurve.Click
pi = 2 * Math.Asin(1)
x = i - 300
Next
myGraphics.DrawCurve(myPen, p)
myGraphics.Dispose()
End Sub
Figure 20.5
20.8 Drawing a Rectangle
To draw a rectangle on the default form in Visual Basic 2022, there are two
ways:
and its width and height. You also must create a Graphics and a Pen object
to handle the actual drawing. The method of the Graphics object to draw the
rectangle is DrawRectangle .
myPen is the variable name of the Pen object created by you. You can use
upper left corner of the rectangle while width and height are self-
(ii) The second way is to create a rectangle object first and then draw this
triangle using the DrawRectangle method. The syntax is as shown below:
myGraphics.DrawRectangle(myPen,myRectangle)
myRect.X = 10
myRect.Y = 10
myRect.Width = 100
myRect.Height = 50
You can also create a rectangle object using a one-line code as follows:
myGraphics.DrawRectangle(myPen, myRectangle)
20.9 Customizing Line Style of the Pen Object
The shapes we draw so far are drawn with a solid line, we can customize
the line style of the Pen object so that we have dotted line, line consisting of
dashes and more. For example, the syntax to draw with a dotted line is
shown below.
myPen.DashStyle=Drawing.Drawing2D.DashStyle.Dot
The last argument Dot specifies a line DashStyle value, a line that makes up
of dots. Other DashStyles values are Dash, DashDot, DashDotDot and
Solid . The following code draws a rectangle with a blue dotted line, as
shown in Figure 20.6.
myPen.DashStyle = Drawing.Drawing2D.DashStyle.Dot
End Sub
Figure 20.6
If you change the DashStyle value to DashDotDot, you will get the
rectangle as shown in Figure 20.7
Figure 20.7
20.10 Drawing an Ellipse
Now we shall learn how to draw ellipses and circles. First, we must
understand the principle behind drawing an ellipse in Visual Basic 2022.
The basic structure of most shapes is a rectangle, ellipse is no exception.
myGraphics.DrawEllipse(myPen, myRectangle)
BtnDraw.Click
Rectangle
myRectangle.X = 40
myRectangle.Y = 30
myRectangle.Width = 200
myRectangle.Height = 100
myGraphics.DrawEllipse(myPen, myRectangle)
End Sub
Figure 20.8
rectangle object. Of course, you still must create the Graphics and the Pen
Where (X,Y) are the coordinates of the upper left corner of the bounding
rectangle, width is the width of the ellipse and height is the height of the
ellipse.
BtnDraw.Click
End Sub
20.11 Drawing a Circle
After you have learned how to draw an ellipse, drawing a circle becomes
very simple. We use the same methods used in the preceding section but
modify the width and height so that they are of the same values.
myRectangle.X = 90
myRectangle.Y = 30
myRectangle.Width = 100
myRectangle.Height = 100
myGraphics.DrawEllipse(myPen, myRectangle)
Where myGraphics is the Graphics object, myText is the text you wish to
display on the screen, myFont is the font object created by you, myBrush is
the brush style created by you and X, Y are the coordinates of upper left
You can create the Font object in visual basic 2022 using the following
statement:
Where the first argument of the font is the font typeface, and the second
argument is the font size. You can add a third argument as font style, either
bold, italic, underline. Here are the examples:
To create your Brush object, you can use the following statement:
Dim myBrush As Brush
Besides the seven colors, some of the common Brush colors are AliceBlue,
AquaMarine Beige, DarkMagenta, DrarkOliveGreen, SkyBlue and more.
You do not have to remember the names of all the colors, the intelliSense
will let you browse through the colors in a drop-down menu once you type
the dot after the word Color.
Now we shall proceed to draw the font using the sample code in Example
20.8.
BtnDraw.Click
FontStyle.Underline)
End Sub
You can also add an Input box which let the user enter his or her message
then display the message on the screen. Besides that, you can insert a
picture box and draw text on it instead of drawing on the form. In this
example, insert a picture box and rename it as MyPicBox. Now, when you
declare the Graphics object, you use the object MyPicBox instead of Me
Handles BtnDrawText.Click
FontStyle.Underline)
End Sub
Figure 20.11
Figure 20.12
20.13 Drawing Polygons
Polygon is a closed plane figure bounded by three or more straight sides. In
order to draw a polygon on the screen, we must define the coordinates of all
the points (also known as vertices) that joined up to form the polygon. The
syntax to define the points of a polygon with vertices A1,A2,A3,A4…An is
as follows.
After declaring the points, we must define a point structure that group all
the points together using the following syntax:
Finally, create the graphics object and use the DrawPolygon method to
draw the polygon using the following syntax:
myGraphics.DrawPolygon(myPen, myPoints)
where myPen is the Pen object created using the following syntax:
BtnDraw.Click
myGraphics.DrawPolygon(myPen, myPoints)
End Sub
BtnDraw.Click
myGraphics.DrawPolygon(myPen, myPoints)
End Sub
Figure 20.14
20.14 Drawing a Pie
In order to draw a pie, you can use the DrawPie method of the graphics
object. As usual, you must create the Graphics and the Pen objects. The
BtnDraw.Click
End Sub
In order to fill the above shapes with color, we must create the Brush object
using the following syntax:
myColor can be any color such as red, blue, yellow and more. You do not
have to worry about the names of the colors because the intellisense will
display the colors and enter the period after the Color keyword.
In Visual Basic 2022, the syntax to fill a rectangle with the color defined by
the brush object is:
myGraphics.FillRectangle (myBrush, 0, 0, 150, 150)
End Sub
Figure 20.16
End Sub
*If you omit the line myGraphics.DrawEllipse(myPen, 50, 50, 180, 100) ,
you will get a solid ellipse without outline.
20.15.3 Drawing and Filling a Polygon with Color
The syntax to fill a polygon with the color defined by the brush object is:
myGraphics.FillPolygon(myBrush, myPoints)
Example 20.17 Drawing a Polygon and Color It
BtnDraw.Click
myGraphics.DrawPolygon(myPen, myPoints)
myGraphics.FillPolygon(myBrush, myPoints)
End Sub
Figure 20.19
The syntax to fill a pie with the color defined by the brush object is:
myGraphics.FillPie(myBrush, X, Y, width, height, StartAngle,
SweepAngle)
End Sub
Figure 20.20
Summary
● In section 20.1, you have understood the concept of graphics creation.
In section 20.2, you have learned how to create the Graphics object.
● In section 20.3, you have learned how to create the Pen object.
● In section 20.4, you have learned how to draw a line.
● In section 20.5, you have learned how to draw a rectangle
● In section 20.6, you have learned how to customize line style.
● In section 20.7, you have learned how to draw an ellipse.
● In section 20.8, you have learned how to draw a circle.
● In section 20.9, you have learned how to draw a polygon.
● In section 20.10, you have learned how to draw a pie.
● In section 20.12, you have learned how to fill shapes with colors.
Chapter 21 Using Timer
Timer control can be used to program events that are time related. For
example, you can use the timer control to create a clock, a stopwatch, a
dice, an animation and more. Timer is a hidden control at runtime, like the
engine of an automobile. We shall illustrate the usage of timer through a
few examples.
To create the clock, first, start a new project in Visual Basic 2022 and select
a new Windows Application. You can give the project any name you wish,
but we will name it MyClock . Change the text of Form1 to MyClock in
the properties window. Add the Timer control to the form by double-
clicking it in the ToolBox.
Next, insert a label control into the form. Change the Font size of the label
to any size you wish and set the Font alignment to be middle center. Before
we forget, you shall also set the Interval property of the Timer control to
1000, which reflects a one second interval (1 unit is 1 millisecond).
Remember to set the MaximizeBox property of Form1 to false so that the
user cannot enlarge the clock. You also must ensure that the Enabled
property of the Timer control is set to True so that the clock starts running
as soon as it is loaded.
Now, you are ready for coding. You would be surprised at what you must
create a clock is only a one-line code, that is:
Label1.Text = TimeOfDay
* TimeOfDay() is a function that returns the current time today based on
your computer system’s time.
Click on the Timer control and enter the code as shown below:
LblClock.Text = TimeOfDay
End Sub
Figure 21.1
Timer1.Enabled = True
End Sub
LblPanel.Text = Val(LblPanel.Text) + 1
End Sub
Timer1.Enabled = False
End Sub
LblPanel.Text = 0
End Sub
We can create a digital dice easily using the Timer Control. To create a dice,
you must generate random numbers using the Rnd function. The Rnd
function generates numbers between 0 and 1. However, you must use the
Int function to obtain random integers. The following statement generates
random integers from 1 to 6 is as follows:
n = Int(1 + Rnd() * 6)
In the code, we introduce the variable m to control the length of time of the
rolling process. If m is more than 1000, then the rolling process will stop by
setting the timer enabled property to False. Set the timer interval to 10 so
that the number changes every 0.01 second.
The Code
Dim n, m As Integer
m = m + 10
n = Int(1 + Rnd() * 6)
LblDice.Text = n
Else
Timer1.Enabled = False
m = 0
End If
End Sub
Timer1.Enabled = True
End Sub
Running the program produces a dice with fast changing numbers which
stops at a certain number. The interface is as shown in Figure 21.3
Figure 21.3
Summary
● In section 21.1, you have learned how to create a digital clock.
● In section 21.2, you have learned how to create a digital stopwatch.
● In section 21.3, you have learned how to create a digital dice.
Chapter 22 Creating Animation
First, insert a picture box into the form. In the picture box properties
window, select the image property and click to import an image file from
your storage devices such as your hard drive, your pen drive or DVD drive.
We have inserted an image of a bunch of grapes. Next, insert a Timer
control into the form and set its interval property to 100, which is
equivalent to 0.1 second. Last, add two buttons to the form, name one of
them as AnimateBtn and the other one as StopBtn , and change the
caption to Animate and Stop respectively.
We make use of the Left property of the picture box to create the motion.
PictureBox.Left means the distance of the PictureBox from the left border
of the Form. Now click on the Timer control and type in the following
code:
Else
PictureBox1.Left = 0
End If
End Sub
In the code above, Me.Width represents the width of the Form. If the
distance of the PictureBox from the left is less than the width of the Form, a
value of 10 is added to the distance of the PictureBox from the left border
each time the Timer tick, or every 0.1 second in this example. When the
distance of the PictureBox from the left border is equal to the width of the
form, the distance from the left border is set to 0, which moves the
PictureBox object to the left border and then moves left again, thus creating
an oscillating motion from left to right. We must insert a button to stop the
motion. The code is:
Timer1.Enabled = False
To animate the PictureBox object, we insert a button and enter the
following code:
Timer1.Enabled = True
Figure 22.1 The runtime interface
In this program, we must insert a timer and set its interval to 100, which
means the drawings will refresh every 0.1 second. Next, insert a picture box
which is used as the surface of a dice. Finally, add a button and change its
text to Roll. Under the Timer sub procedure, we create the Graphics object
and the Pen object following the procedures we have learned in preceding
chapters. Next, we use a Do loop and the Select Case structure to cycle
through all six surfaces of the dice. To create six random cases, we use the
The code
BtnRoll.Click
Timer1.Enabled = True
End Sub
Timer1.Tick
Dim t As Integer
t = 0
Do
MyPicBox.Refresh()
Dim n As Integer
n = Int(6 * Rnd()) + 1
Select Case n
Case 1
Case 2
Case 3
Case 4
Case 5
Case 6
End Select
t = t + 1
Timer1.Enabled = False
End Sub
This is a slot machine created using timer. In this program, we add three
picture boxes, a timer, a button and a label. Set the timer interval to 10,
which means the images will refresh every 0.01 second. In the code, we
shall introduce four variables m, a, b and c, where m is used to stop the
timer and a, b, c are used to generate random images using the syntax Int(1
+ Rnd() * 3) . To load the images, we use the following syntax:
PictureBox.Image = Image.FromFile(Path of the image file)
We employ the If...Then structure to control the timer and the Select
Case...End Select structure to generate the random images. The label is
used to display the message of the outcomes.
The Code
Dim m, a, b, c As Integer
Private Sub BtnSpin_Click(sender As Object, e As EventArgs) Handles
BtnSpin.Click
Timer1.Enabled = True
End Sub
m = m + 10
a = Int(1 + Rnd() *
3) b = Int(1 +
Rnd() * 3) c =
Int(1 + Rnd() * 3)
Select Case a
Case 1
PictureBox1.Image = Image.FromFile("C:\Image\apple.gif")
Case 2
PictureBox1.Image = Image.FromFile("C:\Image\grape.gif")
Case 3
PictureBox1.Image = Image.FromFile("C:\Image\strawberry.gif")
End Select
Select Case b
Case 1
PictureBox2.Image = Image.FromFile("C:\Image\apple.gif")
Case 2
PictureBox2.Image = Image.FromFile("C:\Image\grape.gif")
Case 3
PictureBox2.Image = Image.FromFile("C:\Image\strawberry.gif")
End Select
Select Case c
Case 1
PictureBox3.Image = Image.FromFile("C:\Image\apple.gif")
Case 2
PictureBox3.Image = Image.FromFile("C:\Image\grape.gif")
Case 3
PictureBox3.Image = Image.FromFile("C:\Image\strawberry.gif")
End Select
Else
Timer1.Enabled = False
m = 0
If a = b And b = c Then
Else
End If
End If
End Sub
The runtime interface is shown in Figure 32.3
Figure 32.3
Summary
● In section 22.1, you have learned how to create motion.
● In section 22.2, you have learned how to create a graphical dice.
● In section 22.3, you have learned how to create a slot machine.
Chapter 23 Working with Databases
23.1 Introduction to Database
In our daily life, we deal with many types of information such as names,
addresses, money, date, stock quotes, statistics and more. If you are in
business or working as a professional, you must handle even more data. For
example, a doctor needs to keep track of patients’ personal and medical
information such as names, addresses, phone numbers as well as blood
pressure readings, blood sugar readings, surgical history, medicines
prescribed in the past and more. On the other hand, businesses usually must
manage a large amount of data pertaining to products and customers. All
these data must be organized into a database for ease of data management.
In the past, people usually dealt with data manually like using cards and
folders. However, in the present day fast paced global environment and
faster, more accurate and more efficient than human beings do. With the
advent of the network and the Internet technologies, data can now be
https://www.microsoft.com/en-us/sql-server/sql-server-downloads
To begin building the database project in Visual Basic 2022, launch Visual
Basic 2022. You can name your project as Database Project 1 or whatever
name you wish to call it. Next, change the default form’s Text property to
objects in ADO.NET that are required to build the database. There are:
with them. To reference the ADO.NET object, choose project from the
properties. Next click the References tab to show the active references for
Figure 23.1
https://docs.microsoft.com/en-us/sql/ssms/download-sql-server-
management-studio-ssms
Figure 23.2
After clicking the ‘Connect’ button, SSMS wil be connected to SQL server,
as shown in Figure 23.3
Figure 23.3
You can also disconnect from the SQL server anytime you wish. Next, we
Clicking on New Database will bring out the New Database window, where
you can create a new database by entering the database name as well as
Figure 23.5
Figure 23.6
After creating the database, we must create a table called cuslist. To create
the table, expand the customer database and right click on the table to bring
up the table design window that allows you to key in the fields under
column name and you can specify their data types such as string, numeric ,
money and so on. In our example, we create four fields, CusName,
PhoneNum, State and Income. Save the table as cuslist.
To enter data in the table, right click on the table name to bring a list of
options, select Edit Top 200 Rows from the options to bring up the table for
you to enter the data, as shown in Figure 23.7.
Figure 23.7
Now we are ready to write the code to access the database we have created.
You must detach the file from SQL Server Management Studio and copy
the file to another location before you can access it from Visual Basic
2022. To detach a database file, right click on the file and select Task, then
click o Detach, as shown in Figure 23.8.
Figure 23.8
Having created the instance of the SqlConnecton object, the next step is
to establish a connection to the data source using the SQL
ConnectionString property. The syntax is:
After establishing a connection to the database, you can open the database
using the following syntax:
MyCn.Open()
23.4 Populating Data in ADO.NET
Establishing a connection to a database in Visual Basic 2022 using
SqlConnection alone will not present anything tangible to the user to
manipulate the data until we add more relevant objects and write relevant
codes to the project.
Besides that, we must declare a variable to keep track of the user’s current
row within the data table. The statement is
Having created the above of objects, you must include the following
statements in the Sub Form_Load event to start filling the DataTable with
data from the data source. The statements are as follows:
MyDatAdp.Fill(MyDataTbl)
After filling up the DataTable , we must write code to access the data. To
access data in the DataTable means that we must access the rows in the
table. We can achieve this by using the DataRow object. For example, we
can write the following to access the first row of the table and present the
data via two text boxes with the name txtName and txtState respectively:
strName = MyDataRow("ContactName")
strState = MyDataRow("State")
txtName.Text = strName.ToString
txtState.Text = strState.ToStringMe.showRecords()
* The two fields being referenced here are ContactName and State. Note
Index 0 means first row.
If MyDataTbl.Rows.Count = 0 Then
txtName.Text = ""
txtState.Text = ""
Exit Sub
End If
txtName.Text = MyDataTbl.Rows(MyRowPosition)
("ContactName").ToString
txtState.Text = MyDataTbl.Rows(MyRowPosition)("State").ToString
End Sub
MyBase.Load
AttachDbFilename=C:\Users\Documents\vb2022\customer.mdf;
Integrated Security=True; Connection Timeout=30;" & "User
Instance=True"
MyCn.Open()
MyDatAdp.Fill(MyDataTbl)
Me.showRecords()
End Sub
If MyDataTbl.Rows.Count = 0 Then
End If
TxtCusName.Text = MyDataTbl.Rows(MyRowPosition)
("CusName").ToString()
("PhoneNum").ToString()
("State").ToString()
("Income").ToString()
End Sub
Figure 23.10
23.5 Browsing Records
In the previous section, we have learned how to display the first record
using the showRecords sub procedure. In this chapter, we will create
command buttons and write relevant codes to allow the user to browse the
records forward and backward as well as fast forward to the last record and
back to the first record. The first button we must create is for the user to
browse the first record. We can use the button's text << to indicate to the
user that it is the button to move to the first record and button’s text >> to
move to the last record. Besides, we can use button’s text < for moving to
the previous record and button’s text > for moving to the next record.
Me.showRecords()
MyRowPosition = MyRowPosition - 1
Me.showRecords()
End If
The code for moving to next record is
MyRowPosition = MyRowPosition + 1
Me.showRecords()
End If
The code for moving to last record is
If MyDataTbl.Rows.Count > 0 Then
MyRowPosition = MyDataTbl.Rows.Count - 1
Me.showRecords()
End If
23.6 Editing, Saving, Adding and Deleting
Records
You can edit any record by navigating to the record and change the data
values. However, you must save the data after editing them. You must use
the update method of the SqlDataAdapter to save the data. The code is:
MyDataTbl.Rows(MyRowPosition)("ContactName") = txtName.Text
MyDataTbl.Rows(MyRowPosition)("state") = txtState.Text
MyDatAdp.Update(MyDataTbl)
End If
You can also add new record or new row to the table using the following
code:
MyDataTbl.Rows.Add(MyNewRow)
MyRowPosition = MyDataTbl.Rows.Count - 1
Me.showRecords()
The code above will present a new record with blank fields for the user to
enter the new data. After entering the data, he or she can then click the save
button to save the data.
Lastly, the user might want to delete the data. Remember to add a primary
key to one of the fields in the database, otherwise it will not work. The code
to delete the data is:
If MyDataTbl.Rows.Count <> 0 Then
MyDataTbl.Rows(MyRowPosition).Delete()
MyDatAdp.Update(MyDataTbl)
MyRowPosition = 0
Me.showRecords()
End If
The complete code is shown in Example 23.2
MyCn.Close()
MyCn.Dispose()
End Sub
MyCn.Open()
MyDatAdp.Fill(MyDataTbl)
Me.showRecords()
End Sub
If MyDataTbl.Rows.Count = 0 Then
End If
TxtCusName.Text = MyDataTbl.Rows(MyRowPosition)
("CusName").ToString()
TxtContact.Text = MyDataTbl.Rows(MyRowPosition)
("PhoneNum").ToString()
TxtState.Text = MyDataTbl.Rows(MyRowPosition)("State").ToString()
TxtIncome.Text = MyDataTbl.Rows(MyRowPosition)
("Income").ToString()
End Sub
Private Sub BtnMoveFirst_Click(sender As Object, e As EventArgs)
Handles BtnMoveFirst.Click
MyRowPosition = 0
Me.showRecords()
End Sub
MyRowPosition = MyRowPosition - 1
Me.showRecords()
End If
End Sub
MyRowPosition = MyRowPosition + 1
Me.showRecords()
End If
End Sub
MyRowPosition = MyDataTbl.Rows.Count - 1
Me.showRecords()
End If
End Sub
MyDataTbl.Rows.Add(MyNewRow)
MyRowPosition = MyDataTbl.Rows.Count - 1
Me.showRecords()
End Sub
MyDataTbl.Rows(MyRowPosition).Delete()
MyRowPosition = 0
MyDatAdp.Update(MyDataTbl)
Me.showRecords()
End If
End Sub
MyDataTbl.Rows(MyRowPosition)("CusName") = TxtCusName.Text
MyDataTbl.Rows(MyRowPosition)("PhoneNum") = TxtContact.Text
MyDataTbl.Rows(MyRowPosition)("state") = TxtState.Text
MyDataTbl.Rows(MyRowPosition)("Income") = TxtIncome.Text
MyDatAdp.Update(MyDataTbl)
End If
End Sub
The output interface is as shown in Figure 23.11
Figure 23.11
23.7 Accessing Database using DataGridView
Another method to access a database is to use the DataGridView control.
DataGridView allows the user to browse the data in a database via a table
that comprises rows and columns. To access the database, use the following
statement:
AttachDbFilename=C:\Users\Documents\vb2022\customer.mdf;
Instance=True"
To use the DataGridView control, drag it from the toolbox and insert it into
the form. Next, insert a button and rename it as BtnShow. Click the button
and enter the following code, as shown in Example 23.3
Example 23.3 Browsing Data Using DataGridView
AttachDbFilename=C:\Users\Documents\vb2022\customer.mdf;
Instance=True"
BtnShow.Click
from cuslist"
MyAdpt.Fill(Myds, "cuslist")
DataGridView1.DataSource = Myds.Tables(0)
End Sub
The output is shown in Figure 23.12
Figure 23.12
23.8 Performing Arithmetic Calculations in a
Database
In Visual Basic 2022, we can retrieve data from a database and perform
arithmetic calculations. Let’s create a simple database with two columns,
name and income and save it as family.mdf in SQL server. For income, we
must specify it as money or numeric data type to enable calculation. We use
money in our example.
In our example, we wish to calculate the sum of income for all the data. To
perform this calculation, we use SQL keywords, as follows:
We shall modify the code in 23.7 but we add a button so that we can show
the data in a data grid and calculate the total income, as shown in example
23.4.
AttachDbFilename=C:\Users\Documents\vb2022\family.mdf; Integrated
Adpt.Fill(Myds, "mylist")
End Sub
searchValue As String)
myConn.Open()
MyDatApt.SelectCommand = myCommand
LblTotal.Text =
Convert.ToString(Math.Round(myCommand.ExecuteScalar, 2))
End Sub
Handles BtnCalInc.Click
totalIncome(Datastr, searchterm)
End Sub
The Output
Figure 23.13
In the next example, we shall modify the code in Example 23.4 so that we
can calculate the average income as well. In this example, we add a few
more lines of code and a label to display the average income. The code is
shown in Example 23.5
Example 23.5 Calculating Income
AttachDbFilename=C:\Users\Documents\vb2022\family.mdf; Integrated
Adpt.Fill(Myds, "mylist")
DataGridView1.DataSource = Myds.Tables(0)
End Sub
As String)
mylist;"
myConn.Open()
LblTotal.Text =
Convert.ToString(Math.Round(myCommand.ExecuteScalar, 2))
LblAvg.Text =
Convert.ToString(Math.Round(myCommand2.ExecuteScalar, 2))
myConn.Dispose()
End Sub
End Sub
The output is shown in Figure 23.14
Figure 23.14
Besides the SUM and AVG sql Functions, there is also a COUNT function.
The syntax is
In this example, we add another label to show the count value. We impose a
condition where count is executed for income <20000 with the following
statement:
String)
WHERE Income<20000;"
myConn)
myConn.Open()
LblTotal.Text=Convert.ToString(Math.Round(myCommand.ExecuteScalar,
2))
LblAvg.Text
=Convert.ToString(Math.Round(myCommand2.ExecuteScalar, 2))
LblCount.Text
=Convert.ToString(Math.Round(myCommand3.ExecuteScalar, 2))
myConn.Dispose()
End Sub
In this Chapter, we will learn how to create a text file that can store data.
Using text files is an easy way to manage data, although it is not as
sophisticated as full-fledged database management software such as SQL
Server, Microsoft Access and Oracle. Visual Basic 2022 allows the user to
create a text file, save the text file as well as to read the text file. It is
relatively easy to write code for the above purposes in VB2022.
Reading and writing to a text file in VB2022 required the use of the
StreamReader class and the StreamWriter class respectively.
StreamReader is a tool that enables the streaming of data by moving it
from one location to another so that the user can read it. For example, it
allows the user to read a text file that is stored in a hard drive. On the other
hand, the StreamWriter class is a tool that can write data input by the
user to a storage device such as the hard drive.
24.2 Reading a Text File
In order to read a file from the hard disk or any storage device, we must use
the StreamReader class. To achieve that, first we must include the
following statement in the program code:
Imports System.IO
This line must precede the whole program code as it is higher in hierarchy
than the StreamReader Class. In Fact, this is the concept of object-oriented
programming where StreamReader is part of the namespace System.IO.
You must put it on top of the whole program (i.e. above the Public Class
Form 1 statement). The word import means we import the namesapce
System.IO into the program. Once we have done that, we can declare a
variable of the streamReader data type with the following statement:
Now, start a new project and name it in whatever name you wish, we named
it TxtEditor here. Now, insert the OpenFileDialog control into the form
because we will use it to read the file from the storage device. We also must
declare a new OpenFileDialog object before we can use it, you can name it
as OpenFileDialog1 . The OpenFileDialog control will return a
DialogResult value that can determine whether the user clicks the OK
button or Cancel button. We will also insert a command button and change
its displayed text to 'Open'. The user can use it to open and read a certain
text file. The following statement will accomplish the task above.
results = OpenFileDialog1.ShowDialog
Else
End If
Next, insert a textbox, name it TxtEditor and set its Multiline property to
true. It is used for displaying the text from a text file. We also insert a
button and name it BtnOpen. In order to read the text file, we must create a
new instant of the streamReader and connect it to a text file with the
following statement:
In addition, we must use the ReadToEnd method to read the entire text of a
text file and display it in the text box. The syntax is:
TxtEditor.Text = FileReader.ReadToEnd( )
Lastly, we must close the file by using the Close() method. The entire code
is shown in the box below:
The Code
Imports System.IO
results = OpenFileDialog1.ShowDialog
TxtEditor.Text = FileReader.ReadToEnd()
FileReader.Close()
End If
End Sub
Figure 24.2
The code
Imports System.IO
results = SaveFileDialog1.ShowDialog
FileWriter.Write(TxtEditor.Text)
FileWriter.Close()
End If
End Sub
End Class
The Interface is shown in Figure 24.4
Figure 24.4
When you click the save button, the program will prompt you to key in a
filename and the text will be saved as a text file. You can close the text
editor and reopen the text file saved by you.
Summary
● In Section 24.1, you have understood the concepts of reading and
writing a text file.
● In section 24.2, you have learned how to write code to read a text file.
● In Section 24.3, you have learned how to write code to write a text file.
Chapter 25 Building Console Applications
25.1 Introduction
In Visual Basic 2022, you can build console applications besides the
Windows Form Applications. To start creating a console application, start
Visual Basic 2022 and choose Console App(.NET Core) in the new project
window, as shown in Figure 25.1 below:
Figure 25.1
Retain the name as ConsoleApp or change it to the name of your choice.
Now, click on Console Application to bring up the code window. The default
code is
Module Program
Figure 25.2
The console code window comprises modules, where the main module is
module 1. You can add other modules by clicking on Project on the menu bar
and click Add Module, as shown in Figure 25.3 below:
Figure 25.3
Now run the default code, the output is as shown in a command prompt
window in Figure 25.4.
Figure 25.4
Example 25.1: Displaying a Message
Module Program
Sub Main(args As String())
Dim a, b, sum As Integer
a = 2
b = 3
sum = a + b
Console.WriteLine(sum)
End Sub
End Module
The output is as shown in Figure 25.4
25.2 Creating a Text File Writer in Console
We can write a Console app to create a text file in your hard drive or other
storage devices. In order to write a text file to a hard drive or any storage
devices, we must use the StreamWriter class, as we have done the same
thing in Chapter 24. The statement to write a text file with a file name
mytext.txt to your hard drive is as follows:
Dim objWriter As New
System.IO.StreamWriter("C:\Users\Documents\vb2022\mytext.txt")
It will create a text file in the specified location. In addition, we use the
WriteLine() method to write text to the text file.
Example 25.2 Creating a Text File Writer
Module Program
objWriter.Close()
objWriter.Dispose()
End Sub
End Module
The text file as seen in the Notepad is what as shown in Figure 25.5
Figure 25.5
25.3 Creating a Text File Reader in Console
In order to read a text file from your hard drive or any storage devices, we
must use the StreamReader class, as we have done the same thing in
Chapter 24.
Example 25.3 Creating a Text File Reader
Module Program
System.IO.StreamReader("C:\Users\Documents\vb2022\mytext.txt")
Console.WriteLine(strLine)
Loop
Figure 25.6
25.4 Creating a Console App using If...Then...Else
We can use If...Then...Else to create an Arithmetic program in the Console
App.
Example 25.4 Arithmetic Console App
Module Program
Dim answer As Boolean
Dim x, y, sum As Single
x = 5
y = 100
sum = x + y
If sum = 105 Then
answer = True
Else
answer= False
End If
Console.Write(answer)
End Sub
End Module
When you run the application, you will be asked to enter a first number in
an input box, as shown in Figure 25.7
Figure 25.7
Summary
● In Section 25.1, you have created a Console App that display a
Message.
● In section 25.2, you have built a Console App that creates a text file.
● In Section 25.3, you have built a Console App that read a text file.
● In Section 25.4 You have built a Console App that performs arithmetic
calculations involving the usage of If...Then...Else
Chapter 26 Creating Menu Bar and Toolbar
In previous chapters, we have learned how to create buttons that will trigger
an action or a series of actions when the user clicks on them. However,
most standard Windows applications come with very few clickable buttons,
instead, they provide a menu bar and toolbar so that the user can click on
the items on the menu bar or the icons on the toolbar. Besides, the user can
also use the shortcut keys to access the items using the keyboard. In this
chapter, we will show you how to create the menu items on the menu bar
and the icons on the toolbar.
26.1 Creating Menu Items on the Menu Bar
In this section, we will show you how to create Menu Items on the Menu
Bar. We will use the text editor we have created in chapter 24 to demonstrate
how to create the menu bar. Besides, we will delete the buttons as we will
develop the menu bar and toolbar for navigation. Now, open the text editor
in the design mode. Next, insert the MenuStrip control into the form. You
will notice that the MenuStrip control will not appear on the form, instead,
it lies below the form and remains invisible at runtime, as shown in Figure
26.1.
You will also notice that a text box will appear on the top of the form that
displays the tip Type Here, this is where you can type in the top-level menu
item. Here, we type &File in the text box, the ampersand sign is to display
the menu item File with F underlined where the user can use hotkey Alt+F to
access the item. After you type in the first top level item, the second text box
will appear for you to enter the second item. You can enter as many top-level
menu items as the form can accommodate. For our example, we create three
top level menu items, File, Help and About. Next,
Figure 26.1
We shall now create a few items under the File menu item. To do this, click
on the File item and you will get a drop-down text box will the Type Here
tip, Enter &New as the first item. After you enter the first item, another
drop-down text box below the New item will appear, enter Sa&ve in this text
box. Enter &Open and E&xit for the next two text boxes. Now your design
interface should look like the image shown in Figure 26.2. Notice the N is
underlined for New; v is underlined for Save, O is underlined for Open and x
is underlined for Exit.
Next, we must write code for all the menu items so they can respond to
events like clicking the mouse button or pressing a key on the keyboard.
Before we write code for the items, let us create two sub procedures first.
One of them is to create a text file by writing the file to the hard drive or
other storage devices and the other one is to open a text file from the hard
drive or other storage devices. Let us name the first procedure as
WriteFile() and enter the following code:
Sub WriteFile()
FileWriter.Write(TxtEditor.Text)
FileWriter.Close()
End If
End Sub
Figure 26.2
Next, create another sub procedure ReadFile () and enter the following
code:
Sub ReadFile()
TxtEditor.Text = FileReader.ReadToEnd()
FileReader.Close()
End If
End Sub
For the New item, enter the following code:
End Sub
For the Save item, enter the following code:
Me.WriteFile()
End Sub
For the Open item, enter the following code:
Private Sub ToolStripOpen_Click(sender As Object, e As EventArgs)
Handles ToolStripRead.Click
Me.ReadFile()
End Sub
For the Exit item, enter the following code:
TxtEditor.Dispose()
Me.Close()
End Sub
For the Help button, enter the following code
MsgBox("Type some text in the editor and click save to create a text file.
Click New to start a new text file. Click
End Sub
For the About button, just enter the text " Text Editor Ver 1.0" in the drop-
down menu item, as shown in Figure 26.3
Figure 26.3
Now, run the program and enter some text, as shown in Figure 26.4
Figure 26.4
Next, click on File to bring up the drop-down menu, as shown in Figure
26.5.
Figure 26.5
When you click on the Save button, the Save As dialog will appear, as
shown in Figure 26.6. Save the file as mytext.txt.
Figure 26.6
You can now click New to clear the text and type some other text and save
another file. You can also open a text file by clicking the open button, and
the Open dialog will appear, as shown in Figure 26.7
Figure 26.7
Let select mytext.txt and click the Open button, you will open this text file in
the text editor, as shown in Figure 26.8
Figure 26.8
If you want to show the opened file name appear as the caption of the form,
you enter the following line under the ReadFile() sub procedure,
Me.Text = OpenFileDialog1.FileName
Now, when you open a text file, its name will appear as the caption of the
text editor, as shown in Figure 26.9
Figure 26.9
26.2 Creating the Toolbar
In order to create the toolbar, you must insert the ToolStrip Control into the
form. It will stay below the form and remains invisible at runtime, as shown
in Figure 26.10
Figure 26.10
Now, click on the far-left corner of the form just below the menu bar, click
to bring up the first ToolStrip button with the default name
ToolStripButton1. You can rename it to ToolStripNew. Now click on the
image property to bring up the Select Source dialog and import an image as
icon, as shown in Figure 26.11
Figure 26.11
After opening an image folder and selected an image file, the image will
appear in the Select Source window, as shown in Figure 26.12
Figure 26.12
After clicking the OK button, the image will appear as an icon to replace
the default toolstrip button on the toolbar, as shown in Figure 26.13
Figure 26.13
In addition, you might want to add the Tooltip Text in the properties
window to the toolstrip button, so that the tip will appear when the mouse
hovers about this toolstrip button on the toolbar. You add the Tooltip text as
shown in Figure 26.14
Figure 26.14
When you run the application and place the mouse over the ‘New’ toolstrip
button, the tip "New File" will appear, as shown in Figure 26.15
Figure 26.15
Next, continue to add two more toolbar buttons (one for saving file and the
other one for opening file) on the toolbar until you obtain the design
interface, as shown in Figure 26.16.
Figure 26.16
Now, it is time to write code for the three toolstrip buttons on the toolbar.
For the ‘New’ toolbar button, enter the following code:
End Sub
For the "Save" toolbar button, enter the following Code:
Me.WriteFile()
End Sub
For the "Open" toolbar button, enter the following Code:
Me.ReadFile()
End Sub
Finally, you have added both the functional menu bar and toolbar. You can
add more menu items and toolstrip buttons and experiment with them.
Summary
● In Section 26.1, you have learned how to create a menu bar by adding
top-level menus as well as menu items. You have also learned how to
write code for the menu items.
● In section 26.2, you have built the toolbar by adding toolstrip buttons to
it. You have also learned how to write code for the toolstrip buttons.
Chapter 27 Deploying your VB 2022 Applications
Having developed a Visual Basic 2022 application, you might want to
publish and distribute it to the users.
Before deploying your application, you must test and debug your
application to ensure it is error-free.
Publishing your application is quite easy, it just requires a few clicks. First,
load your application in Visual Basic 2022. In this example, we wish to
publish the Draw Text application. In the Visual Basic 2022 IDE, choose
Build and then select Publish Draw text, as shown in Figure 27.1
Figure 27.1
After clicking Publish Draw Text, the Publish Wizard will ask you to
choose a location that you want to publish this application. You may publish
the application on your local drive or to a remote location via FTP, as
shown in Figure 27.2.
Figure 27.2
Click the Next button to continue. Now, the Publish Wizard will ask you
how users will install the application. There are three options, from a
website, from a UNC path or file share and from a CD-ROM or DVD-
ROM. In this example, we choose CD-ROM or DVD-ROM, as shown in
Figure 27.3
Figure 27.3
You may click the Next button to continue with the Publish Wizard or the
Finish button to complete the publishing process. If you click the Next
button, the Publish Wizard will ask where will the application check for
updates. In our example, we choose that the application will not check for
updates, as shown in Figure 27.4
Figure 27.4
After clicking the Next button, the final screen of the Publish Wizard will
show you where the application will be published to, as shown in Figure
27.5
Figure 27.5
Upon clicking the Finish button, the installation files and folder will be
saved to the specified location. In our examples, the folder is Application
files and the files are Draw text.application and setup.exe. You may now
burn the folder and files into a CD-ROM, DVD-ROM or upload them to a
website for distribution to the users.
Summary
● In this chapter, you have learned how to create installation files to
deploy your Visual Basic 2022 Applications.
Index
Abs, 133, 139
Add() method, 44, 47, 54
ADO.NET, 217, 218, 225, 226
animation, 204
arguments, 170
Arrays, 75, 76
Asc, 93
ASCII, 93
background color, 26, 28, 34, 42, 58, 156
BMI Calculator, 83, 127
boggle, 95
Boolean data types, 66
Button, 40, 148, 153
ByRef , 130, 131, 132
ByVal , 69, 82, 83, 85, 86, 88, 91, 98, 105, 108, 110, 111, 112, 120, 121,
130, 131, 132, 150, 166, 170, 238, 240, 242
checkbox, 31, 148, 152
Checkbox, 148
chr, 95
Chr, 93, 95
Class, 38, 103, 164, 165, 166, 244, 246, 248, 249
class module, 170
combobox, 31, 53, 56, 57
ComboBox, 40, 53
conditional operators, 97, 98, 102, 107, 113
Console, 251, 253, 254, 255, 256, 257, 258
Constants, 68, 73
CreateGraphics , 172, 174, 176, 178, 180, 182, 184, 185, 187, 188, 190, 192,
194, 195, 197, 198, 200, 201, 202, 211
currency data types., 65
Dash , 185
DashDot , 185
DashDotDot , 185, 186
DashStyle, 185, 186
DashStyles, 185
Database, 216, 217, 218, 220, 221, 236, 237
digital dice, 206, 208, 209
Dim , 45, 47, 49, 55, 69, 70, 71, 72, 73, 76, 77, 78, 82, 83, 85, 86, 87, 88,
90, 91, 99, 100, 103, 105, 108, 110, 111, 112, 114, 115, 116, 117, 120,
121, 123, 125, 128, 129, 131, 138, 148, 150, 154, 156, 159, 161, 167, 172,
173, 174, 175, 176, 177, 178, 180, 182, 184, 185, 187, 188, 190, 192, 193,
194, 195, 196, 198, 200, 201, 202, 207, 211, 214, 227, 228, 231, 233, 235,
237, 238, 240, 242, 245, 246, 249, 253, 254, 256, 257, 260, 261
Do Loop , 118, 121, 122
Double precision data types, 65
DrawEllipse , 186, 187, 188, 200, 201, 211
DrawPie , 196, 197, 202
DrawString, 189, 190, 191, 192
Ellipse, 186, 200
Encapsulation, 163
Error handling, 158
event-driven programming language, 15, 36
Exp, 134, 139
FillEllipse , 197, 200
FillPie , 197, 202, 203
FillPolygon , 197, 201
FillRectangle , 197, 198
Fix, 135, 139
For...Next loop, 51, 114
For...Next Loop, 114
Format, 128, 130, 138, 140, 141, 142, 143, 144, 145, 146, 166
function, 23, 38, 40, 42, 45, 53, 55, 81, 87, 88, 89, 91, 92, 93, 99, 125, 127,
130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 142, 147, 179, 181,
182, 204, 206, 241
Future Value Calculator, 128
Graphics, 172, 173, 174, 175, 176, 177, 178, 179, 180, 182, 183, 184, 185,
187, 188, 189, 190, 191, 192, 194, 195, 196, 197, 198, 200, 201, 202, 203,
210, 211
If...End If , 51
If...Then...ElseIf, 105
If…Then…Else, 97
Inheritance, 163
Inputbox, 49
Int, 71, 95, 103, 125, 136, 137, 139, 170, 207, 210, 211, 213, 214
label, 31, 42, 48, 52, 57, 90, 108, 151, 153, 155, 158, 159, 204, 213, 239,
242
Label, 40, 41, 42, 123
Lcase, 92, 93
Left Function, 89
Len Function, 87
listbox, 31, 45, 46, 47, 49, 50, 51, 52, 57
ListBox, 40, 43, 44
Literals, 67
Log, 136, 139
Logical Operators, 97
Looping, 114
Ltrim Function, 92
Mathematical Operators, 81
Menu Bar, 259
Menu Items, 259
message box, 38, 40, 41, 42, 70, 77, 78, 106, 124, 167
Mid Function, 89
module, 170
MsgBox, 23, 38, 39, 40, 70, 72, 73, 77, 78, 85, 86, 87, 88, 100, 106, 125,
131, 263
Non-numeric data types, 66
Numeric Data Types, 65
object-oriented programming, 15, 38, 44, 163, 172, 244
OFGSelectImage , 61, 62
On Error GoTo, 158, 159
OpenFileDialog , 61, 64, 245, 246, 261
Password Cracker, 124
Pen Object, 173, 185
picture box,, 31, 59, 63, 172
Polygon, 193, 201
Polymorphism, 163
Public , 38, 72, 73, 76, 100, 103, 127, 164, 166, 238, 240, 242, 244, 246,
249
PV, 170
quadrilateral, 195
radio button, 31, 148, 153, 157
rectangle, 172, 183, 184, 185, 186, 187, 188, 196, 197, 198, 199, 203
Remove method, 48, 57
RGB color code, 27
Right Function, 88
Rnd , 71, 95, 99, 103, 125, 137, 139, 206, 207, 210, 211, 213, 214
Rnd function, 95
Round, 138, 139, 239, 240, 242
Rtrim Function, 92
SaveFileDialog, 248, 249, 261
Select Case , 108, 109, 110, 111, 112, 113, 210, 211, 214
showRecords, 227, 229, 230, 231, 232, 233, 234, 235
SizeMode , 58
slot machine, 213, 215
SQL, 216, 217, 218, 219, 220, 224, 225, 237, 238, 244
Static , 72
StreamReader , 244, 245, 246, 248, 255, 256, 261
StreamWriter, 244, 248, 249, 254, 255, 260
StretchImage , 58
String, 40, 43, 48, 53, 56, 67, 69, 70, 76, 77, 78, 79, 85, 87, 88, 90, 91, 103,
105, 108, 154, 156, 164, 192, 227, 228, 233, 236, 237, 238, 240, 242, 251,
253, 254, 256, 257
String Collection Editor, 43, 48, 53, 56
sub procedure, 123, 126, 127, 210, 227, 230, 261, 267
SweepAngle , 196, 202
textbox, 31, 108, 245, 248
TextBox, 40, 41
timer, 32, 124, 145, 204, 205, 207, 209, 210, 213
Toolbox, 22, 31, 32, 33
ToolStrip, 267, 268
Triangle, 194
Trim Function, 91
Try…Catch ...End Try, 160
Ucase, 92, 93
User-Defined Functions, 127
Variables, 68, 69, 71
VB.NET, 15
VB6, 15, 158
Visual Basic 2022, 1, 2, 3, 15, 18, 19, 21, 22, 23, 24, 25, 26, 29, 32, 36, 38,
44, 65, 68, 69, 81, 85, 87, 88, 90, 92, 97, 98, 105, 108, 114, 118, 121, 125,
127, 133, 137, 143, 158, 160, 163, 164, 165, 172, 181, 183, 186, 190, 191,
198, 204, 217, 218, 224, 226, 237, 244, 251, 255, 273, 277
Visual Basic 6, 3, 15, 158, 172
Visual Studio 2019, 15, 17, 18, 19
Visual Studio 2022, 17, 18, 19
While...End While Loop, 121, 122