Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (4 votes)
2K views

Visual Basic 2022 Made Easy A Comprehensive Guide To Visual Basic 2022 Programming

Programming Made Easy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (4 votes)
2K views

Visual Basic 2022 Made Easy A Comprehensive Guide To Visual Basic 2022 Programming

Programming Made Easy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 384

 

 
 
 
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 2 Designing the User Interface


2.1 Customizing the Form
Example 2.1 Changing Properties at Runtime
Example 2.2 Customizing the Form
2.2 Adding Controls to the Form

Chapter 3 Writing the Code


3.1 The Concept of Event-Driven Programming
3.2 Writing the Code
Example 3.1 Displaying a Message
Example 3.3 Arithmetic Calculations

Chapter 4 Working with Controls


4.1 TextBox
Example 4.1 Adding two numbers
4.2 Label
Example 4.2 Display the output on a Label
4.3 ListBox
4.3.1 Adding Items to ListBox
Example 4.3 Adding an Item to ListBox
Example 4.4 Adding Items using InputBox
Example 4.5 Geometric Progression
4.3.2 Removing Items from a List Box
Example 4.6 Removing Items from ListBox
Example 4.6 Removing an Item from ListBox via an Input Box
Example 4.7 Delete a Selected Item from ListBox
Example 4.8 Delete Multiple Selected Items from ListBox
Example 4.9 Clear All Items from ListBox
4.4 ComboBox
4.4.1 Adding Items to ComboBox
Example 4.10 Adding an Item to ComboBox
Example 4.11 Adding an Item to ComboBox via an Input Box
4.4.2 Removing Items from a Combo box
Example 4.12 Delete an Item from ComboBox
Example 4.13 Delete a Selected Item from ComboBox
Example 4.14 Remove All Items from ComboBox

Chapter 5 Handling Images


5.1 Loading an Image in a Picture Box
5.1.1 Loading an Image at Design Time
5.1.2 Loading an Image at Runtime
Example 5.1 Loading an Image at Runtime
5.2 Loading an Image using Open File Dialog Control
Example 5.2 Loading an Image via a Dialog Box

Chapter 6 Working with Data


6.1 Visual Basic 2022 Data Types
6.1.1 Numeric Data Types
6.1.2 Non-numeric Data Types
6.1.3 Suffixes for Literals
6.2 Variables and Constants
6.2.1 Variable Names
6.2.2 Declaring Variables
Example 6.1 Declaring Variables
Example 6.2 Declaring a String Variable
Example 6.3 Declaring a Fixed Length String Variable
6.2.3 Assigning Values to Variables
Example 6.4 Assigning Values to Variables
Example 6.5 Error Assigning a Variable
6.2.4 Scope of Declaration
6.2.5 Declaring Constants
Example 6.6 Declaring Constants
Example 6.6 Computing the Area of a Circle

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 8 Mathematical Operations


8.1 Mathematical Operators
8.2 Writing Code that Performs Mathematical Operations
Example 8.1 Standard Arithmetic Calculations
Example 8.1 Performing Arithmetic Operations
Example 8.2 Pythagorean Theorem
Example 8.3: BMI Calculator

Chapter 9 String Manipulation


9.1 String Manipulation Using + and & signs
Example 9.1 Concatenation of Strings
Example 9.2 Data Mismatch
9.2 String Manipulation Using Built-in Functions
9.2.1 The Len Function
Example 9.3  Using the Len Function to find the Lenth of a Phrase
9.2.2 The Right Function
Example 9.4 Extracting the Right Portion of a Phrase
9.2.3 The Left Function
9.2.4 The Mid Function
Example 9.5 Using the Mid Function to Extract a Part of a Phrase
Example 9.6 Extracting a Part of a Phrase
9.2.5 Trim Function
Example 9.7 Trimming a Phrase
9.2.6 Ltrim Function
9.2.7 The Rtrim Function
9.2.8 The InStr function
9.2.9 The Ucase and the Lcase Functions
9.2.10 The Chr and the Asc functions
Example 9.8 Boggle

Chapter 10 Using If…Then…Else


10.1 Conditional Operators
10.2 Logical Operators
10.3 Using If ...Then...Else
10.3.1 If ...Then Statement
Example 10.1 Using If…Then Statement
10.3.2 If...Then…Else Statement
Example 10.2 Lucky Draw Simulation
Example 10.3 Another Lucky Draw Program
10.3.3 If...Then...ElseIf Statement
Example 10.4 Grade Generator

Chapter 11 Select Case


Example 11.1: Examination Grades
Example 11.2 Using Case Is
Example 11.3 Select Case for a Range of Values
Example 11.4 Computing Exam Grades

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 13 Sub Procedures


Example 13.1 A Sub Procedure that Add Two Numbers
Example 13.2: Password Cracker

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

Chapter 15 Mathematical Functions


15.1 The Abs Function
Example 15.1 Computing Absolute Value
15.2 The Exp function
Example 15.2 Compute Exponential Value
15.3 The Fix Function
Example 15.3 Using Fix
15.4 The Int Function
15.5 The Log Function
Example 15.4 The Log Function
15.6 The Rnd( ) Function
Example 15.5 Generating Random Integers
15.7 The Round Function
Example 15.6 Rounding Numbers

Chapter 16 The Format Function


16.1 Format Function for Numbers
16.1.1 Built-in Format function for Numbers
Example 16.1 Formatting Numbers
16.1.2 User-Defined Format
Example 16.2 Using User-Defined Formats
16.2 Formatting Date and Time
16.2.1 Formatting Date and time using predefined formats
Example 16.3 Formatting Date and Time
16.2.2  Formatting Date and time using user-defined formats
Example 16.4 Formatting Date and Time with User-Defined Format

Chapter 17 Checkbox and Radio Button


17.1 Checkbox
Example 17.1: Online Shopping Mall
Example 17.2 Shopping Cart
Example 17.3 Formatting Fonts
17.2 Radio Button
Example 17.4 Shopping Cart with Radio Buttons
Example 17.5 Multiple Selections Using Groupbox

Chapter 18 Errors Handling


18.1 Using On Error GoTo Syntax
Example 18.1 Division Errors
18.2 Using Try…Catch ...End Try Structure
Example 18.1 Data Types Mismatch Errors

Chapter 19 Object-Oriented Programming


19.1 Concepts of Object-Oriented Programming
(a) Encapsulation
(b) Inheritance
(c) Polymorphism
19.2 Creating a Class
Example 19.1 BMI Class
Example 19.2 Examination Class
Example 19.3 Future Value Class

Chapter 20 Creating Graphics


20.1 Introduction to Graphics Creation
20.2 Creating the Graphics Object
20.3 Creating the Pen Object
20.4 Drawing a Straight Line
20.5 Drawing Lines that Connect Multiple Points
Example 20.1 Drawing straight lines that connect multiple points
20.6 Drawing a curve that Connect Multiple Points
Example 20.2 Drawing a Curve
20.7 Drawing a Quadratic Curve
Example 20.3 Drawing the Quadratic
20.8 Drawing a Sine Curve
Example 20.4 Drawing a Sine Curve
20.8 Drawing a Rectangle
20.9 Customizing Line Style of the Pen Object
Example 20.5 Drawing a Rectangle with Dash Line Border
20.10 Drawing an Ellipse
Example 20.6 Drawing an Ellipse
Example 20.7 Drawing Ellipse with DrawEllipse Method
20.11 Drawing a Circle
Example 20.8 Drawing a Circle
20.12 Drawing Text
Example 20.10 Drawing Text
Example 20.11 Drawing Text
20.13 Drawing Polygons
Example 20.12 Drawing a Triangle
Example 20.13 Drawing a Quadrilateral
20.14 Drawing a Pie
Example 20.14 Drawing a pie that sweeps clockwise through 60
degrees.
20.15 Filling Shapes with Color
20.15.1 Drawing and Filling a Rectangle with Color
Example 20.15 Drawing a Square
20.15.2 Drawing and Filling an Ellipse with Color
Example 20.16 Drawing an Ellipse and Color it
20.15.3 Drawing and Filling a Polygon with Color
Example 20.17 Drawing a Polygon and Color It
20.15.4 Drawing and Filling a Pie
Example 20.18 Drawing a Pie and Color It

Chapter 21 Using Timer


Example 21.1 Creating a Digital Clock
Example 21.2 Creating a Stopwatch
Example 21.3 Creating a Digital Dice

Chapter 22 Creating Animation


Example 22.1 Creating a Moving Object
Example 22.2 Creating a Graphical Dice
Example 22.3 Creating a Slot Machine

Chapter 23 Working with Databases


23.1 Introduction to Database
23.2 Creating a Database Application
23.3 Creating a Connection to a Database using ADO.NET
23.4 Populating Data in ADO.NET
Example 23.1 Creating a Customer Contact List
23.5 Browsing Records
23.6  Editing, Saving, Adding and Deleting Records
Example 23.2 Browsing the Database
23.7 Accessing Database using DataGridView
Example 23.3 Browsing Data Using DataGridView
23.8 Performing Arithmetic Calculations in a Database
Example 23.4 Performing Arithmetic Calculations in a Database
Example 23.5 Calculating Income
Example 23.6 Using the Count Function

Chapter 24 Reading and Writing Text Files


24.2 Reading a Text File
24.3 Writing to a Text File

Chapter 25 Building Console Applications


25.1 Introduction
Example 25.1: Displaying a Message
25.2 Creating a Text File Writer in Console
Example 25.2 Creating a Text File Writer
25.3 Creating a Text File Reader in Console
Example 25.3 Creating a Text File Reader
25.4 Creating a Console App using If...Then...Else
Example 25.4 Arithmetic Console App

Chapter 26 Creating Menu Bar and Toolbar


26.1 Creating Menu Items on the Menu Bar
26.2 Creating the Toolbar

Chapter 27 Deploying your VB 2022 Applications


Index
Chapter 1 Introduction
1.1 A Brief History of Visual Basic
Visual Basic is a third-generation event-driven programming language first
released by Microsoft in 1991.  The final version of the classic Visual Basic
was Visual Basic 6. VB6 is a user-friendly programming language designed
for beginners. It allows anyone to develop GUI Windows desktop
applications effortlessly. Interestingly, many developers still favor VB6
over its successor VB.NET.
 
In 2002, Microsoft released Visual Basic.NET (VB.NET), replacing Visual
Basic 6.  Thereafter, Microsoft declared VB6 a legacy programming
language in 2008.  However, Microsoft still provides some form of support
for VB6. Unlike VB6, VB.NET is a fully object-oriented programming
language implemented on the .NET Framework. It was created to cater for
the development of the web as well as mobile applications. Subsequently,
Microsoft has released many versions of VB.NET: Visual Basic 2005,
Visual Basic 2008, Visual Basic 2010, Visual Basic 2012, Visual Basic
2013,  Visual Basic 2015, Visual Basic 2017, Visual Basic 2019 and Visual
Basic 2022.  Although the .NET portion was discarded in 2005, all versions
of the Visual Basic programming language released since 2002 are regarded
as the VB.NET programming language.
 
Microsoft released Visual Studio 2022 in early 2022. VS 2022 allows you
to code in different programming languages and different platforms, among
them is Visual Basic 2022. The other Programming languages are C# C++,
F#, JavaScript, Java and Python.
1.2 Installation of Visual Studio 2022
You may download the free version of Visual Studio 2022 from the
following link:
https://visualstudio.microsoft.com/vs/

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
 

Figure 1.5 Visual Studio 2022 Start Page


 
The Visual Studio 2022 start page offers a much simpler UI than VS2019, it
comprises four options: clone a repository, open a project or solution, open
a local folder or create a new project.
 
Let us create a new project by clicking the Create a new project option. You
will see the Create a new project template page, as shown in Figure 1.6.
There are a dozen templates to choose from, but since the book is about
Visual Basic 2022 programming, scroll down to select WPF application, as
shown in Figure1.6.

Figure 1.6 Create a new project template


 
Next, select the Windows Forms App (.Net Framework) template as we
want to develop a Windows desktop project. After selecting the template
and clicking the Next button, the project configuration page appears, as
shown in Figure 1.7. You can configure your project by typing the project
name and selecting a few other options.
Figure 1.7 Configuring Project
 
At the bottom of this dialog box, you can change the default project name
WindowsApplication1 to some other name you like, for example, My First
Visual Basic 2022 Application. After renaming the project, click OK to
continue. The Visual Basic 2022 IDE Windows will appear, as shown in
Figure 1.8. Visual Basic 2022 IDE comprises a few windows, the Form
window, the Solution Explorer window, and the Properties window. It also
consists of a toolbox which contains many useful controls that allows the
programmer to develop his or her Visual Basic 2022 programs.
 
Figure 1.8 The Visual Basic 2022 IDE

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

Figure 1.12 The Runtime Interface


Figure 1.13 The Message Box
 
 
 

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

Figure 2.4 Runtime UI


You can also change the properties of the form at runtime by writing
relevant codes. The default form is an object, and an instant of the form can
be denoted by the name  Me . The property of the object can be defined by
specifying the object’s name followed by a period, as follows:

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.FromArgb(0, 255, 0)

Example 2.1 Changing Properties at Runtime

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles_


MyBase.Load

Me.Text = "My First Visual Basic 2022 Application"

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:

Me.BackColor = Color.FromA rgb(64,224,208)

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

Private Sub Form1_Load(sender As Object, e As EventArgs Handles


MyBase.Load

Me.Text = "My First VB2022 App"

Me.BackColor =Color.Beige

Me.MaximizeBox = False

Me.MinimizeBox = True

Me.Size = New Size(400, 400)

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.

Figure 2.6: Toolbox


You can position the Toolbox by dragging it anywhere you like while its
status is set to float. You can also dock the toolbox by right-clicking on the
toolbox and choose dock from the pop-up menu. The docked Toolbox
appears side by side with the Solution Explorer, or as one of the tabbed
windows together with the Form Design window and the code window, as
shown in Figure 2.7.

Figure 2.7 Toolbox


You can also dock the toolbox at the bottom, below the default form, as
shown in Figure 2.8. Further, you may also pin the toolbox to the side bar or
the bottom bar by clicking on the pin icon on the menu bar of the toolbox.
How and where you want to position your toolbox is entirely up to you, but
we strongly suggest that you place the toolbox alongside or at the bottom of
the default form for ease of use. You should never cover the form with the
toolbox because it will be difficult to add controls to the form.
 
Figure 2.8

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

Figure 3.2: Events associated with the button


3.2 Writing the Code
To write code, click any part of the form to enter the code window, as
shown in Figure 3.1. The event procedure is to load Form1 which starts
with  the keywords Private Sub   and ends with  End Sub . This procedure
includes the Form1 class and the event Load, and they are bound together
with an underscore, i.e., Form_Load . It does nothing other than loading an
empty form. To make the load event does something, insert the following
statement.

MsgBox ( "Welcome to Visual Basic 2022")

Example 3.1 Displaying a Message

Public Class Form1

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles_


MyBase.Load

MsgBox ( "My First Visual Basic 2022 APP", ,"My Message")

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

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles


MyBase.Load

MsgBox("2" & "+" & "5" & "=" & 2 + 5)

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

or pictures. String in a TextBox can be converted to numeric data by using

the function Val(text) . The following example illustrates a simple program

that processes the input from the user.

Example 4.1 Adding two numbers

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.

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles


Button1.Click

    MsgBox("The sum is" & Val(TextBox1.Text) + Val(TextBox2.Text))

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

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles


Button1.Click

  LblSum.Text = Val(TextBox1.Text) + Val(TextBox2.Text)

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

a) Adding items using the String Collection Editor

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

access the properties window. In the properties window, click on collection

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,

as shown in Figure 4.5


Figure 4.4

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")

Example 4.3 Adding an Item to ListBox

In this example, running the program will add the item “Vivo” to the end of
the list, as shown in Figure 4.6

Private Sub BtnAdd_Click(sender As Object, e As EventArgs) Handles


BtnAdd.Click
       MyListBox.Items.Add("Vivo")
End Sub
Figure 4.6
Example 4.4 Adding Items using InputBox

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:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles


Button1.Click

Dim myitem                        'declare the variable myitem

myitem = InputBox("Enter your Item")

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

This is a program that generates a geometric progression and displays the


results in a list box. Geometric progression is a sequence of numbers where
each subsequent number is found by multiplying the previous number with a
fixed number. This fixed number is called the common ratio. The common
ratio can be a negative number, an integer, a fraction, and any number but it
must not be a zero or 1.

n-1
The formula to find the nth term of the geometric progression is     ar ,

where a is the first number and r is the common ratio.

In this program, we employ the Do...Loop Until statement to generate the


numbers in a geometric progression. To design the UI, we insert three text
boxes for the user to enter the first number, the common ratio and the
number of terms. We also insert a list box to display the generated numbers.
Besides that, a command button is needed for the user to click and generate
the geometric progression. In addition, we also add a button for clearing the
list of generated numbers.
To add the numbers to the list box, we use the Add() method. The syntax is  
ListBox1.Items.Add(x) , where x can be any variable.
The code

Private Sub BtnComp_Click(sender As Object, e As EventArgs) Handles


BtnComp.Click

       Dim x, n, num As Double

        Dim r As Double

       x = TxtFirst.Text

        r = TxtCR.Text

        num = TxtN.Text

        MyList.Items.Add("n" & vbTab & "x")

        MyList.Items.Add("___________")

       n = 1

        Do

           x = x * r

            MyList.Items.Add(n & vbTab & x)

            n = n + 1

        Loop Until n = num + 1

End Sub

Private Sub BtnClr_Click(sender As Object, e As EventArgs) Handles


BtnClr.Click

        MyList.Items.Clear()
End Sub
 
The output is as shown in Figure 4.9
 

Figure 4.9 The runtime interface


 
4.3.2 Removing Items from a List Box

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.

Example 4.6 Removing Items from ListBox

In this example, add a  button and label it “Remove Items”. Click on this
button and enter the following code

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles


Button2.Click
MyListBox.Items.Remove("iPhone")
End Sub
 
The item “iPhone” will be removed after running the program, as shown in
Figure 4.10
Figure 4.10

Example 4.6 Removing an Item from ListBox via an Input Box

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:

Private Sub BtnDelete_Click(sender As Object, e As EventArgs)


Handles BtnDelete.Click
        Dim myitem

       myitem = InputBox("Enter your Item for Deletion")

        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)

Example 4.7 Delete a Selected Item from ListBox

Private Sub BtnDelSel_Click(sender As Object, e As EventArgs)


Handles BtnDelSel.Click
        MyListBox.Items.Remove(MyListBox.SelectedItem)
End Sub
 
When the user run the program and select an item to delete, the item will be
deleted, as shown in Figure 4.12 and Figure 4.13.
Figure 4.12

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:

Private Sub BtnDelSelected_Click(sender As Object, e As EventArgs)


Handles BtnDelSelected.Click
       If MyListBox.SelectedItems.Count > 0 Then

           For n As Integer = MyListBox.SelectedItems.Count - 1 To 0 Step


-1

                'remove the current selected item from items

                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”

Private Sub BtnClr_Click(sender As Object, e As EventArgs) Handles


BtnClr.Click

        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

Collection Editor as shown in Figure 4.15. Besides that, if you want to

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

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles


Button1.Click
MyComboBox.Items.Add("Vivo")
End Sub
 
The output is as shown in Figure 4.17

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

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles


Button1.Click
Dim myitem

myitem = InputBox("Enter your Item")

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

the Delete key.

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

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles


Button2.Click
MyComboBox.Items.Remove("iPhone")
End Sub
The item “iPhone” will be removed after running the program. You can also
let the user select a certain item to delete, as in Example 4.13.
Example 4.13 Delete a Selected Item from ComboBox

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles


Button1.Click
MyComboBox.Items.Remove(MyComboBox.SelectedItem)
End Sub

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

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles


Button2.Click
MyComboBox.Items.Clear()
End Sub
 
Summary
●     In section 4.1, you have learned how to work with a text box.
●     In section 4.2, you have learned how to work with a label
●     In section 4.3.1, you have learned how to add items to a list box
●     In section 4.3.2, you have learned how to remove items from a list box.
●     In section 4.4.1, you have learned how to add items to a combo box
●         In section 4.4.2, you have learned how to remove items from a combo
box
Chapter 5 Handling Images
 
In this chapter, we shall learn how to load an image into the picture box at
design time and at runtime. In addition, we shall also learn how to use a
common dialog control to browse for image files in your local drives and
then select and load an image into the picture box.
5.1 Loading an Image in a Picture Box
5.1.1 Loading an Image at Design Time
Let us create an image viewer. To design the UI, insert a picture box in the
form. Next, change its border property to FixedSingle and its background
color to white. Besides that, change the SizeMode property of the image to
StretchImage so that the image can fit in the picture box.
Now, right click on the picture box to bring out its properties window. In the
properties window, scroll to the Image property, as shown in Figure 5.1. In
the properties window, click on the grey button on the right of the Image
item to bring out the “Select Source” dialog box, as shown in Figure 5.2
 

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

To load an image at runtime, use the code as in Example 5.1.


Example 5.1 Loading an Image at Runtime

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles


MyBase.Load
MyPicBox.Image = Image.FromFile("C:\Users\Documents\My
Websites\vbtutor\images\vb6_cover.jpg")
End Sub
* You must search for an image in your local drive and determine its path.
Running the program will display the same image in the picture box as in
Figure 5.4
5.2 Loading an Image using Open File Dialog
Control
We have learned how to load an image in a picture box at the design phase
using the properties window. Next, we shall learn how to load an image
using the OpenFileDialog controls.
First, we must add the OpenFileDialog control on the form. This control
will be invisible during runtime, but it facilitates the process of launching a
dialog box and letting the user browse his or her local drives, then select
and open a file. For the OpenFileDialog to display all types of image files,
we must specify the types of image files under the Filter property. Before
that, rename OpenFileDialog as OFGSelectImage . Next, right click on
the OpenFileDialog control to access its properties window. Beside the
Filter property, specify the image files using the format:

JPEG Files| *.JPG|GIF Files|*.GIF|WIndows Bitmaps|*.BMP


 
as shown in Figure 5.5. These are the common image file formats. Besides
that, you also must delete the default Filename.
Figure 5.5
Next, double-click on the View button and enter the code as in Example 5.2
Example 5.2 Loading an Image via a Dialog Box

Private Sub BtnLoadImg_Click(sender As Object, e As EventArgs)


Handles Button1.Click
If OFGSelectImage.ShowDialog = Windows.Forms.DialogResult.OK
Then

  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

1.401298E-45 to 3.402823E+38 for


positive values.
 Double    8 bytes -1.79769313486232e+308 to
-4.94065645841247E-324 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).

6.1.2 Non-numeric Data Types

Non-numeric data types are data that cannot be manipulated


mathematically. Non-numeric data comprises text or string data types, Date
data types, Boolean data types Object data type and Variant data type. They
are summarized in Table 6.2.
 
Table 2 Non-numeric Data Types
TYPE STORAGE RANGE
Length of 1 to 65,400 characters
String(fixed
string
length)

Length + 10 0 to 2 billion characters


String(variable
bytes
length)

Date  8 bytes January 1, 100 to December 31,


9999
Boolean  2 bytes True or False
Object  4 bytes Any embedded object
Variant(numeric)  16 bytes Any value as large as Double
Variant(text) Length+22 Same as variable-length string
bytes
 
6.1.3 Suffixes for Literals

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.

Data can be stored as a variable or as a constant.  Variables are like

mailboxes in the post office. The content of the variables changes every

now and then, just like the mailboxes.

6.2.1 Variable Names

Like the mailboxes, each variable must be given a name. To name a


variable in Visual Basic 2022, you must follow a set of rules. The following
are eules when naming the variables in Visual Basic:
●     It must be less than 255 characters.
●     No spacing is allowed.
●     It must not begin with a number.
●     Period is not permitted.
Examples of valid and invalid variable names are displayed in Table 6.4
Table 6.4 Variable Name
Valid Names Invalid Names

My_Computer My.Computer
 Smartphone123 123Smartphone
 Long_Name_Can_beUSE  LongName&Canbe&Use    
  *& is not acceptable
 

6.2.2 Declaring Variables


In Visual Basic 2022, we must declare the variables before using them by

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

windows using the Dim statement. The syntax is as follows:

Dim VariableName As DataType

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:

Dim VariableName1 As DataType1, VariableName2 As DataType2,


VariableName3 As DataType3
 

Example 6.1 Declaring Variables

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles MyBase.Load

Dim password As String

Dim yourName As String

Dim firstnum As Integer

Dim secondnum As Integer

Dim total As Integer

Dim doDate As Date

End Sub

You may also combine the above statements in one line, separating each
variable with a comma, as follows:

Dim password As String, yourName As String, firstnum As

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

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles

Button1.Click

Dim YourMessage As String

YourMessage = "Happy Birthday!"

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:

Dim VariableName As String * n

Where n defines the number of characters the string can hold.


Example 6.3 Declaring a Fixed Length String Variable

Dim yourName As String * 10

yourName can hold no more than 10 Characters.

6.2.3 Assigning Values to Variables

After declaring various variables, we can assign values to those variables.


The syntax of an assignment is:
Variable=Expression
The variable can be a declared variable or a control property value. The
expression could be a mathematical expression, a number, a string, a
Boolean value and more, as illustrated in Example 6.4
Example 6.4 Assigning Values to Variables

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)

total = firstNumber + secondNumber+ThirdNumber

MeanScore% = SumScores% / NumSubjects%

X=sqr (16)

TrimString= Ltrim ("Visual Basic", 4)

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

Dim YourMessage As Integer

YourMessage = "Happy Birthday!"

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:

Private VariableName As Datatype

Static VariableName As Datatype

Public VariableName As Datatype

 
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.

 6.2.5 Declaring Constants

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

is as shown in Example 6.6.

Example 6.6 Declaring Constants


Const ConstantName As Single=3.142
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles
Button1.Click

Const Pi As Single = 3.142

Dim R As Single = 10

Dim AreaCircle As Single

AreaCircle = Pi * R ^ 2

MsgBox("Area of circle with " & "radius" & R & "=" & AreaCircle)

End Sub

Example 6.6 Computing the Area of a Circle

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles


Button1.Click

Const Pi As Single = 3.142

Dim R As Single = 10

Dim AreaCircle As Single

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.

For example, if we wish to enter one hundred names, it is very tedious to


declare one hundred  different names. Instead of declaring one hundred
different variables, we only need to declare only one array. We differentiate
each item in the array by using a subscript, the index value of each item, for
example name(1), name(2),name(3) …….etc. which will make declaring
variables streamline and much more systematic.
7.2 Dimension of an Array
An array can be one dimensional or multidimensional. One dimensional
array is a list of items that consists of one row of items or one column of
items. A two-dimensional array is a table of items that are made up of rows
and columns. The way to reference an element in a one-dimensional array is
ArrayName(x), where x is the index or position number of the element.

The way to reference an element in a  two-dimensional array is


ArrayName(x,y) , where (x, y) is the index or position number of
the  element. Usually, it is sufficient to use one dimensional and two-
dimensional arrays, you only must use higher dimensional arrays if you
must deal with more complex problems. Let me illustrate the arrays with
tables.
 
Table 7.1 One-Dimensional Array
Student
SName(0) SName(1) SName(2) SName(3) SName(4) SName(5)
Name

 
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:

Dim arrayName(n) As dataType

* n indicates the last index in the array.


Please note that n does not indicate the number of elements in the array, it is
one less than the number of elements (n-1) because the first element is
always the zeroth element. The first element is arrayName(0), the second
element is arrayName(1), the third element is arrayName(2) and so on. The
number of elements in an array is also known as length, we can retrieve the
length of an array using the syntax  arrayName.length  
For example, the following statement declares an array that consists of 11
elements starting from CusName(0) through to CusName(10)

Dim CusName(10) As String

To find out the length of the array, you can write the following code:
 

Example 7.1 To Find the Length of an Array

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles


MyBase.Load

Dim CusName(10)As String

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:

Dim arrayname As DataType()

arrayName = New String(){1,2,3,....,n)

This array will consist of n elements, starting with arrayName(1).


 

 Example 7.2 Find the length of Non-zeroth Array


 

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles

MyBase.Load

Dim CusName As String()

CusName = New String() {1, 2, 3}

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)

Dim ArrayName(m,n) As dataType

Example 7.3 Declaring Two-Dimensional Array


 

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles

MyBase.Load

Dim CusName(5,6) As String

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
 

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles

MyBase.Load

Dim num As Integer

Dim CusName(5) As String

For num = 0 To 5

CusName(num) = InputBox("Enter the customer name", "Enter Name")

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

Private Sub Button1_Click(ByVal sender As Object, ByVal e As


EventArgs) Handles Button1.Click

Dim num1, num2, difference, product, quotient As Single

num1 = TextBox1.Text

num2 = TextBox2.Text

sum=num1+num2

difference=num1-num2

product = num1 * num2

quotient=num1/num2

LblSum.Text=sum

LblDiff.Text=difference

LblPro.Text = product

LblQt.Text = quotient

End Sub

Example 8.2 Pythagorean Theorem

This program uses Pythagorean Theorem to calculate the length of


hypotenuse c given the length of the adjacent side and the opposite side b.
In case you have forgotten the formula for the Pythagorean Theorem, it is
written as

c^2=a^2+b^2

Private Sub Button1_Click(ByVal sender As Object, ByVal e As


EventArgs) Handles Button1.Click

Dim a, b, c As Single

a = TextBox1.Text

b = TextBox2.Text

c= (a^2+b^2)^(1/2)

Label3.Text=c

End Sub

Example 8.3: BMI Calculator

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:

Private Sub Button1_Click(ByVal sender As Object, ByVal e As


EventArgs) Handles Button1.Click

Dim height, weight, bmi As Single

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,

gender, cities, book titles, sentences, words, text, alphanumeric characters

and more. String manipulation is best demonstrated in word processing

which deals with text editing.

In Visual Basic 2022, a string is a single unit of data that is made up of a


series of characters that includes letters, digits, alphanumeric symbols etc. It
is treated as the String data type and is non-numeric in nature, which means
it cannot be manipulated mathematically though it might consist of
numbers.
9.1 String Manipulation Using + and & signs
Strings can be manipulated using the & sign and the + sign, both perform
the string concatenation which means combining two or more smaller
strings into a larger string. For example, we can join "Visual" ,"Basic" and
"2022" into "Visual Basic 2022" using "Visual" & "Basic" or "Visual
"+"Basic", as shown in the Examples below:
Example 9.1 Concatenation of Strings

Private Sub BtnShow_Click(ByVal sender As Object, ByVal e As

EventArgs) Handles BtnShow.Click

Dim text1, text2, text3, text4 As String

text1 = "Visual"

text2 = "Basic"

text3 = "2022"

text4 = text1 + " "+text2 + " "+text3

MsgBox(text4)

End Sub

The line text4=text1+ text2 + text3 can be replaced by text4=text1 &


text2 &text3 and produces the same output. However, if one of the
variables is declared as a numeric data type, you cannot use the + sign, you
can only use the & sign.
The output is shown in Figure 9.1

Figure 9.1
 
Example 9.2 Data Mismatch

Private Sub BtnShow_Click(ByVal sender As Object, ByVal e As


EventArgs) Handles BtnShow.Click

Dim text1, text3 As string

Dim Text2 As Integer

text1 = "Visual"

text2 = 22

text3 = text1 + text2

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.

Dim text1, text3 As string

Dim Text2 As Integer

text1 = "Visual"

text2 = 22

text3 = text1 & text2

MsgBox(text3)

The output is shown in Figure 9.3

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

Private Sub BtnShow_Click(ByVal sender As System.Object, ByVal e

As EventArgs) Handles BtnShow.Click

Dim MyText As String

MyText="Visual Basic 2022"

MsgBox(Len(MyText))

End Sub

The output is shown in Figure 9.4


Figure 9.4

9.2.2 The Right Function

The Right function extracts the right portion of a phrase. The syntax is

Microsoft.VisualBasic.Right("Phrase",n)

Example 9.4 Extracting the Right Portion of a Phrase

Private Sub BtnShow_Click(ByVal sender As Object, ByVal e As

EventArgs) Handles BtnShow.Click

Dim MyText As String

MyText = "Visual Basic"

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,

Microsoft.VisualBasic.Left ("Visual Basic" , 4) = Visu

9.2.4 The Mid Function

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

Dim myPhrase As String

myPhrase = InputBox("Enter your phrase")

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 .

Example 9.6 Extracting a Part of a Phrase

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:

Private Sub BtnExtract_Click(sender As Object, e As EventArgs)

Handles BtnExtract.Click

       Dim myPhrase As String

       Dim pos, n As Integer

        myPhrase = TxtPhrase.Text

        pos = TxtPos.Text

        n = TxtNumber.Text

        LblExtract.Text = Mid(myPhrase, pos, n)

End Sub

The runtime interface is as follows:


Figure 9.6
 
9.2.5 Trim Function

The Trim function trims the empty spaces on both sides of the phrase. The
syntax is

Trim("Phrase")

For example, Trim (" Visual Basic ") = Visual Basic


Example 9.7 Trimming a Phrase

Private Sub Button1_Click(ByVal sender As Object, ByVal e As

EventArgs) Handles Button1.Click

Dim myPhrase As String

myPhrase = InputBox("Enter your 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,

Rtrim("Visual Basic 2022") = Visual Basic 2022

9.2.8 The InStr function

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

Instr(n, original phase, embedded phrase)


Where n is the position where the Instr function will begin to look for the
embedded phrase. For example

Instr(1, "Visual Basic 2022 ","Basic")=8


 

9.2.9 The Ucase and the Lcase Functions

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,

Microsoft.VisualBasic.Ucase("Visual Basic") = VISUAL BASIC

Microsoft.VisualBasic.Lcase("Visual Basic") = visual basic

9.2.10 The Chr and the Asc functions

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:

Chr(65)=A, Chr(122)=z, Chr(37)=% , Asc("B")=66, Asc("&")=38


 
Table 9.1 displays the ASCII Code
 
Table 9.1 ASCII Code
ASCII Chr ASCII Chr ASCII Chr
8 Backspace 61 = 98 b
13 Enter key 62 > 99 c
32 Space 63 ? 100 d
33 ! 64 @ 101 e
34 " 65 A 102 f
35 # 66 B 103 g
36 $ 67 C 104 h
37 % 68 D 105 i
38 & 69 E 106 j
39 ' 70 F 107 k
40 ( 71 G 108 l
41 ) 72 H 109 m
42 * 73 I 110 n
43 + 74 J 111 o
44 , 75 K 112 p
45 - 76 L 113 q
46 . 77 M 114 r
47 / 78 N 115 s
48 0 79 O 116 t
49 1 80 P 117 u
50 2 81 Q 118 v
51 3 82 R 119 w
52 4 83 S 120 x
53 5 84 T 121 y
54 6 85 U 122 z
55 7 86 V 123 {
56 8 87 W 124 |
57 9 88 X 125 }
58 : 89 Y 126 ~
59 ; 90 Z 127 DEL
60 < 97 a    
 
 
Example 9.8 Boggle
 
Boggle is a type of words puzzle game where the players can form as many
words as possible from the characters displayed on a nxn square. Words can
be formed in many ways, from left to right, from right to left, top to bottom,
bottom to top, diagonal, zigzag manner and more.
In this example, we have designed a 5x5 boggle. To design the Interface,
insert twenty labels on the Form1. This is only a boggle board generator, so
the players must write the words on a piece of paper.
Each time we press the shake button, a different set of characters will
appear. To achieve this, we use the chr() function and the Rnd function to
randomly generate the characters. Besides that, we must declare an array for
the Label as Vb2013 will not create the array automatically for the label,
unlike VB6.
Alphabet A to Z correspond to Chr(65) to chr(90), therefore we must
generate random numbers between 65 to 90. The formula to generate
random numbers between two numbers is:
m = Int((MaxValue - MinValue + 1) * Rnd) + MinValue
Therefore, the formula to generate random numbers between 65 and 90 is
RndNum=Int(26)+65 , which means we can generate random alphabet
using chr(m) in a For Next Loop.
The Code
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles
Button1.Click
        Dim i, n As Integer
        For i = 1 To 25
        n = Int(26 * Rnd()) + 65
'Declare an array for the Labels
Dim FoundControls As Control() = Me.Controls.Find("Label" & i, True)
'Find the label with the name "Label#" - where # is the current index
            If FoundControls.Count > 0 Then
                FoundControls(0).Text = Chr(n) 'Change its text
            End If
        Next
End Sub
 
The Output
Figure 9.7
 
 
 
 
Summary
●         In section 9.1, you have learned how to manipulate string using the &
and + signs.
●     In section 9.2, you have learned how to manipulate string using various
built-in functions.
Chapter 10 Using If…Then…Else
The decision-making process is an important part of programming in Visual
Basic 2022 because it can solve problems in a smart way and provide useful
output or feedback to the user. For example, we can write a Visual Basic
2022 program that can instruct the computer to perform several tasks until
certain conditions are met, or a program that will reject non-numeric data.
In order to control the program flow and to make decisions, we must use the
conditional operators and the logical operators together with the
If...Then...Else control structure.
10.1 Conditional Operators
The conditional operators are powerful tools that resemble mathematical
operators. These operators allow a program to compare data values and then
decide what actions to take, whether to execute a program or terminate the
program and more. They are used to compare two values to check whether
they are equal, or one value is greater or less than the other value. The
comparison will return a true or a false result. These operators are shown in
Table 10.1.
Table 10.1 Conditional Operators
Operators Description
= Equal to
> Greater than
< Less than
>= More than and equal to
<= Less than and equal to
<> Not equal to
10.2 Logical Operators
Sometimes we must make more than one comparison before a decision can
be made and an action taken. In this case, using numerical comparison
operators alone is not enough, we must use the logical operators. The
logical operators are shown in the table 10.2.
Table 10.2 Logical Operators
Operators Description
And Both sides must be true
Or One side or the other must be true
Xor One side or the other must be true but not
both
Not Negates true
The logical operators can be used to compare numerical data as well as non-
numeric data.  To make string comparison, there are certain rules to follow:
Upper case letters are less than lowercase letters, "A"<"B"<"C"<"D"…….
<"Z" and number are less than letters.
10.3 Using If ...Then...Else
To effectively control the program flow, we shall use the If control
structure together with conditional operators and logical operators. There
are three types of If control structures, namely If...Then statement,
If...Then...Else statement and If...Then...ElseIf statement.
10.3.1 If ...Then Statement
This is the simplest control structure which instructs the computer to
perform a certain action if the condition is true. However, when the
condition is false, no action will be performed. The syntax for the If...Then
statement is

If condition Then

Visual Basic 2022 expressions

End If

Example 10.1 Using If…Then Statement

Private Sub Button1_Click(ByVal sender As Object, ByVal e As


EventArgs) Handles Button1.Click

Dim myNumber As Integer

myNumber = TextBox1.Text

If myNumber > 100 Then

Label2.Text = " You win a lucky prize"

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

End If condition2 Then


Expression2
Else
Expression 3
End If
Example 10.2 Lucky Draw Simulation

This is a lucky draw simulation program. We use the Rnd() function to


generate a random number between 0 and 1. In addition, we use the formula
Int(Rnd() * 10) + 1 to generate a random integer from 1 and 10. Next, we
use the If...Then...Else statement to determine the condition for striking a
lucky draw.  To design the UI, we insert two labels, one of them is to
display the generated number and the other one is to display the message of
the lucky draw outcome. In addition, we insert a button and rename it as
BtnDraw then click it and enter the following code:

Public Sub BtnBet_Click(sender As Object, e As EventArgs) Handles


BtnBet.Click
 
        Dim myNum As Integer
       myNum = InputBox("Enter your lucky number and click OK")
 
        If myNum > LuckyNum Then
           MsgBox("Your number is too big")
        ElseIf myNum < LuckyNum Then
            MsgBox("Your number is too small")
        Else
           MsgBox("Congratulations! You strike the lucky number")
        End If
 
    End Sub
 
 
Executing the code will display the output UI , as shown in Figure 10.1
Figure 10.1
To start the lucky draw, click the ‘Generate Lucky Number" button to
generate the lucky number. Click the "Bet" button to bring up an input box,
enter your lucky number and click OK, as shown in figure 10.2.

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

We modified Example 10.2 and add in an additional constraint, age. In this


program, we use the logical operator And beside the conditional operators.
This implies that both conditions must be fulfilled for the outcomes to be
true, otherwise the second block of code will be executed. In this example,
the lucky number must be more than 120 and the age must be more than 50
in order to win a lucky prize, any one of the above conditions not fulfilled
will disqualify the user from winning a lucky prize. In addition, we make
the program more interactive by adding a name in the message. The code is
as follows:

Public Class Form1


    Dim myAge As Integer

   Dim myName As String

 
Private Sub BtnDraw_Click(sender As Object, e As EventArgs) Handles
BtnDraw.Click

Dim myNumber As Integer

myAge = TxtAge.Text

myName = TxtName.Text

myNumber = Int(Rnd() * 200) + 1

LblNum.Text = myNumber

If myNumber > 120 And myAge > 50 Then

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

Visual Basic 2022 expression

ElseIf condition 1 Then

Visual Basic 2022 expression

ElseIf condition 2 Then

Visual Basic 2022 expression

Else

Visual Basic 2022 expression

End If

Example 10.4 Grade Generator

Private Sub BtnCompute_Click(ByVal sender As Object, ByVal e As

EventArgs) Handles Button1.Click

Dim Mark As Integer

Dim Grade As String

Mark = Val(TxtMark.Text)

If Mark>=80 Then

Grade="A"

ElseIf Mark>=60 And Mark<80 Then


Grade="B"
ElseIf Mark>=50 And Mark<60 Then
Grade="C"

Else

Grade="D"

End If

MsgBox("You grade is " & Grade)


End Sub
 
Running the program produces a text box for the user to enter the mark.
After entering the mark and clicking the ‘Compute Grade’ button, the grade
will be displayed in a message box, as shown in Figure 10.8

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 expression list 1

Block of one or more Visual Basic 2022 statements

Case expression list 2

Block of one or more Visual Basic 2022 Statements

Case Else

Block of one or more Visual Basic 2022 Statements

End Select

Example 11.1: Examination Grades

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:

Private Sub BtnCompute_Click(ByVal sender As Object, ByVal e As

EventArgs) Handles BtnCompute.Click

Dim grade As String

grade=txtGrade.Text

Select Case grade

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.

Private Sub BtnCompute_Click(ByVal sender As Object, ByVal e As


EventArgs) Handles BtnCompute.Click

Dim mark As integer

mark = TxtMark.Text

Select Case mark

  Case Is >= 85

LblRemark.Text= "Excellence"

  Case Is >= 70

LblRemark.Text= "Good"

Case Is >= 60

LblRemark.Text = "Above Average"

 Case Is >= 50

LblRemark.Text= "Average"

Case Else

LblRemark.Text = "Must work harder"

End Select

End Sub

The output is shown in Figure 11.2.

 
Figure 11.2

Example 11.3 Select Case for a Range of Values

Private Sub BtnCompute_Click(ByVal sender As Object, ByVal e As


EventArgs) Handles BtnCompute.Click

'Examination Marks

Dim mark As Single

mark = TxtMark.Text

Select Case mark

Case 0 to 49

  LblRemark.Text = "Must work harder"

Case 50 to 59

  LblRemark.Text = "Average"

Case 60 to 69

LblRemark.Text= "Above Average"

Case 70 to 84

LblRemark.Text = "Good"

Case 85 to 100

  LblRemark.Text= "Excellence"

Case Else

LblRemark.Text= "Wrong entry, please re-enter the mark"

End Select

End Sub
 

Example 11.4 Computing Exam Grades

Grades in high school are usually presented with grades like A, B, C, D or


E. The grades can be computed as follows:

Private Sub BtnCompute_Click(ByVal sender As Object, ByVal e As


EventArgs) Handles BtnCompute.Click

'Examination Marks

Dim mark As Single

mark = TextBox1.Text

Select Case mark

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

Label1.Text = "Error, please re-enter the mark"

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
 

Looping allows a procedure to run repetitively if the processor and memory

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,

the   Do...loop  and the  While...End While  loop


12.1 For...Next Loop
The structure of a For...Next loop is as follows:
For counter = startNumber to endNumber (Step increment)

One or more Visual Basic 2022 statements

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

Dim counter As Integer

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

Dim counter, sum As Integer

For counter=1 to 100 step 10

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

For counter = 100 To 5 Step -5

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
 

Example 12.4 Exit For

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

Block of one or more Visual Basic 2022 statements

Loop
b)
Do

Block of one or more Visual Basic 2012 statements

Loop While condition


 
c)
Do Until condition

Block of one or more Visual Basic 2012 statements

Loop
d)
Do

Block of one or more Visual Basic 2012 statements

Loop Until condition


 
The syntax to exit a Do Loop is  Exit Do . Let us examine the following
examples:
Example 12.5 Adding Numbers in a Do Loop

Do while counter <=100

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

Loop until counter>100


 
 
 

Example 12.6 Adding Numbers in a Do Loop

Private Sub BtnCompute_Click(ByVal sender As Object, ByVal e As


EventArgs) Handles BtnCompute.Click

Dim sum, n As Integer

MyListBox.Items.Add("n" & vbTab & "Sum")

MyListBox.Items.Add("---------------")

Do

n += 1

sum += n

MyListBox.Items.Add(n & vbTab & sum)

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

MyListBox.Items.Add(n & vbTab & sum)

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

Loop, as shown below:

While conditions

Visual Basic 2022 statements

End While
The loop is illustrated in Example 12.7
Example 12.7 Summation of Numbers using a While End While Loop

Private Sub BtnCompute_Click(ByVal sender As Object, ByVal e As


EventArgs) Handles BtnCompute.Click

Dim sum, n As Integer

ListBox1.Items.Add("n" & vbTab & "sum")

ListBox1.Items.Add("---------------")

While n <> 10

n += 1

sum += n

ListBox1.Items.Add(n & vbTab & sum)

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

Example 13.1 A Sub Procedure that Add Two Numbers

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

Sub Sum(a As Single, b As Single)

Dim mySum As Single


   mySum = a + b
    LblSum.Text = mySum
End Sub
 
Executing the program produces a message box as shown in Figure 13.1

Figure 13.1
Example 13.2: Password Cracker

This is a password cracking program that can generate possible passwords.


It compares each of generated passwords with the actual password; and if
the generated password is found to be equal to the actual password, login
will be successful. In this program, a timer is inserted into the form and it is
used to do a repetitive job of generating the passwords.

We create a password generating procedure called generate ()  and it is


called by the Timer1_Tick() event so that the procedure is repeated after
every interval. The interval of the timer can be set in its properties window
where a value of 1 is 1 millisecond, so a value of 1000 is 1 second: the
smaller the value, the shorter the interval. However, do not set the timer to
zero because if you do that, the timer will not start. We shall set the Timer
interval at 100 which is equivalent to 0.1 second.

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.

Therefore, Int(Rnd*100) will produce a random number between 0 and 99,


and the value of Int(Rnd*100)+100 will produce a random number
between 100 and 199. Finally, the program uses If...Then...Else to check
whether the generated password is equal to the actual password or not; and
if they are equal, the password generating process will be terminated by
setting the Timer1.Enabled property to False. The code is as follows:

Dim password As Integer


Dim crackpass As Integer
Private Sub BtnGenerate_Click(sender As Object, e As EventArgs)
Handles BtnGenerate.Click

Timer1.Enabled = True

End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles

Timer1.Tick

generate()

If crackpass = password Then

Timer1.Enabled = False

LblCrackPass.Text = crackpass

MsgBox("Password Cracked!Login Successful!")

Else Label1.Text = crackpass

LblMsg.Text = "Please wait..."

End If

End Sub
Sub generate()

crackpass = Int(Rnd() * 100) + 100

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

Private Function functionName (Argument As dataType,..........) As


dataType

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

Private Function BMI(Height As Single, weight As Single) As Double

              BMI = weight / Height ^ 2

End Function

Private Sub BtnCal_Click(sender As Object, e As EventArgs) Handles


BtnCal.Click

Dim h As Single, w As Single

h = Val(TxtHeight.Text)

w = Val(TxtWeight.Text)

LblBMI.Text = Format(BMI(h, w), "0.00")


End Sub

The output is as shown in Figure 14.1

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

Private Function FV(pv As Single, i As Single, n As Integer) As Double

FV = pv * (1 + i / 100) ^ n

End Function

Private Sub BtnCal_Click(sender As Object, e As EventArgs) Handles


BtnCal.Click

Dim FutureVal As Single

Dim PresentVal As Single

Dim interest As Single

Dim period As Integer

PresentVal = TxtPV.Text

interest = TxtInt.Text

period = TxtN.Text

FutureVal = FV(PresentVal, interest, period)

LblFV.Text = Format(FutureVal, "$#,##0.00")

End Sub

The Output is shown in Figure 14.2


Figure 14.2
14.2 Passing Arguments by Value and by
Reference
Functions can be called by value or called by reference.   By default, the
arguments in the function are passed by reference. If arguments are passed
by reference, the original data will be modified and no longer preserved. On
the one hand, if arguments are passed by value, the original data will be
preserved. The keyword to pass arguments by reference is  ByRef  and the
keyword to pass arguments by value is  ByVal .
For example,

Private Function FV(ByVal pv As Single, ByRef i As Single, n As


Integer) As Double

 
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

Private Function sqroot(ByRef x As Single) As Double


x = x ^ 0.5

sqroot = x

End Function

Private Function sqroot1(ByVal y As Single) As Double

y = y ^ 0.5

sqroot1 = y

End Function

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles


Button1.Click

Dim u As Single

u = 9

MsgBox(3 * sqroot(u), , "ByRef")

MsgBox("Value of u is " & u, , "ByRef")

End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles


Button2.Click

Dim u As Single

u = 9

MsgBox(3 * sqroot1(u), , "ByVal")

MsgBox("Value of u is " & u, , "ByVal")

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.

Example 15.1 Computing Absolute Value


 
This program computes the absolute value of a number
The Code 

Private Sub BtnComp_Click(sender As Object, e As EventArgs) Handles

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

Private Sub BtnComp_Click(sender As Object, e As EventArgs) Handles

BtnComp.Click

LblExp.Text = Math.Exp(Val(TxtNum.Text))

End Sub

The Output is shown in Figure 15.2


 
Figure 15.2
15.3 The Fix Function
The Fix function truncates the decimal part of a positive number and returns

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.

Example 15.3 Using Fix

Private Sub BtnComp_Click(sender As Object, e As EventArgs) Handles

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.

Example 15.4 The Log Function

Private Sub BtnComp_Click(sender As Object, e As EventArgs) Handles

BtnComp.Click

LblLog.Text = Math.Log(Val(TxtNum.Text))

End Sub

The Output is shown in Figure 15.4

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

Private Sub BtnGen_Click(sender As Object, e As EventArgs) Handles


BtnGen.Click

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

number of decimal places. The Format is Round (n, m) which means to

round a number n to m decimal places. For example, Math.Round (7.2567,

2) =7.26

Example 15.6 Rounding Numbers

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles


Button1.Click
Dim n As integer
n=Txtn

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.

16.1.1 Built-in Format function for Numbers

The syntax of the built-in Format function is

Format(n, "style argument")

The list of style arguments is listed in Table 16.1


Table 16.1 Style Arguments
Style Explanation Example
Argument
General Display number without Format(8972.234, "General
Number separators Number")=8972.234

Fixed Display number without Format(8972.2, "Fixed")=8972.23


separators and rounds to two
decimal places.

Standard Display number with Format(6648972.265, "Standard")=


separators and rounds  to two 6,648,972.27
decimal places.
Currency Display number with a dollar Format(6648972.265, "Currency")=
sign,has separators and rounds $6,648,972.27
to two decimal places.
Percent Converts the number to the Format(0.56324, "Percent")=56.32 %
percentage form and displays
a % sign and rounds to two
decimal places.

 
Example 16.1 Formatting Numbers

Private Sub BtnFormat_Click(sender As Object, e As EventArgs)

Handles BtnFormat.Click

Label1.Text = Format(8972.234, "General Number")

Label2.Text = Format(8972.2, "Fixed")

Label3.Text = Format(6648972.265, "Standard")

Label4.Text = Format(6648972.265, "Currency")

Label5.Text = Format(0.56324, "Percent")

End Sub

The output is shown in Figure 16.1

Figure 16.1
 

16.1.2 User-Defined Format

The syntax of the user-defined Format function is

Format(n, "user's format")


 

Although it is known as user-defined format, we still must follow certain


formatting styles. Examples of user-defined formatting styles are listed in
Table 16.2.
Table 16.2
Format Description Output

Format(781234.576,"0") Rounds to whole number without  781235


separators between thousands
 Format(781234.576,"0.0") Rounds to 1 decimal place without  781234.6
separators between thousands
 Format(781234.576,"0.00") Rounds to 2 decimal places without  781234.58
separators between thousands
  Format(781234.576,"#,##0.00" Rounds to 2 decimal places with  781,234.58
) separators between thousands
 Format(781234.576,"$#,##0.00 Displays dollar sign and Rounds to 2  $781,234.58
") decimal places with separators between
thousands
 Format(0.576,"0%") Converts to percentage without decimal  58%
place
 Format(0.5768,"0%") Converts to percentage form with two  57.68%
decimal places

 
Example 16.2 Using User-Defined Formats

Private Sub BtnFormat_Click(sender As Object, e As EventArgs)

Handles BtnFormat.Click

Label1.Text = Format(8972.234, "0.0")

Label2.Text = Format(8972.2345, "0.00")

Label3.Text = Format(6648972.265, "#,##0.00")

Label4.Text = Format(6648972.265, "$#,##0.00")

Label5.Text = Format(0.56324, "0%")

End Sub

The Output is shown in Figure 16.2

 
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.

16.2.1 Formatting Date and time using predefined formats 


In Visual Basic 2022 , we can format date and time using predefined
formats or user-defined formats. The predefined formats of date and time
are shown in Table 16.3.
Table 16.3

 Format  Description

Format(Now, "General Displays current date and time


Date")
Format(Now, "Long Displays current date in long format
Date")
Format (Now, "Short Displays current date in short format
date")
Format (Now, "Long Displays current time in long format.
Time")
Format (Now, "Short Displays current time in short format.
Time")
 
 Example 16.3 Formatting Date and Time
Private Sub BtnDisplay_Click(sender As Object, e As EventArgs)

Handles BtnDisplay.Click

Label1.Text = Format(Now, "General Date")

Label2.Text = Format(Now, "Long Date")

Label3.Text = Format(Now, "short Date")

Label4.Text = Format(Now, "Long Time")

Label5.Text = Format(Now, "Short Time")

End Sub

The Output is shown in Figure 16.3

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:

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles

Timer1.Tick

Label1.Text = Format(Now, "General Date")

Label2.Text = Format(Now, "Long Date")

Label3.Text = Format(Now, "short Date")

Label4.Text = Format(Now, "Long Time")

Label5.Text = Format(Now, "Short Time")

End Sub

16.2.2  Formatting Date and time using user-defined formats

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, "m") Displays current month and date

Format (Now, "mm") Displays current month in double digits.

Format (Now, "mmm") Displays abbreviated name of the current month

Format (Now, "mmmm") Displays full name of the current month.


Format (Now, "dd/mm/yyyy") Displays current date in the day/month/year format.

Format (Now, "mmm,d,yyyy") Displays current date in the Month, Day, Year Format

Format (Now, "h:mm:ss tt") Displays current time in hour:minute:second format


and show am/pm

Format (Now, "MM/dd/yyyy Displays current date and time in hour:minute:second


h:mm:ss) format

Example 16.4 Formatting Date and Time with User-Defined Format

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles

Timer1.Tick

Label1.Text = Format(Now, "m")

Label2.Text = Format(Now, "mm")

Label3.Text = Format(Now, "mmm")

Label4.Text = Format(Now, "mmmm")

Label5.Text = Format(Now, "dd/mm/yyyy")

Label6.Text = Format(Now, "mmm,d,yyyy")

Label7.Text = Format(Now, "h:mm:ss tt")

Label8.Text = Format(Now, "MM/dd/yyyy h:mm:ss tt")

End Sub

The output is shown in Figure 16.4


 
Figure 16.4
 
Summary
●         In section 16.1(a), you have learned how to use the built-in format
function
●     In section 16.1(b), you have learned how to use the user-defined format
function
●     In section 16.2(a), you have learned how to format date and time using
predefined formats.
●     In section 16.2(b), you have learned how to format date and time using
user-defined formats.
Chapter 17 Checkbox and Radio Button
In this chapter, we shall learn how to use two very useful controls in,
checkbox and radio button.
17.1 Checkbox
A  Checkbox allows the user to select one or more items by checking the

check box or check boxes concerned. For example, in the Font dialog box

of any Microsoft Text editor like FrontPage, there are

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.

Example 17.1: Online Shopping Mall

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

Const IPhone As Integer = 5000

Const Samsung As Integer = 4500

Const Huawei As Integer = 3500

Const Xiaomi As Integer = 2500

Const Vivo As Integer = 3000

Const Oppo As Integer = 3399

Dim sum As Integer

If CheckBox1.Checked = True Then

sum += IPhone
End If

If CheckBox2.Checked = True Then

sum += Samsung
End If

If CheckBox3.Checked = True Then

sum += Huawei

End If

If CheckBox4.Checked = True Then

sum += Xiaomi
End If

If CheckBox5.Checked = True Then

sum += Vivo
End If

If CheckBox6.Checked = True Then

sum += Oppo

End If

LblTotal.Text = sum.ToString("c")

End Sub

Private Sub BtnReset_Click(sender As Object, e As EventArgs) Handles


BtnReset.Click

CheckBox1.Checked = False

CheckBox2.Checked = False

CheckBox3.Checked = False

CheckBox4.Checked = False

CheckBox5.Checked = False

CheckBox6.Checked = False

End Sub

The Runtime Interface is shown in Figure 17.1

Figure 17.1: Shopping Mall

Example 17.2 Shopping Cart

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


System.EventArgs) Handles Button1.Click

Const large As Integer = 10.0

Const medium As Integer = 8

Const small As Integer = 5


Dim sum As Integer

If CheckBox1.Checked = True Then

sum += large

End If

If CheckBox2.Checked = True Then

sum += medium

End If

If CheckBox3.Checked = True Then

sum += small

End If

Label5.Text = sum.ToString("c")

End Sub

Example 17.3 Formatting Fonts

In this example, the text on the label can be formatting using the three
check boxes that represent bold, italic and underline.

The Code

Private Sub ChkBold_CheckedChanged(sender As Object, e As


EventArgs) Handles ChkBold.CheckedChanged

If ChkBold.Checked Then

LblDisplay.Font = New Font(LblDisplay.Font, LblDisplay.Font.Style Or


FontStyle.Bold)

Else

LblDisplay.Font = New Font(LblDisplay.Font, LblDisplay.Font.Style


And Not FontStyle.Bold)

End If

End Sub

Private Sub ChkItalic_CheckedChanged(sender As Object, e As


EventArgs) Handles ChkItalic.CheckedChanged

If ChkItalic.Checked Then

LblDisplay.Font = New Font(LblDisplay.Font, LblDisplay.Font.Style Or


FontStyle.Italic)

Else

LblDisplay.Font = New Font(LblDisplay.Font, LblDisplay.Font.Style


And Not FontStyle.Italic)

End If

End Sub

Private Sub ChkUnder_CheckedChanged(sender As Object, e As


EventArgs) Handles ChkUnder.CheckedChanged

If ChkUnder.Checked Then

LblDisplay.Font = New Font(LblDisplay.Font, LblDisplay.Font.Style Or


FontStyle.Underline)

Else

LblDisplay.Font = New Font(LblDisplay.Font, LblDisplay.Font.Style


And Not FontStyle.Underline)

End If

End Sub

* The program uses the CheckedChanged event to respond to the user


selection by checking a checkbox; it is like the click event. The statement

LblDisplay.Font = New Font(LblDisplay.Font, LblDisplay.Font.Style Or


FontStyle.Italic)

will retain the original font type but change it to italic font style.

LblDisplay.Font = New Font(LblDisplay.Font, LblDisplay.Font.Style


And Not FontStyle.Italic)

will also retain the original font type but change it to regular font style. (The
other statements employ the same logic)

The Output interface is shown in Figure 17.2


Figure 17.2
17.2 Radio Button
Radio buttons operate differently from the check boxes. Radio buttons are
mutually exclusive, which means the user can only choose one item only
out of several choices.

Example 17.4 Shopping Cart with Radio Buttons

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

Private Sub BtnConfirm_Click(sender As Object, e As EventArgs)

Handles BtnConfirm.Click

Dim Tcolor As String

If RadioRed.Checked  Then

Tcolor = "Red Color"

LblDisplay.ForeColor = Color.Red

ElseIf RadioGreen.Checked Then

Tcolor = "Green Color"

LblDisplay.ForeColor = Color.Green

ElseIf RadioBlue.Checked Then

Tcolor = "Blue Color"

LblDisplay.ForeColor = Color.Blue
ElseIf RadioPink.Checked Then

Tcolor = "Pink Color"

LblDisplay.ForeColor = Color.Pink
ElseIf RadioOrange.Checked Then

Tcolor = "Orange Color"

LblDisplay.ForeColor = Color.Orange

Else

Tcolor = "Yellow Color"

LblDisplay.ForeColor = Color.Yellow

End If

LblDisplay.Text = Tcolor

End Sub

The Runtime Interface is shown in Figure 17.3


Figure 17.3

Example 17.5 Multiple Selections Using Groupbox

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

Private Sub BtnConfirm_Click(sender As Object, e As EventArgs)

Handles BtnConfirm.Click

Dim TSize, TColor As String

If RadioXL.Checked Then

TSize = "XL"

ElseIf RadioL.Checked Then

TSize = "L"

ElseIf RadioM.Checked Then

TSize = "M"

Else : TSize = "S"

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

The Runtime Interface is shown in Figure 17.5


Figure 17.5

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.

Therefore, a good programmer should be more alert to the parts of the


program that could trigger errors and should write errors handling code to
help the user in managing the errors. Writing errors handling code is a good
practice for Visual Basic 2022 programmers, so do not try to finish a
program fast by omitting the errors handling code. However, there should
not be too many errors handling code in the program as it creates problems
for the programmer to maintain and troubleshoot the program later.

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

On Error GoTo program_label structure. Although it has a more advanced

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

On Error GoTo program_label

* program_label is the section of code that is designed by the programmer


to handle the error committed by the user. Once an error is detected, the
program will jump to the program_label section for error handling.

Example 18.1 Division Errors


In this example, we will deal with the error of entering non-numeric data
into the text boxes that are supposed to hold numeric values. The
program_label here is error_handler. when the user enters a non-numeric
value into the text boxes, the error message will display the text "One or
both of the entries is/are non-numeric!". If no error occurs, it will display
the correct answer. Try it out yourself.

The Code

Private Sub BtnCal_Click(sender As Object, e As EventArgs) Handles

BtnCal.Click

Lbl_ErrMsg.Visible = False

Dim firstNum, secondNum As Double

On Error GoTo error_handler

firstNum = TxtNum1.Text

secondNum = TxtNum2.Text

Lbl_Answer.Text = firstNum / secondNum

Exit Sub 'To prevent error handling even the inputs are valid

error_handler:

Lbl_Answer.Text = "Error"

Lbl_ErrMsg.Visible = True

Lbl_ErrMsg.Text = "One or both of the entries is/are non-numeric! Try

again!"

End Sub

The runtime interface is shown in Figure 18.1


Figure 18.1

*Please note that division by zero in Visual Basic 2022 no longer gives an

error message, but it displays the answer as Infinity ( ∞ ).


18.2 Using Try…Catch ...End Try Structure
Visual Basic 2022 has adopted a new approach in handling errors, or rather
exceptions handling. It is supposed to be more efficient than the old On
Error Goto method, where it can handle various types of errors within the
Try…Catch…End Try structure. The structure is as follows:

Try

statements

Catch exception_variable As Exception

statements to deal with exceptions

End Try

Example 18.1 Data Types Mismatch Errors

Private Sub BtnCal_Click(sender As Object, e As EventArgs) Handles


BtnCal.Click

Lbl_ErrMsg.Visible = False

Dim firstNum, secondNum, answer As Double

Try

firstNum = TxtNum1.Text

secondNum = TxtNum2.Text

answer = firstNum / secondNum

LblAnswer.Text = answer

Catch ex As Exception

LblAnswer.Text = "Error"

Lbl_ErrMsg.Visible = True

Lbl_ErrMsg.Text = " One or both of the entries is/are non-numeric! Try


again!"

End Try

End Sub

The runtime interface is shown in Figure 18.2

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.

For a programming language to qualify as an object-oriented programming


language, it must have three core technologies: encapsulation, inheritance
and polymorphism. These three terms are explained below:

(a) Encapsulation

Encapsulation refers to the creation of self-contained modules that bind


processing functions to the data. These user-defined data types are called
classes. Each class contains data as well as a set of methods which
manipulate the data. The data components of a class are called instance
variables and one instance of a class is an object. For example, in a library
system, a class could be a member, and John and Sharon could be two
instances (two objects) of the library class.

(b) Inheritance

Classes are created according to hierarchies, and inheritance allows the


structure and methods in one class to be passed down the hierarchy. That
means less programming is required when adding functions to complex
systems. If a step is added at the bottom of a hierarchy, then only the
processing and data associated with that unique step needs to be added.
Everything else about that step is inherited.

(c) Polymorphism

Object-oriented programming allows procedures about objects to be created


whose exact type is not known until runtime. For example, a screen cursor
may change its shape from an arrow to a line depending on the program
mode. The routine to move the cursor on screen in response to mouse
movement would be written for "cursor," and polymorphism allows that
cursor to take on whatever shape is required at runtime. It also allows new
shapes to be easily integrated.
19.2 Creating a Class
Visual Basic 2022 allows us to write programs that break down into
modules. These modules represent the real-world objects and are known as
classes or types. An object can be created out of a class, and it is known as
an instance of the class. A class can comprises subclass. For example, an
apple tree is a subclass of the plant class and the apple in your backyard is
an instance of the apple tree class. Another example is a student class is a
subclass of the human class while your son John is an instance of the
student class. A class consists of data members as well as methods. In
Visual Basic 2022, the program structure to define a Human class can be
written as follows:

Public Class Human

'Data Members

Private Name As String

Private Birthdate As String

Private Gender As String

Private Age As Integer

'Methods

Overridable Sub ShowInfo()

MessageBox.Show(Name)

MessageBox.Show(Birthdate)

MessageBox.Show(Gender)

MessageBox.Show(Age)

End Sub

End Class

Another Example:

Public Class Car

'Data Members

Private Brand As String

Private Model As String

Private Year Made As String

Private Capacity As Integer

'Methods

Overridable Sub ShowInfo()

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).

Example 19.1 BMI Class


To create a class, start Visual Basic 2022 as usual and choose Windows
Applications. In the Visual Basic 2022 IDE, click on Project on the menu
bar and select Add Class, the Add New Item dialog appears, as shown in
Figure 19.1
Figure 19.1

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

Public Class MyClass1

Public Function BMI(ByVal height As Single, ByVal weight As Single)

BMI = Format((weight) / (height ^ 2), "0.00")

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.

Private Sub BtnBMI_Click(sender As Object, e As EventArgs) Handles


BtnBMI.Click

Dim MyObject As Object

Dim h, w As Single

MyObject = New MyClass1()

h = InputBox("What is your height in meter")

w = InputBox("What is your weight in kg")

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.

Since Visual Basic evolved into an object-oriented programming language


under the VB.net framework, shape controls are no longer available. Now
the programmer needs to write code to create various shapes and drawings.
Even though the learning curve is steeper, the programmer can write
powerful code to create all kinds of graphics. You can even design your
own controls.

Visual Basic 2022 offers various graphics capabilities that enable


programmers to write code that can create all kinds of shapes and even
fonts.
20.2 Creating the Graphics Object
Before you can draw anything on a form, you must create the Graphics

object in Visual Basic 2022. A graphics object is created using the

CreateGraphics()   method. You can create a graphics object that draws to

the form itself or a control.

To draw graphics on the default form, you can use the following statement:

Dim myGraphics As Graphics = me.CreateGraphics

To draw a picture box, you can use the following statement:

Dim myGraphics As Graphics = PictureBox1.CreateGraphics

You can also use the text box as a drawing surface, the statement is:

Dim myGraphics As Graphics = TextBox1.CreateGraphics

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

can create a pen in the following section.


20.3 Creating the Pen Object
A Pen can be created using the following code:

myPen = New Pen(Brushes.Color, LineWidth)

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:

myPen = New Pen(Brushes.DarkMagenta, 10)

You can also create a Pen using the following statement:

Dim myPen As Pen

myPen = New Pen(Drawing.Color.Blue, 5)

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

draw graphics on the screen.


20.4 Drawing a Straight Line
In this section, we will show you how to draw a straight line on the Form.

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.

Private Sub BtnDraw_Click(sender As Object, e As EventArgs) Handles

BtnDraw.Click

Dim myGraphics As Graphics = Me.CreateGraphics

Dim myPen As Pen

myPen = New Pen(Brushes.DarkMagenta, 20)

myGraphics.DrawLine(myPen, 60, 180, 220, 50)

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

coordinate of the line. The syntax of the Drawline argument is

object.DrawLine(Pen, x1, y1, x2, y2)


For the above example, the starting coordinate is (60,80) and the ending
coordinate is (220,50). Figure 20.1 shows the line created by the program.

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:

Point() = {point1, point2, point3, point4,.............}


We must declare the array using the Dim keyword, as follows:

Dim MyPoints As Point() = {point1, point2, point3, point4,.....}


In addition, each point must declare using the Dim keyword, as follows:

Dim point1 As New Point (x1,y1)

Dim point2 As New Point (x2,y2)

Dim point3 As New Point (x3,y3)

Example 20.1 Drawing straight lines that connect multiple points

Private Sub BtnDrawLine_Click(sender As Object, e As EventArgs)

Handles BtnDrawLine.Click

Dim point1 As New Point(30, 30)

Dim point2 As New Point(70, 15)

Dim point3 As New Point(100, 5)

Dim point4 As New Point(200, 70)

Dim point5 As New Point(350, 90)

Dim point6 As New Point(300, 150)

Dim point7 As New Point(20, 200)

Dim myPoints As Point() = {point1, point2, point3, point4, point5,

point6, point7}

Dim myGraphics As Graphics = Me.CreateGraphics

Dim myPen As Pen

     myPen = New Pen(Brushes.OrangeRed, 2)

     myGraphics.DrawLines(myPen, myPoints)

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:

Point() = {point1, point2, point3, point4,.............}


We must declare the array using the Dim keyword, as follows:

Dim MyPoints As Point() = {point1, point2, point3, point4,.....}


In addition, each point must declare using the Dim keyword, as follows:

Dim point1 As New Point (x1,y1)

Dim point2 As New Point (x2,y2)

Dim point1 As New Point (x3,y3)

Example 20.2 Drawing a Curve

Private Sub BtnDrawCurve_Click(sender As Object, e As EventArgs)

Handles BtnDrawCurve.Click

Dim point1 As New Point(30, 30)

Dim point2 As New Point(70, 15)

Dim point3 As New Pozzsxint(100, 5)

Dim point4 As New Point(200, 70)

Dim point5 As New Point(350, 90)

Dim point6 As New Point(300, 150)

Dim point7 As New Point(20, 200)

Dim myPoints As Point() = {point1, point2, point3, point4,  point5,

point6, point7}

Dim myGraphics As Graphics = Me.CreateGraphics

Dim myPen As Pen

       myPen = New Pen(Brushes.DarkMagenta, 2)

        myGraphics.DrawCurve(myPen, myPoints)

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

the TranslateTransform method of the Graphics class, the syntax is as

follows:

MyGraphics.TranslateTransform(dx:=x1, dy:=y1)
 
where (x1,y1) is the new origin.
Example 20.3 Drawing the Quadratic

In this example, we want to draw a quadratic graph for the following


quadratic function:

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

Private p(500) As Point

Private Sub BtnDrawCurve_Click(sender As Object, e As EventArgs)

Handles BtnDrawCurve.Click

        Dim x, y, i As Double

       For i = 0 To 500

            x = i - 250

            y = (300 - (x ^ 2 - 3 * x + 1)) / 200

            p(i) = New Point(x, y)

        Next

       Dim myGraphics As Graphics = MyCanvas.CreateGraphics

       Dim myPen As Pen

       myGraphics.TranslateTransform(dx:=250, dy:=295)

        myPen = New Pen(Brushes.DarkMagenta, 2)

       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)

Example 20.4 Drawing a Sine Curve

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

We use the negative to accommodate the new coordinate system. We


multiply it by 80 so that the value is big enough for the coordinate y to be
visible on the drawing canvas.

The Code

Private p(600) As Point

Private Sub BtnDrawCurve_Click(sender As Object, e As EventArgs)

Handles BtnDrawCurve.Click

      Dim x, y, i As Double

       Dim pi As Single

       pi = 2 * Math.Asin(1)

       For i = 0 To 600

           x = i - 300

            y = -(Math.Sin((pi * x) / 180)) * 80

            p(i) = New Point(x, y)

        Next

        Dim myGraphics As Graphics = MyCanvas.CreateGraphics

       Dim myPen As Pen

       myGraphics.TranslateTransform(dx:=300, dy:=180)

       myPen = New Pen(Brushes.DarkMagenta, 2)

        myGraphics.DrawLine(myPen, 0, 100, 0, -200)

        myGraphics.DrawLine(myPen, -300, 0, 300, 0)

        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:

(i)The first is to draw a rectangle directly using

the  DrawRectangle  method by specifying its upper-left corner coordinates

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 .

The syntax is:

myGrapphics.DrawRectangle(myPen, X, Y, width, height)

Where myGraphics is the variable name of the Graphics object and

myPen is the variable name of the Pen object created by you. You can use

any valid and meaningful variable names. X, Y is the coordinate of the

upper left corner of the rectangle while width and height are self-

explanatory, i.e, the width and height of the rectangle.

The code is as follows:

Dim myPen As Pen

myPen = New Pen(Drawing.Color.Blue, 5)

Dim myGraphics As Graphics = Me.CreateGraphics

myGraphics.DrawRectangle(myPen, 0, 0, 100, 50)

(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)

where myRectangle is the rectangle object created by you, the user.

The code to create a rectangle object is as shown below:

Dim myRectangle As New Rectangle

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:

Dim myRectangle As New Rectangle(X,Y,width, height)

The code to draw the above rectangle is

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.

Example 20.5 Drawing a Rectangle with Dash Line Border

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles


Button1.Click
Dim myPen As Pen

myPen = New Pen(Drawing.Color.Blue, 5)

Dim myGraphics As Graphics = Me.CreateGraphics

myPen.DashStyle = Drawing.Drawing2D.DashStyle.Dot

myGraphics.DrawRectangle(myPen, 10, 10, 100, 50)

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.

Therefore, we must create a Rectangle object before we can draw an ellipse.


This rectangle serves as a bounding rectangle for the ellipse. However, you
still must use the  DrawEllipse  method to finish the job. On the other hand,
we can also draw an ellipse with the  DrawEllipse   method without first
creating a rectangle. We shall show you both ways. In the first method, let
us say you have created a rectangle object known as myRectangle and a
pen object as myPen , then you can draw an ellipse using the following
statement:

myGraphics.DrawEllipse(myPen, myRectangle)

Example 20.6 Drawing an Ellipse

Private Sub BtnDraw_Click(sender As Object, e As EventArgs) Handles

BtnDraw.Click

Dim myPen As Pen

myPen = New Pen(Drawing.Color.DarkTurquoise, 5)   

                                       Dim myGraphics As Graphics =

Me.CreateGraphics                                           Dim myRectangle As New

Rectangle

myRectangle.X = 40

myRectangle.Y = 30

myRectangle.Width = 200

myRectangle.Height = 100

myGraphics.DrawEllipse(myPen, myRectangle)

End Sub

The output image is shown in Figure 20.8

Figure 20.8

The second method is using the  DrawEllipse  method without creating a

rectangle object. Of course, you still must create the Graphics and the Pen

objects. The syntax is:


myGraphics.DrawEllipse(myPen, X,Y,Width, Height)

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.

Example 20.7 Drawing Ellipse with DrawEllipse Method

Private Sub BtnDraw_Click(sender As Object, e As EventArgs) Handles

BtnDraw.Click

Dim myPen As Pen

myPen = New Pen(Drawing.Color.DarkTurquoise, 5)

Dim myGraphics As Graphics = Me.CreateGraphics

myGraphics.DrawEllipse(myPen, 40, 30, 200, 100)

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.

Example 20.8 Drawing a Circle

Dim myPen As Pen

myPen = New Pen(Drawing.Color.DarkTurquoise, 5)

Dim myGraphics As Graphics = Me.CreateGraphics

Dim myRectangle As New Rectangle

myRectangle.X = 90

myRectangle.Y = 30

myRectangle.Width = 100

myRectangle.Height = 100

myGraphics.DrawEllipse(myPen, myRectangle)

The output image is shown in Figure 20.9


Figure 20.9
20.12 Drawing Text
In order to draw text on the screen, we can use the DrawString method. The
format is as follows:

myGraphics.DrawString(myText, myFont, mybrush, X , Y)

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

corner of the Text.

You can create the Font object in visual basic 2022 using the following
statement:

myFont = New System.Drawing.Font("Verdana", 20)

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:

myFont = New System.Drawing.Font("Verdana", 20, FontStyle.Bold)


myFont = New System.Drawing.Font("Verdana", 20,
FontStyle.Underline)

myFont = New System.Drawing.Font("Verdana", 20, FontStyle.Italic)

myFont = New System.Drawing.Font("Verdana", 20, FontStyle.Regular)

 
To create your Brush object, you can use the following statement:
 
Dim myBrush As Brush

myBrush = New Drawing.SolidBrush(Color.BrushColor)

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.

Example 20.10 Drawing Text

Private Sub BtnDraw_Click(sender As Object, e As EventArgs) Handles

BtnDraw.Click

Dim myGraphics As Graphics = Me.CreateGraphics

Dim myFont As Font

Dim myBrush As Brush

myBrush = New Drawing.SolidBrush(Color.DarkOrchid)

myFont = New System.Drawing.Font("Verdana", 20,

FontStyle.Underline)

myGraphics.DrawString("Visual Basic 2022", myFont, myBrush, 10, 10)

End Sub

The runtime interface is as shown in Figure 20.10


Figure 20.10
 
Example 20.10 can be modified if you do not want to create the Font and
the Brush objects. You can use the font of an existing object such as the
Form and the System Colors. Replace the last line in the preceding example
with this line (you must delete the lines that create the Brush and Font
objects as well)

myGraphics.DrawString("Visual Basic 2022", me.Font,


System.Drawing.Brushes.DarkOrchid, 10, 10)

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

(the Form object)

The Code is as shown in Example 20.11

Example 20.11 Drawing Text

Private Sub BtnDrawText_Click(sender As Object, e As EventArgs)

Handles BtnDrawText.Click

Dim myGraphics As Graphics = MyPicBox.CreateGraphics

Dim myFont As Font

Dim myBrush As Brush

Dim userMsg As String

userMsg = InputBox("What is your message?", "Message Entry Form",  

"Enter your message here", 100, 200)

myBrush = New Drawing.SolidBrush(Color.DarkOrchid)

myFont = New System.Drawing.Font("Verdana", 20,

FontStyle.Underline)

myGraphics.DrawString(userMsg, myFont, myBrush, 10, 10)

End Sub

 Te runtime interfaces are shown in Figure 20.11 and 20.12

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.

Dim A1 As New Point(X1,Y1)

Dim A2 As New Point(X2,Y2)

Dim A3 As New Point(X3,Y3)

Dim A4 As New Point(X4,Y4)

Dim An As New Point(Xn,Yn)

After declaring the points, we must define a point structure that group all
the points together using the following syntax:

Dim myPoints As Point() = {A1, A2, A3,....,An}

Finally, create the graphics object and use the DrawPolygon method to
draw the polygon using the following syntax:

Dim myGraphics As Graphics = Me.CreateGraphics

myGraphics.DrawPolygon(myPen, myPoints)

where myPen is the Pen object created using the following syntax:

myPen = New Pen(Drawing.Color.Blue, 5)


A triangle is a polygon with three vertices. Let us examine Example 20.12

Example 20.12 Drawing a Triangle

Private Sub BtnDraw_Click(sender As Object, e As EventArgs) Handles

BtnDraw.Click

Dim myPen As Pen

Dim A As New Point(10, 10)

Dim B As New Point(100, 50)

Dim C As New Point(60, 150)

Dim myPoints As Point() = {A, B, C}

myPen = New Pen(Drawing.Color.Blue, 5)

Dim myGraphics As Graphics = Me.CreateGraphics

myGraphics.DrawPolygon(myPen, myPoints)

End Sub

Running the program produces the image as shown in Figure 20.13


Figure 20.13

Example 20.13 Drawing a Quadrilateral

A quadrilateral is a polygon consisting of four sides, so you must define


four vertices.
The Code

Private Sub BtnDraw_Click(sender As Object, e As EventArgs) Handles

BtnDraw.Click

Dim myPen As Pen

Dim A As New Point(10, 10)

Dim B As New Point(100, 50)

Dim C As New Point(120, 150)

Dim D As New Point(60, 200)

Dim myPoints As Point() = {A, B, C, D}

myPen = New Pen(Drawing.Color.Blue, 5)

Dim myGraphics As Graphics = Me.CreateGraphics

myGraphics.DrawPolygon(myPen, myPoints)

End Sub

The output image is as shown in Figure 20.14

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

syntax for drawing a pie is:

myGraphics.DrawPie(myPen, X, Y, width,height, StartAngle,


SweepAngle)

Where X and Y are the coordinates of the bounding rectangle, other


arguments are self-explanatory. Both StartAngle and SweepAngle are
measured in degree. SweepAngle can take possible or negative values. If
the value is positive, it sweeps through clockwise direction while negative
means it sweeps through anticlockwise direction.

Example 20.14 Drawing a pie that sweeps clockwise through 60


degrees.

Private Sub BtnDraw_Click(sender As Object, e As EventArgs) Handles

BtnDraw.Click

Dim myPen As Pen myPen = New Pen(Drawing.Color.Blue, 5)

Dim myGraphics As Graphics = Me.CreateGraphics

myGraphics.DrawPie(myPen, 50,50, 150,150,0,60)

End Sub

The output image is as shown in Figure 20.15


Figure 20.15
20.15 Filling Shapes with Color
In preceding chapters, we have learned how to draw a rectangle, ellipse,
circle, polygon and pie with outlines only. In this chapter, we will show you
how to fill the shapes with color, or simply solid shapes in Visual Basic
2103. Three methods that are used to fill shapes are  FillRectangle,
FillEllipse , FillPolygon  and  FillPie.

In order to fill the above shapes with color, we must create the Brush object
using the following syntax:

myBrush = New SolidBrush(Color.myColor)

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.

20.15.1 Drawing and Filling a Rectangle with Color

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)

Example 20.15 Drawing a Square

Private Sub BtnDraw_Click(sender As Object, e As EventArgs) Handles


BtnDraw.Click
Dim myPen As Pen

Dim myBrush As Brush

Dim myGraphics As Graphics = Me.CreateGraphics

myPen = New Pen(Drawing.Color.Blue, 5)

myBrush = New SolidBrush(Color.Coral)

myGraphics.DrawRectangle(myPen, 65, 50, 150, 150)

myGraphics.FillRectangle(myBrush, 65, 50, 150, 150)

End Sub

The output is as shown in Figure 20.16

Figure 20.16

*Note that if you omit the line  myGraphics.DrawRectangle(myPen, 65, 50,


150, 150) , you will get a solid rectangle without outline, as shown in
Figure 20.17
Figure 20.17
20.15.2 Drawing and Filling an Ellipse with Color
The syntax to fill an ellipse with the color defined by the brush object is:
myGraphics.FillEllipse (myBrush, 0, 0, 150, 150)

Example 20.16 Drawing an Ellipse and Color it

Private Sub BtnDraw_Click(sender As Object, e As EventArgs) Handles


BtnDraw.Click
Dim myPen As Pen

Dim myBrush As Brush

Dim myGraphics As Graphics = Me.CreateGraphics

myPen = New Pen(Drawing.Color.Blue, 5)

myBrush = New SolidBrush(Color.Coral)

myGraphics.DrawEllipse(myPen, 50, 50, 180, 100)

myGraphics.FillEllipse(myBrush, 50, 50, 180, 100)

End Sub

The output interface is as shown in Figure 20.18


Figure 20.18

*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
 

Private Sub BtnDraw_Click(sender As Object, e As EventArgs) Handles

BtnDraw.Click

Dim myPen As Pen

Dim myBrush As Brush

Dim A As New Point(70, 10)

Dim B As New Point(170, 50)

Dim C As New Point(200, 150)

Dim D As New Point(140, 200)

Dim myPoints As Point() = {A, B, C, D}

myPen = New Pen(Drawing.Color.Blue, 5)

myBrush = New SolidBrush(Color.Coral)

Dim myGraphics As Graphics = Me.CreateGraphics

myGraphics.DrawPolygon(myPen, myPoints)

myGraphics.FillPolygon(myBrush, myPoints)

End Sub

The output interface is as shown in Figure 20.19

Figure 20.19

* If you omit  myGraphics the line DrawPolygon(myPen, myPoints),  you


will get a polygon without outline

20.15.4 Drawing and Filling a Pie

The syntax to fill a pie with the color defined by the brush object is:
myGraphics.FillPie(myBrush, X, Y, width, height, StartAngle,
SweepAngle)

Example 20.18 Drawing a Pie and Color It

Private Sub BtnDraw_Click(sender As Object, e As EventArgs) Handles


BtnDraw.Click

Dim myPen As Pen

Dim myBrush As Brush

Dim myGraphics As Graphics = Me.CreateGraphics         

                              myPen = New Pen(Drawing.Color.Blue, 5)

myBrush = New SolidBrush(Color.Coral)

myGraphics.DrawPie(myPen, 30, 40, 150, 150, 0, 60)

myGraphics.FillPie(myBrush, 30, 40, 150, 150, 0, 60)

End Sub

The output is as shown in Figure 20.20

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.

Example 21.1 Creating a Digital Clock

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:

Private Sub Timer1_Tick(sender As System.Object, e As EventArgs)


Handles Timer1.Tick

LblClock.Text = TimeOfDay

End Sub

The digital clock is as shown in Figure 21.1

Figure 21.1

Example 21.2 Creating a Stopwatch


We can create a stopwatch using the Timer control. Start a new project and
name it stopwatch. Change the Form1 caption to Stopwatch . Insert the
Timer control into the form and set its interval to 1000 which is equal to
one second. Besides that, set the timer Enabled property to False so that it
will not start ticking when the program is started. Insert three buttons and
change their names to BtnStart, BtnStop and BtnReset respectively.
Change their text to "Start", "Stop" and "Reset" accordingly. Now, enter the
code as follows:

Private Sub BtnStart_Click(sender As Object, e As EventArgs) Handles


BtnStart.Click

Timer1.Enabled = True

End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles


Timer1.Tick

LblPanel.Text = Val(LblPanel.Text) + 1

End Sub

Private Sub BtnStop_Click(sender As Object, e As EventArgs) Handles


BtnStop.Click

Timer1.Enabled = False

End Sub

Private Sub BtnReset_Click(sender As Object, e As EventArgs) Handles


BtnReset.Click

LblPanel.Text = 0

End Sub

The Interface of the Stopwatch is as shown in Figure 21.2


Figure 21.2

 Example 21.3 Creating a Digital Dice

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

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles


Timer1.Tick

m = m + 10

If m < 1000 Then

n = Int(1 + Rnd() * 6)

LblDice.Text = n

Else

Timer1.Enabled = False

m = 0

End If

End Sub

Private Sub BtnRoll_Click(sender As Object, e As EventArgs) Handles


BtnRoll.Click

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
 

We can use VB2022 to create animation. In the preceding chapter, we have


learned how to create animation using timer. In fact, the programs we have
created in the previous chapter such as the stopwatch and the digital dice
are animated programs. In this Chapter, we shall show you more advanced
animated programs.

We can create a continuously moving object using timer. The motion can be


from left to right or from top to bottom motion or diagonal. Let us examine
Example 22.1.

Example 22.1 Creating a Moving Object

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:

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles


Timer1.Tick

If PictureBox1.Left < Me.Width Then


PictureBox1.Left = PictureBox1.Left + 10

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

Example 22.2 Creating a Graphical Dice

In preceding chapters, we have learned how to create graphics and draw


objects on the form. Now we shall use the previous knowledge to create an
animated graphical dice using timer.

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

syntax  n = Int(6 * Rnd()) + 1.  We can stop the loop by introducing a


variable t and the loop until condition. The condition we set here is t >1000,

you can use any figure you wish.

The code

Private Sub BtnRoll_Click(sender As Object, e As EventArgs) Handles

BtnRoll.Click

Timer1.Enabled = True

End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles

Timer1.Tick

Dim t As Integer

t = 0

Do

MyPicBox.Refresh()

Dim n As Integer

Dim myPen As Pen

myPen = New Pen(Drawing.Color.DarkTurquoise, 10)

Dim myGraphics As Graphics = MyPicBox.CreateGraphics

n = Int(6 * Rnd()) + 1

Select Case n

Case 1

myGraphics.DrawEllipse(myPen, 80, 80, 10, 10)

Case 2

myGraphics.DrawEllipse(myPen, 40, 40, 10, 10)

myGraphics.DrawEllipse(myPen, 120, 120, 10, 10)

Case 3

myGraphics.DrawEllipse(myPen, 40, 40, 10, 10)

myGraphics.DrawEllipse(myPen, 80, 80, 10, 10)

myGraphics.DrawEllipse(myPen, 120, 120, 10, 10)

Case 4

myGraphics.DrawEllipse(myPen, 40, 40, 10, 10)

myGraphics.DrawEllipse(myPen, 120, 40, 10, 10)

myGraphics.DrawEllipse(myPen, 40, 120, 10, 10)

myGraphics.DrawEllipse(myPen, 120, 120, 10, 10)

Case 5

myGraphics.DrawEllipse(myPen, 40, 40, 10, 10)

myGraphics.DrawEllipse(myPen, 120, 40, 10, 10)

myGraphics.DrawEllipse(myPen, 80, 80, 10, 10)

myGraphics.DrawEllipse(myPen, 40, 120, 10, 10)

myGraphics.DrawEllipse(myPen, 120, 120, 10, 10)

Case 6

myGraphics.DrawEllipse(myPen, 40, 40, 10, 10)

myGraphics.DrawEllipse(myPen, 120, 40, 10, 10)

myGraphics.DrawEllipse(myPen, 40, 80, 10, 10)

myGraphics.DrawEllipse(myPen, 120, 80, 10, 10)

myGraphics.DrawEllipse(myPen, 40, 120, 10, 10)

myGraphics.DrawEllipse(myPen, 120, 120, 10, 10)

End Select

t = t + 1

Loop Until t > 1000

Timer1.Enabled = False

End Sub

The runtime interface is as shown in Figure 22.2


Figure 22.2

Example 22.3 Creating a Slot Machine

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

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles


Timer1.Tick

m = m + 10

If m < 1000 Then

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

LblMsg.Text = "Jackpot! You won $1,000,000"

Else

LblMsg.Text = "No luck, try again"

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

Information age, it is no longer feasible to manage data manually. Most data

are now managed using computer-based database management systems.

Computer-based Database management systems can handle data much

faster, more accurate and more efficient than human beings do. With the

advent of the network and the Internet technologies, data can now be

managed locally and remotely.

Companies usually invest heavily in database management systems in order


to run the organizations efficiently and effectively. Database management
systems are usually used in running payroll systems, inventory system,
accounting system, payment system, order handling system, customer
relationship management system (CRM) and more. Some of the
commercial database management systems (DBMS) are Oracle, Microsoft
SQL server and Microsoft Access
23.2 Creating a Database Application
A database management system typically deals with storing, modifying, and
extracting information from a database. It can also add, edit and delete
records from the database. However, a DBMS can be difficult to handle by
ordinary people or businessmen who have no technological backgrounds.
Fortunately, we can create user friendly database applications to handle the
jobs with the DBMS running in the background. One of the best programs
that can create such database applications is none other than Visual Basic
2022.

Visual Basic 2022 uses ADO.NET to handle databases. ADO.NET is


Microsoft’s latest database technology which can work with many other
advanced database management systems such as Microsoft SQL server. In
this chapter, we will develop codes that make use of SQL Server 2022;
therefore, you must have Microsoft SQL Server 2022 installed in your PC,
you can download Microsoft SQL Server 2022 Express for free from

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

Contacts as we will be building a database of contact list. There are a few

objects in ADO.NET that are required to build the database. There are:

●     SqlConnection- to connect to a data source in SQL Server.


●     DataTable -to store data for navigation and manipulation.
●     DataAdapter- to populate a DataReader

The objects belong to the System.Data and System.Xml namespace.

Therefore, we must reference them in the beginning before we can work

with them. To reference the ADO.NET object, choose project from the

menu then select Database Project 1 properties to display the project

properties. Next click the References tab to show the active references for

the project, as shown in Figure 23.1

Figure 23.1

Under imported namespaces, make sure system.data, System.Data.Sqlclient


are selected, otherwise check them. Having done that, you must click the
Save All button on the toolbar and then return to the Visual Basic 2022
IDE.
23.3 Creating a Connection to a Database using
ADO.NET
In Visual Basic 2022, we must create a connection to a database before we
can access its data. Before we begin, let us create a new database. Since we
are using SQL Server 2022 as the database engine, we will use SQL Server
Management Studio  to create a database file with the mdf extension.You
can download SQL Server Management Studio (SSMS) for free.

from the link below:

https://docs.microsoft.com/en-us/sql/ssms/download-sql-server-
management-studio-ssms

We suggest you download the latest SSMS,  SQL Server Management


Studio 17.4. Upon launching SSMS, the initial dialog will ask you to
connect it to the SQL server, as shown in Figure 23.2.

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

will create a database file. To create a new database, right-click on

databases and select New Database, as shown in Figure 23.4


Figure 23.4

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

initial number of rows, as shown in Figure 23.5. In our example, we will

create a database name known as customer, the database file is

customer.mdf. After creating the database file, it will appear in SSMS, as

shown in Figure 23.6


 

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

The ADO.NET object offers a number of connection objects such as


  OleDbConnection,  SqlConnection   and more. OleDbConnection is
used to access OLEDB data such as Microsoft Access whilst
SqlConnection is used to access data provided by Microsoft SQL server.
Since we will work with SQL databases in our example, we will use the
SqlConnection object. To initialize the variable to a new SqlConnection
object, we use the following syntax:

Private MyCn As New SqlConnection

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:

MyCn.ConnectionString ="Data Source=.\SQLEXPRESS;


AttachDbFilename=C:\Users\admin.DESKTOP-
G1G4HEK\Documents\My Websites\vbtutor\vb2022\customer.mdf;
Integrated Security=True; Connection Timeout=30;" & "User
Instance=True"
 

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.

The next step is to create an instance of the  SqlDataAdpate r  in our code


so that we can populate the DataTable with data from the data source.
Besides, you also must create an instance of the  DataTable . Other than
that, you should also create an instance of
the  SqlCommandBuilder  which is used to manipulate data such as
updating and deleting data in the data table and send the changes back to
the data source. The statements are:

Private MyDatAdp As New SqlDataAdapter

Private MyCmdBld As New SqlCommandBuilder

Private MyDataTbl As New DataTable

Besides that, we must declare a variable to keep track of the user’s current
row within the data table. The statement is

Private MyRowPosition As Integer = 0

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 = New SqlDataAdapter("Select* from Contacts", MyCn)

MyCmdBld = New SqlCommandBuilder(MyDatAdp)

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:

Dim MyDataRow As DataRow = MyDataTbl.Rows(0)

Dim strName As String

Dim strState As String

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.

showRecords() is a sub procedure created to show data in the text boxes.


The code is as follows:

Private Sub showRecords()

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

The full Code is shown in Example 23.1

Example 23.1 Creating a Customer Contact List

Private MyDatAdp As New SqlDataAdapter

Private MyCmdBld As New SqlCommandBuilder

Private MyDataTbl As New DataTable

Private MyCn As New SqlConnection

Private MyRowPosition As Integer = 0

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles

MyBase.Load

MyCn.ConnectionString ="Data Source=.\SQLEXPRESS;

AttachDbFilename=C:\Users\Documents\vb2022\customer.mdf;
Integrated Security=True; Connection Timeout=30;" & "User

Instance=True"

MyCn.Open()

MyDatAdp = New SqlDataAdapter("Select* from Contacts", MyCn)

MyCmdBld = New SqlCommandBuilder(MyDatAdp)

MyDatAdp.Fill(MyDataTbl)

Dim MyDataRow As DataRow = MyDataTbl.Rows(0)

Dim strName As String

Dim strState As String

Dim strPhone As String

Dim strIncome As Double

        strName = MyDataRow("CusName")

       strPhone = MyDataRow("PhoneNum")

        strState = MyDataRow("State")

        strIncome = MyDataRow("Income")

        TxtCusName.Text = strName.ToString()

        TxtContact.Text = strPhone.ToString()

        TxtState.Text = strState.ToString()

        TxtIncome.Text = strIncome.ToString()

Me.showRecords()

End Sub

If MyDataTbl.Rows.Count = 0 Then

           TxtCusName.Text = ""

           TxtContact.Text = ""

           TxtState.Text = ""

            TxtIncome.Text = ""

            Exit Sub

        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

The output interface is shown in Figure 23.10

 
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.

The code for moving to the first record is


MyRowPosition = 0

Me.showRecords()

The code for moving to previous record is

If MyRowPosition > 0 Then

MyRowPosition = MyRowPosition - 1

Me.showRecords()

End If
The code for moving to next record is

If MyRowPosition < (MyDataTbl.Rows.Count - 1) Then

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:

If MyDataTbl.Rows.Count <> 0 Then

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:

Dim MyNewRow As DataRow = MyDataTbl.NewRow()

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

Example 23.2 Browsing the Database

Private MyDatAdp As New SqlDataAdapter

Private MyCmdBld As New SqlCommandBuilder

Private MyDataTbl As New DataTable

Private MyCn As New SqlConnection

Private MyRowPosition As Integer = 0

Private Sub Form1_FormClosed(sender As Object, e As EventArgs)


Handles
Me.FormClosed

MyCn.Close()

MyCn.Dispose()

End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles


MyBase.Load

MyCn.ConnectionString = "Data Source=.\SQLEXPRESS;


AttachDbFilename=C:\Users\Documents\vb2022\customer.mdf;
Integrated Security=True; Connection Timeout=30;" & "User
Instance=True"
 

MyCn.Open()

MyDatAdp = New SqlDataAdapter("Select* from cuslist", MyCn)

        MyCmdBld = New SqlCommandBuilder(MyDatAdp)

        MyDatAdp.Fill(MyDataTbl)

       Dim MyDataRow As DataRow = MyDataTbl.Rows(0)

       Dim strName As String

       Dim strState As String

       Dim strPhone As String

       Dim strIncome As Double

       strName = MyDataRow("CusName")

        strPhone = MyDataRow("PhoneNum")

        strState = MyDataRow("State")

       strIncome = MyDataRow("Income")

        TxtCusName.Text = strName.ToString()

        TxtContact.Text = strPhone.ToString()

        TxtState.Text = strState.ToString()

        TxtIncome.Text = strIncome.ToString()

       Me.showRecords()

   End Sub

Private Sub showRecords()

If MyDataTbl.Rows.Count = 0 Then

            TxtCusName.Text = ""

            TxtContact.Text = ""

            TxtState.Text = ""

            TxtIncome.Text = ""

           Exit Sub

       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

Private Sub BtnMovePrev_Click(sender As Object, e As EventArgs)


Handles BtnMovePrev.Click

If MyRowPosition > 0 Then

MyRowPosition = MyRowPosition - 1

Me.showRecords()

End If

End Sub

Private Sub BtnMoveNext_Click(sender As Object, e As EventArgs)


Handles BtnMoveNext.Click

If MyRowPosition < (MyDataTbl.Rows.Count - 1) Then

MyRowPosition = MyRowPosition + 1

Me.showRecords()

End If

End Sub

Private Sub BtnMoveLast_Click(sender As Object, e As EventArgs)


Handles BtnMoveLast.Click

If MyDataTbl.Rows.Count > 0 Then

MyRowPosition = MyDataTbl.Rows.Count - 1

Me.showRecords()

End If

End Sub

Private Sub BtnAdd_Click(sender As Object, e As EventArgs) Handles


BtnAdd.Click

Dim MyNewRow As DataRow = MyDataTbl.NewRow()

MyDataTbl.Rows.Add(MyNewRow)

MyRowPosition = MyDataTbl.Rows.Count - 1

Me.showRecords()

End Sub

Private Sub BtnDelete_Click(sender As Object, e As EventArgs)


Handles BtnDelete.Click

If MyDataTbl.Rows.Count <> 0 Then

MyDataTbl.Rows(MyRowPosition).Delete()

MyRowPosition = 0

MyDatAdp.Update(MyDataTbl)

Me.showRecords()

End If

End Sub

Private Sub BtnSave_Click(sender As Object, e As EventArgs) Handles


BtnSave.Click

If MyDataTbl.Rows.Count <> 0 Then

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:

Private Datastr As String = "Data Source=.\SQLEXPRESS;

AttachDbFilename=C:\Users\Documents\vb2022\customer.mdf;

Integrated Security=True; Connection Timeout=30;" & "User

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

Private Datastr As String = "Data Source=.\SQLEXPRESS;

AttachDbFilename=C:\Users\Documents\vb2022\customer.mdf;

Integrated Security=True; Connection Timeout=30;" & "User

Instance=True"

Private Sub BtnShow_Click(sender As Object, e As EventArgs) Handles

BtnShow.Click

Dim Mycon As New SqlConnection(Datastr)

Dim MySelect As String = "Select CusName, PhoneNum,State, Income

from cuslist"

Dim MyAdpt As New SqlDataAdapter(MySelect, Mycon)

Dim Myds As New DataSet()

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:

Dim mySelectQuery As String = "Select SUM (Income) FROM mylist;"

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.

Example 23.4 Performing Arithmetic Calculations in a Database

Private Datastr As String = "Data Source=.\SQLEXPRESS;

AttachDbFilename=C:\Users\Documents\vb2022\family.mdf; Integrated

Security=True; Connection Timeout=30;" & "User Instance=True"

Private searchterm As String

Private Sub BtnShow_Click(sender As Object, e As EventArgs) Handles


BtnShow.Click

Dim Mycon As New SqlConnection(Datastr)

Dim MySelect As String = "Select Name, Income from mylist;"

Dim Adpt As New SqlDataAdapter(MySelect, Mycon)

Dim Myds As New DataSet()

   Adpt.Fill(Myds, "mylist")

    DataGridView1.DataSource = Myds.Tables(0)

End Sub
 
 

'Sub procedure to calculate the sum of income

Public Sub totalIncome(ByVal myConnString As String, ByVal

searchValue As String)

Dim MyDatApt As New SqlDataAdapter

Dim Myds As New DataSet

Dim mySelectQuery As String = "Select SUM (Income) FROM mylist;"

Dim myConn As New SqlConnection(myConnString)

Dim myCommand As New SqlCommand(mySelectQuery, myConn)

myConn.Open()

MyDatApt.SelectCommand = myCommand

LblTotal.Text =

Convert.ToString(Math.Round(myCommand.ExecuteScalar, 2))

myConn.Dispose()     'To dispose the object to release more memory

End Sub

Private Sub BtnCalInc_Click(sender As Object, e As EventArgs)

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

Private Datastr As String = "Data Source=.\SQLEXPRESS;

AttachDbFilename=C:\Users\Documents\vb2022\family.mdf; Integrated

Security=True; Connection Timeout=30;" & "User Instance=True"

Private searchterm As String

Private Sub BtnShow_Click(sender As Object, e As EventArgs) Handles


BtnShow.Click

Dim Mycon As New SqlConnection(Datastr)

Dim MySelect As String = "Select Name, Income from mylist"

Dim Adpt As New SqlDataAdapter(MySelect, Mycon)

Dim Myds As New DataSet()

Adpt.Fill(Myds, "mylist")

DataGridView1.DataSource = Myds.Tables(0)

End Sub

Public Sub Income(ByVal myConnString As String, ByVal searchValue

As String)

Dim MyDatApt As New SqlDataAdapter

Dim Myds As New DataSet

Dim mySelectQuery As String = "Select SUM (Income) FROM mylist;"

Dim mySelectQuery2 As String = "Select AVG (Income) FROM

mylist;"

Dim myConn As New SqlConnection(myConnString)

Dim myCommand As New SqlCommand(mySelectQuery, myConn)

Dim myCommand2 As New SqlCommand(mySelectQuery2, myConn)

        myConn.Open()

        MyDatApt.SelectCommand = myCommand

        MyDatApt.SelectCommand = myCommand2

LblTotal.Text =

Convert.ToString(Math.Round(myCommand.ExecuteScalar, 2))

LblAvg.Text =

Convert.ToString(Math.Round(myCommand2.ExecuteScalar, 2))

        myConn.Dispose()

End Sub

Private Sub BtnCalInc_Click(sender As Object, e As EventArgs)


Handles BtnCalInc.Click

        Income(Datastr, searchterm)

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

SELECT COUNT(column_name) FROM table_name WHERE


condition;
We shall show how it works in Example 23.6
Example 23.6 Using the Count Function

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:

Dim mySelectQuery3 As String = "Select COUNT (Income) FROM


mylist WHERE Income<20000;"

Modify this part of the code in Example 23.5, as follows:


 

Public Sub Income(ByVal myConnString As String, ByVal searchValue As

String)

Dim MyDatApt As New SqlDataAdapter

Dim Myds As New DataSet

Dim mySelectQuery As String = "Select SUM (Income) FROM mylist;"

Dim mySelectQuery2 As String = "Select AVG (Income) FROM mylist;"

Dim mySelectQuery3 As String = "Select COUNT (Income) FROM mylist

WHERE Income<20000;"

        Dim myConn As New SqlConnection(myConnString)

       Dim myCommand As New SqlCommand(mySelectQuery, myConn)

        Dim myCommand2 As New SqlCommand(mySelectQuery2,

myConn)

       Dim myCommand3 As New SqlCommand(mySelectQuery3,


myConn)

        myConn.Open()

        MyDatApt.SelectCommand = myCommand

        MyDatApt.SelectCommand = myCommand2

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

The output is shown in Figure 23.15


 
Figure 23.15
 
 
Summary
●     In section 23.1, you have understood the concepts of database.
●     In section 23.2, you have learned how to create a database.
●         In section 23.3, you have learned how to create a connection to a
database.
●     In section 23.4, you have learned how to populate a database.
●         In section 23.5, you have learned how to write code for browsing
records.
●     In section 23.5, you have learned how to write code for editing, saving,
adding and deleting records in a database.
Chapter 24 Reading and Writing Text Files
To be able to open a file and read the data from the storage unit of a
computer, such as a hard drive as well as able to save the data into the
storage unit are important functions of a computer program. In fact, the
ability to store, retrieve and modify data makes a computer a powerful tool
in database management.

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:

Dim FileReader As StreamReader

If we do not include the Imports System.IO, we must use the statement.

Dim FileReader As IO.StreamReader

each time we want to use the StreamReader class.

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.

Dim results As DialogResult

Dim OpenFileDialog1 As New OpenFileDialog()

results = OpenFileDialog1.ShowDialog

If results = DialogResult.OK Then

'Code to be executed if OK button was clicked

Else

'Code to be executed if Cancel button was clicked

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:

FileReader = New StreamReader(OpenFileDialog1.FileName)

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

Public Class Form1

Private Sub BtnOpen_Click(sender As Object, e As EventArgs) Handles


BtnOpen.Click

Dim FileReader As StreamReader

Dim results As DialogResult

Dim OpenFileDialog1 As New OpenFileDialog()

results = OpenFileDialog1.ShowDialog

If results = DialogResult.OK Then

FileReader = New StreamReader(OpenFileDialog1.FileName)

TxtEditor.Text = FileReader.ReadToEnd()

FileReader.Close()

End If

End Sub
 

The Design Interface is shown in Figure 24.1


Figure 24.1

The Open Dialog box is shown in Figure 24.2

Figure 24.2

 The Output Interface is shown in Figure 24.3


Figure 24.3
24.3 Writing to a Text File
Writing a text file means storing the text entered by the user via the textbox
into a storage device such as a hard drive. It also means saving the file. To
accomplish this task, we must deploy the StreamWriter Class. You also
must insert the SaveFileDialog control into the form as it is used to save
the data into the storage unit like a hard drive. You must declare a new
SaveFileDialog object before you can use it. You can name it as
SaveFileDialog1 . We also insert another button and name it as BtnSave.
The Code is the same as the code for reading the file, you just change the
StreamReader to StreamWriter , and the method  from ReadToEnd to
Write.

The code

Imports System.IO

Public Class Form1

Private Sub BtnSave_Click(sender As Object, e As EventArgs) Handles


BtnOpen.Click

Dim FileWriter As StreamWriter

Dim results As DialogResult

Dim saveFileDialog1 As New SaveFileDialog()

results = SaveFileDialog1.ShowDialog

If results = DialogResult.OK Then

FileWriter = New StreamWriter(SaveFileDialog1.FileName, False)

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

   Sub Main(args As String())

        Console . WriteLine("Hello World!")


     End Sub
End Module
 
as shown in Figure 25.2 below:
 

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

The following program will perform a basic arithmetic operation.

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

Figure 25.4 The output in command prompt console

 
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

Sub Main(args As String())

Dim objWriter As New


System.IO.StreamWriter("C:\Users\Documents\vb2022\mytext.txt")

objWriter.WriteLine("Welcome to Visual Basic 2022")

objWriter.WriteLine("Please follow our  Visual Basic 2022 Chapters")

objWriter.WriteLine("The Chapters are interesting")

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

Sub Main(args As String())

Dim objReader As New

System.IO.StreamReader("C:\Users\Documents\vb2022\mytext.txt")

       Dim strLine As String

        'Reading  the first line

       strLine = objReader.ReadLine

        'Read until  the end of the file.

        Do While Not strLine Is Nothing

           'Write the line to the Console window.

           Console.WriteLine(strLine)

            'Read the next line.


           strLine = objReader.ReadLine

        Loop

     

    End Sub


 
The output

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

    Sub Main(args As String())

 
    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()

Dim FileWriter As StreamWriter

Dim results As DialogResult

Dim saveFileDialog1 As New SaveFileDialog()

     results = saveFileDialog1.ShowDialog

If results = DialogResult.OK Then

  FileWriter = New StreamWriter(saveFileDialog1.FileName, False)

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()

Dim FileReader As StreamReader

Dim results As DialogResult

Dim OpenFileDialog1 As New OpenFileDialog()

    results = OpenFileDialog1.ShowDialog

If results = DialogResult.OK Then

    FileReader = New StreamReader(OpenFileDialog1.FileName)

   TxtEditor.Text = FileReader.ReadToEnd()

    FileReader.Close()

End If

End Sub
For the New item, enter the following code:

Private Sub ToolStripNew_Click(sender As Object, e As EventArgs)


Handles ToolStripNew.Click

        TxtEditor.Text = ""

End Sub
 
For the Save item, enter the following code:

Private Sub ToolStripSave_Click(sender As Object, e As EventArgs)


Handles ToolStripSave.Click

        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:
 

Private Sub ExitToolStripMenuItem_Click(sender As Object, e As


EventArgs) Handles ExitToolStripMenuItem.Click

        TxtEditor.Dispose()

        Me.Close()

End Sub
 
For the Help button, enter the following code

Private Sub HelpToolStripMenuItem_Click(sender As Object, e As


EventArgs) Handles HelpToolStripMenuItem.Click

MsgBox("Type some text in the editor and click save to create a text file.
Click New to start a new text file. Click

Open to open a text file.")

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:

Private Sub ToolStripNew_Click(sender As Object, e As EventArgs)


Handles ToolStripNew.Click

        TxtEditor.Text = ""

End Sub
For the "Save" toolbar button, enter the following Code:

Private Sub ToolStripSave_Click(sender As Object, e As EventArgs)


Handles ToolStripSave.Click

        Me.WriteFile()

End Sub
 
For the "Open" toolbar button, enter the following Code:
 

Private Sub OpenToolStripMenuItem_Click(sender As Object, e As


EventArgs) Handles OpenToolStripMenuItem.Click

        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
 

You might also like