BASIC COMPUTER
CODING: VISUAL BASIC
BIBLIOTEX Digital Library
[Link]
BASIC COMPUTER CODING: VISUAL BASIC
BIBLIOTEX Digital Library
[Link]
email: info@[Link]
e-book Edition 2019
ISBN: 978-1-98462-690-5 (e-book)
This book contains information obtained from highly regarded resources. Reprinted
material sources are indicated. Copyright for individual articles remains with the
authors as indicated and published under Creative Commons License. A Wide variety
of references are listed. Reasonable efforts have been made to publish reliable data
and views articulated in the chapters are those of the individual contributors, and not
necessarily those of the editors or publishers. Editors or publishers are not responsible
for the accuracy of the information in the published chapters or consequences of their
use. The publisher assumes no responsibility for any damage or grievance to the persons
or property arising out of the use of any materials, instructions, methods or thoughts in
the book. The editors and the publisher have attempted to trace the copyright holders
of all material reproduced in this publication and apologize to copyright holders if
permission has not been obtained. If any copyright holder has not been acknowledged,
please write to us so we may rectify.
Notice: Registered trademark of products or corporate names are used only for
explanation and identification without intent of infringement.
© 2019 3G E-learning LLC
In Collaboration with 3G E-Learning LLC. Originally Published in printed book format by
3G E-Learning LLC with ISBN 978-1-98462-290-7
EDITORIAL BOARD
Aleksandar Mratinković is born on May 5, 1988. in Arandjelovac, Serbia. He has
graduated on Economic high school (2007), The College of Tourism in Belgrade
(2013), and also has a master degree of Psychology (Faculty of Philosophy,
University of Novi Sad). He has been engaged in different fields of psychology
(Developmental Psychology, Clinical Psychology, Educational Psychology and
Industrial Psychology) and has published several scientific works.
Dan Piestun (PhD) is currently a startup entrepreneur in Israel working on the
interface of Agriculture and Biomedical Sciences and was formerly president-
CEO of the National Institute of Agricultural Research (INIA) in Uruguay.
Dan is a widely published scientist who has received many honours during his
career including being a two-time recipient of the Amit Golda Meir Prize from
the Hebrew University of Jerusalem, his areas of expertise includes stem cell
molecular biology, plant and animal genetics and bioinformatics. Dan’s passion
for applied science and technological solutions did not stop him from pursuing a
deep connection to the farmer, his family and nature. Among some of his interest
and practices counts enjoying working as a beekeeper and onboard fishing.
Felecia Killings is the Founder and CEO of LiyahAmore Publishing, a publishing
company committed to providing technical and educational services and products
to Christian Authors. She operates as the Senior Editor and Writer, the Senior
Writing Coach, the Content Marketing Specialist, Editor-in-Chief to the company’s
quarterly magazine, the Executive and Host of an international virtual network,
and the Executive Director of the company’s online school for Authors. She is a
former high-school English instructor and professional development professor. She
possesses a Master of Arts degree in Education and a Bachelor’s degree in English
and African American studies.
Dr. Sandra El Hajj, Ph.D. in Health Sciences from Nova Southeastern University,
Florida, USA is a health professional specialized in Preventive and Global Health.
With her 12 years of education obtained from one of the most prominent universities
in Beirut, in addition to two leading universities in the State of Florida (USA), Dr.
Sandra made sure to incorporate interdisciplinary and multicultural approaches in
her work. Her long years of studies helped her create her own miniature world of
knowledge linking together the healthcare field with Medical Research, Statistics,
Food Technology, Environmental & Occupational Health, Preventive Health and
most noteworthy her precious last degree of Global Health. Till today, she is the
first and only doctor specialized in Global Health in the Middle East area.
Hazem Shawky Fouda has a PhD. in Agriculture Sciences, obtained his PhD.
From the Faculty of Agriculture, Alexandria University in 2008, He is working in
Cotton Arbitration & Testing General Organization (CATGO).
Fozia Parveen has a Dphil in Sustainable Water Engineering from the University of
Oxford. Prior to this she has received MS in Environmental Sciences from National
University of Science and Technology (NUST), Islamabad Pakistan and BS in
Environmental Sciences from Fatima Jinnah Women University (FJWU), Rawalpindi.
Igor Krunic 2003-2007 in the School of Economics. After graduating in 2007,
he went on to study at The College of Tourism, at the University of Belgrade
where he got his bachelor degree in 2010. He was active as a third-year student
representative in the student [Link] he went on the Faculty of science, at
the University of Novi Sad where he successfully defended his master’s thesis in
2013. The crown of his study was the work titled Opportunities for development
of cultural tourism in Cacak“. Later on, he became part of a multinational
company where he got promoted to a deputy director of logistic. Nowadays
he is a consultant and writer of academic subjects in the field of tourism.
Dr. Jovan Pehcevski obtained his PhD in Computer Science from RMIT University
in Melbourne, Australia in 2007. His research interests include big data, business
intelligence and predictive analytics, data and information science, information
retrieval, XML, web services and service-oriented architectures, and relational and
NoSQL database systems. He has published over 30 journal and conference papers
and he also serves as a journal and conference reviewer. He is currently working as a
Dean and Associate Professor at European University in Skopje, Macedonia.
Dr. Tanjina Nur finished her PhD in Civil and Environmental Engineering in 2014
from University of Technology Sydney (UTS). Now she is working as Post-Doctoral
Researcher in the Centre for Technology in Water and Wastewater (CTWW) and
published about eight International journal papers with 80 citations. Her research
interest is wastewater treatment technology using adsorption process.
Stephen obtained his PhD from the University of North Carolina at Charlotte in
2013 where his graduate research focused on cancer immunology and the tumor
microenvironment. He received postdoctoral training in regenerative and translational
medicine, specifically gastrointestinal tissue engineering, at the Wake Forest Institute
of Regenerative Medicine. Currently, Stephen is an instructor for anatomy and
physiology and biology at Forsyth Technical Community College.
Michelle holds a Masters of Business Administration from the University of Phoenix,
with a concentration in Human Resources Management. She is a professional author
and has had numerous articles published in the Henry County Times and has written
and revised several employee handbooks for various YMCA organizations throughout
the United States.
Table of Contents
Preface xi
Chapter 1 Introduction to Visual Basic 1
Learning Objectives ............................................................................. 1
Introduction.......................................................................................... 2
1.1 Meaning of Visual Basic ............................................................... 2
1.1.1 History of Visual Basic ........................................................3
1.1.2 The Importance of Visual Basic Programming
Language ..........................................................................4
1.1.3 Advantages and Disadvantages of Visual Basic ..............6
1.2 Visual Basic Environment ............................................................ 7
1.3 Building VB Applications ............................................................. 9
1.3.1 Creating Your First Application .........................................9
1.3.2 Steps in Building a Visual Basic Application .................13
1.3.3 Structure of a Visual Basic Application ...........................15
1.3.4 Drawing the User Interface and Setting Properties.......16
1.3.5 Saving Projects ....................................................................20
Summary............................................................................................. 24
Knowledge Check ............................................................................. 25
Review Questions .............................................................................. 26
References ........................................................................................... 27
Chapter 2 Data Types, Constants and Variables 29
Learning Objectives ........................................................................... 29
Introduction........................................................................................ 30
2.1 Data Types .................................................................................... 31
2.1.1 Memory Consumption ......................................................33
2.1.2 Composite Data Types .......................................................33
2.1.3 Boolean Data Type .............................................................34
2.1.4 Byte Data Type ....................................................................35
2.1.5 Char Data Type ..................................................................37
2.1.6 Decimal Data Type .............................................................39
2.1.7 Double Data Type...............................................................41
2.1.8 Integer data type.................................................................42
2.2 Variables In Visual Basic ............................................................. 44
2.2.1 Declaring Variables ...........................................................45
2.2.2 Comparing Implicit and Explicit Variable
Performance ...................................................................45
2.2.3 Providing Names for the Variables..................................46
2.2.4 Static Variables ....................................................................47
2.2.5 Forcing Explicit Declaration .............................................50
2.2.6 Using a Naming Convention ............................................51
2.2.7 Understanding Variable Scope and Lifetime .................51
2.3 Constants in Visual Basic............................................................ 53
2.3.1 User-Defined Constants ...................................................54
2.3.2 Declare a Constant .............................................................55
2.3.3 Constant and Literal Data Types .....................................57
Case Study .......................................................................................... 60
Summary............................................................................................. 64
Knowledge Check ............................................................................. 66
Review Questions .............................................................................. 67
References ........................................................................................... 68
Chapter 3 Control Statements and Tools 69
Learning Objectives ........................................................................... 69
Introduction........................................................................................ 70
3.1 Statement ...................................................................................... 70
3.1.1 Declaration Statements ......................................................70
3.1.2 Executable Statements .......................................................73
3.2 Decision Making Structures ....................................................... 74
3.2.1 If...Then Statement .............................................................76
3.2.2 If...Then...Else Statement ...................................................77
3.2.3 The If...Else If...Else Statement..........................................79
3.2.4 Nested If Statements ..........................................................81
3.2.5 Select Case Statement ........................................................82
3.2.6 Nested Select Case Statement ...........................................84
3.3 Visual Basic Control .................................................................... 85
3.3.1 Control Properties ..............................................................86
3.3.2 Control Methods.................................................................86
3.3.3 Control Events ....................................................................87
3.4. Visual Basic Control Tools ......................................................... 88
3.4.1 Intrinsic Controls ................................................................88
3.4.2 ActiveX Controls.................................................................89
3.4.3 Insertable Objects ...............................................................89
Role Model.......................................................................................... 90
Summary............................................................................................. 94
Knowledge Check ............................................................................. 96
Review Questions .............................................................................. 97
References ........................................................................................... 98
Chapter 4 Menu Bar and Dialog Boxes 99
Learning Objectives ........................................................................... 99
4.1 Menu Bar..................................................................................... 100
4.1.1 Adding Menu Bar Using Visual Basic’s Application
Wizard ..........................................................................100
4.1.2 Adding Menu Bar Using Menu Editor..........................106
4.2 Dialog Boxes ............................................................................... 109
4.2.1 Using a Parent Control ....................................................111
4.2.2 Dialog Box Creation .........................................................112
4.2.3 Characteristics of Dialog Boxes ......................................113
4.2.4 Modal and Modeless Dialog Boxes ...............................119
Summary .......................................................................................... 123
Knowledge Check ........................................................................... 124
Review Questions ............................................................................ 125
References ......................................................................................... 126
Chapter 5 Executing the Debugging 127
Learning Objectives ......................................................................... 127
Introduction...................................................................................... 128
5.1 Error Types ................................................................................. 128
5.1.1 Syntax Errors .....................................................................128
5.1.2 Run-time Errors ................................................................129
5.1.3 Logic Errors .......................................................................130
5.2 Debugging Visual Basic Programs .......................................... 130
5.3 Debugging Tools ........................................................................ 133
5.4 Error Handling........................................................................... 139
5.4.1 In Case Of Error, Jump To Label ....................................142
5.4.2 In Case Of Error, Jump To Line # ...................................145
5.4.3 Resume ..............................................................................146
Summary........................................................................................... 151
Knowledge Check ........................................................................... 152
Review Questions ............................................................................ 153
References ......................................................................................... 154
Chapter 6 Procedures and Arrays 155
Learning Objectives ......................................................................... 155
Introduction...................................................................................... 156
6.1 Basics of Procedures .................................................................. 156
6.1.1 Sub Procedures .................................................................157
6.1.2 Event Procedures..............................................................161
6.1.3 General Procedures ..........................................................161
6.1.4 Function Procedures ........................................................163
6.1.5 Property Procedures ........................................................166
6.2 Arrays in Visual Basic ............................................................... 171
6.2.1 Dimension of an Array ....................................................173
6.2.2 Dynamic Array .................................................................177
6.2.3 Retrieving the Contents of an Array..............................181
6.2.4 Multidimensional Arrays ................................................182
Summary........................................................................................... 186
Knowledge Check ........................................................................... 188
Review Questions ............................................................................ 189
References ......................................................................................... 190
Chapter 7 Data Access 191
Learning Objectives ......................................................................... 191
Introduction...................................................................................... 192
7.1 [Link] Object Model ............................................................ 192
7.1.1 Data Provider ....................................................................193
7.1.2 DataSet ...............................................................................194
7.2 Connecting to a Database ......................................................... 196
7.3 Creating Table, Columns and Rows ....................................... 205
7.4 Selecting the Data Source ......................................................... 208
7.4.1 Linking Data Sources to an Application .......................209
7.4.2 Adding SQL Statements to a Visual Basic
Application...................................................................211
Role Model........................................................................................ 213
Summary........................................................................................... 216
Knowledge Check ........................................................................... 217
Review Questions ............................................................................ 218
References ......................................................................................... 219
Index 221
Preface
Visual Basic is one of the most widely used programming languages
in the world. The major reason for its popularity is that it allows
programmers to create Windows applications quickly and easily.
It was indeed the first visual development tool from Microsoft.
Visual Basic was derived from BASIC and enables rapid application
development of graphical user interface applications, access to
databases using DAO, RDO, or ADO, and creation of ActiveX
controls and objects. One of the most important things to be
considered with regard to programming in Visual basic is that
the structure of VB is designed in a way that allows programmers
to create executable code – Exe files. It enables programmers to
develop programs that can be used as front end to databases.
Besides, it’s with the help of visual basic tools; one can change
the abstract ideas into programs or into the whole software while
it allows revising and modifying the programs fittingly.
Organization of the Book
This book is systematically divided into seven chapters. This book
focuses on using the latest and most powerful tools from the
Microsoft arsenal within your Visual Basic solutions. The book
introduces the Visual Basic Integrated Development Environment
(IDE) and its wealth of development tools. Students will learn to
build effective user interfaces with Visual Basic controls, forms,
and other GUI components. Students will learn the use of the
debugging and testing tools available in Visual Studio. Database
access is introduced, using Visual Basic’s ADO Control and data-
aware components like the Data Grid and Data Environment
Designer.
Chapter 1 presents an introduction to Visual Basic. It focuses on
meaning of visual basic, visual basic environment, building VB
applications.
Chapter 2 focuses on data types, constants and variables. The data
type defines which operations can safely be performed to create,
transform and use the variable in another computation. Useful
variables and constants in visual basic are also explained.
Chapter 3 discusses the control statement and tools necessary to
control the sequence of operations in a program. This can be done
by using control statements. An executable statement performs an
action. Statements calling a procedure, branching to another place
in the code, looping through several statements, or evaluating an
expression are executable statements.
Chapter 4 focuses on menu bar and dialog boxes. It allows you
to create a robust program. In general, error handling should be
part of your overall program plan, so that when you have an
error-free script, nothing is going to bring it to a screeching halt.
Chapter 5 focuses on debugging visual basic programs, debugging
tools, and error handling. Errors, bugs, and therefore debugging
are a part of life for a programmer.
Chapter 6 is intended to focus on the basics of procedures. The
chapter also focuses on the concept of arrays in visual basic.
The fundamental role of a procedure is to offer a single point
of reference for some small goal or task that the developer or
programmer can trigger by invoking the procedure itself.
Chapter 7 focuses on Data Access feature of Visual Basic that allows
you to access and manipulate any database from Visual Basic.
CHAPTER 1
INTRODUCTION TO
VISUAL BASIC
“I know blind programmers who work in C and Visual Basic in addition to
mainframe languages, because as long as they can get at a text file, they can do
programming. But if the graphical tool kit you are using requires you to drag and
drop items on the screen, you can’t do it.”
―Curtis Chong,
Learning Objectives
After studying this chapter, you will be able to:
■ Overview of meaning of visual basic
■ Discuss the visual basic environment
■ Describe the building VB applications
Basic Computer Coding: Visual Basic
INTRODUCTION
Visual Basic is a high level programming
language evolved from the earlier DOS
version called BASIC. BASIC means Beginners’
Allpurpose Symbolic Instruction Code. It is a
fairly easy programming language to learn. The
codes look a bit like English Language.
VISUAL BASIC is a VISUAL and events driven
Programming Language. These are the main
divergence from the old BASIC. In BASIC,
programming is done in a text-only environment
and the program is executed sequentially. In
VISUAL BASIC, programming is done in a
graphical environment. Because users may click
on a certain object randomly, so each object
has to be programmed indepently to be able to
response to those actions (events).Therefore, a
VISUAL BASIC Program is made up of many
subprograms, each has its own program codes,
and each can be excecuted indepently and at
The graphical user the same time each can be linked together in
interface (GUI), is a one way or another.
type of user interface
that allows users to
interact with electronic
devices through 1.1 MEANING OF VISUAL BASIC
graphical icons and
visual indicators such Visual Basic is a programming language and
as secondary notation, development environment created by Microsoft.
instead of text-based It is an extension of the BASIC programming
user interfaces, typed
language that combines BASIC functions and
command labels or text
navigation. commands with visual controls. Visual Basic
2
Introduction to Visual Basic
provides a graphical user interface GUI that
allows the developer to drag and drop objects
into the program as well as manually write
program code.
Visual Basic, also referred to as “VB,” is
designed to make software development easy
and efficient, while still being powerful enough
to create advanced programs. For example, the
Visual Basic language is designed to be “human Remember
readable,” which means the source code can be
understood without requiring lots of comments. Visual Basic
The Visual Basic program also includes features is available as
like “IntelliSense” and “Code Snippets,” which a streamlined
automatically generate code for visual objects application that
added by the programmer. Another feature, is used primarily
called “AutoCorrect,” can debug the code while by beginning
the program is running. developers and
for educational
Programs created with Visual Basic can be purposes.
designed to run on Windows, on the Web,
within Office applications, or on mobile devices.
Visual Studio, the most comprehensive VB
development environment, or IDE, can be used
to create programs for all these mediums. Visual
Studio .NET provides development tools to
create programs based on the .NET framework,
such as [Link] applications, which are often
deployed on the Web.
1.1.1 History of Visual Basic
The first version of visual basic, VB 1.0, was
announced in the year 1991. The creation of user
interface through a drag and drop design was
inspired a beta generator that was developed
by Alan Cooper at Tripod, which was Cooper’s
company.
Microsoft entered into a contract with Cooper
and his partners to create Tripod into a system
3
Basic Computer Coding: Visual Basic
that is programmable for Windows 3.0. This system was developed
under the code name of Ruby, which has no relationship with the
Ruby Programming Language. Tripod did not have any programming
language at all. Microsoft then decided to use Ruby in combination
with basic language to develop visual basic.
The interface of Ruby contributed the “visual” component of the
Visual Basic programming language. This was then amalgamated
with the Embedded BASIC engine that was developed for the ceased
“Omega” database system of Microsoft.
The introduction of version 5.0, in the month of February in 1997,
Microsoft exclusively released a visual basic that was compatible
with 32-bit Microsoft Windows versions. The programmers who had
a preference for writing programs in 16-bit could do it in versions
between 4.0 and 5.0. In addition to that the programs written Visual
Basic 5.0 can be converted to Version 4.0 programs in an easy
manner. The version 5.0 also has the ability of compilation with
native execution code of Windows, and introduction of custom
user controls.
The introduction of Visual Basic 6.0 was made in the middle of 1998.
This version also came with a number of enhancements, including
the striking ability of creating web based applications. The extended
support for Visual Basic 6.0 was ceased in the month of March in
2008. The basic parts of development environment of Visual Basic
6, however, still run in all the 32-bit Microsoft windows, including
Windows 8.1.
After the cessation of mainstream and extended support for Visual
Basic 6.0 caused a number of programs to show concern. The
community members then created a lobby of users and a petition
was signed by them. The basic aim of this petition was to ensure
that the product remains alive. However, the petition did not attain
its aim effectively.
1.1.2 The Importance of Visual Basic Programming
Language
Visual Basic is regarded as the third generation event-driven
programming language. It was released in 1987. Being the first
4
Introduction to Visual Basic
visual development tool from Microsoft, it is considered as one of
the most powerful programming languages. As compared to other
computer programming languages, such as, C, C++, it is easy to
learn and understand, provided that one has determination and
dedication to do so.
Visual basic programming language allows programmers to create
software interface and codes in an easy to use graphical environment.
VB is the combination of different components that are used on
forms having specific attributes and actions with the help of those
components. On the one hand it allows programmers to develop
widows based applications rapidly; on the other hand, it helps greatly
in accessing data bases, using ADO while letting the programmers
use ActiveX controls and various objects. While it is intended more
to develop applications, it is also useful for games development for
particular or limited purposes, unlike C++ that is more suitable for
developing games.
As compared to other languages, Visual basic may be slower though,
yet it is flexible and it can be rightly said that things that are
difficult in other languages are comparatively easier in visual basic
programming language. It may also be said that, since it is one of
the most popular programming languages, lots of related books
and material and other resources are available and can be accessed
for developing programming skills at visual basic programming
language conveniently.
One of the most important things to be considered with regard to
programming in Visual basic is that the structure of VB is designed
in a way that allows programmers to create executable code – Exe
files. It enables programmers to develop programs that can be used
as front end to databases. Besides, it’s with the help of visual basic
tools, one can change the abstract ideas into programs or into the
whole software while it allows revising and modifying the programs
fittingly.
5
Basic Computer Coding: Visual Basic
1.1.3 Advantages and Disadvantages of Visual Basic
Advantages
■ The structure of the Basic programming language is very
simple, particularly as to the executable code.
■ VB is not only a language but primarily an integrated,
interactive development environment (“IDE“).
■ The VB-IDE has been highly optimized to support rapid
application development (“RAD”). It is particularly easy to
develop graphical user interfaces and to connect them to
handler functions provided by the application.
■ The graphical user interface of the VB-IDE provides
intuitively appealing views for the management of the
program structure in the large and the various types of
entities (classes, modules, procedures, forms, …).
■ VB provides a comprehensive interactive and context-
sensitive online help system.
■ When editing program texts the “IntelliSense” technology
informs you in a little popup window about the types of
constructs that may be entered at the current cursor location.
■ VB is a component integration language which is attuned
to Microsoft’s Component Object Model (“COM”).
■ COM components can be written in different languages
and then inegrated using VB.
■ Interfaces of COM components can be easily called remotely
via Distributed COM (“DCOM”), which makes it easy to
construct distributed applications.
■ COM components can be embedded in / linked to your
application’s user interface and also in/to stored documents
(Object Linking and Embedding “OLE”, “Compound
Documents”).
■ There is a wealth of readily available COM components
for many different purposes.
6
Introduction to Visual Basic
■ Visual Basic is built around the .NET
environment used by all Microsoft
Visual languages, so there is very little
that can’t be done in Visual Basic that
can be done in other languages (such
as C#).
Visual Basic 1.0 for
Disadvantages DOS was released in
September 1992. The
■ Visual basic is a proprietary
language itself was
programming language written not quite compatible
by Microsoft, so programs written with Visual Basic
in Visual basic cannot, easily, be for Windows, as
transferred to other operating systems. it was actually
■ There are some, fairly minor the next version
of Microsoft’s
disadvantages compared with C. C
DOS-based BASIC
has better declaration of arrays –
compilers, Microsoft
its possible to initialize an array of QuickBASIC
structures in C at declaration time; compiler and the
this is impossible in VB. BASIC Professional
Development
System 7.1. The
1.2 VISUAL BASIC interface was
barely graphical,
ENVIRONMENT using extended
ASCII characters
On start up, Visual Basic 6.0 will display the to simulate the
following dialog box as shown in figure 1. appearance of a
You can choose to start a new project, open GUI.
an existing project or select a list of recently
opened programs. A project is a collection of
files that make up your application. There are
various types of applications we could create,
however, we shall concentrate on creating
Standard EXE programs (EXE means executable
program). Now, click on the Standard EXE
icon to go into the actual VB programming
environment.
7
Basic Computer Coding: Visual Basic
Figure 1: The Visual Basic Start-up Dialog Box.
In figure 2, the Visual Basic Environment consists of the
■ The Blank Form window which you can design your
application’s interface.
■ The Project window displays the files that are created in
your application.
■ The Properties window which displays the properties
of various controls and objects that are created in your
applications.
It also includes a Toolbox that consists of all the controls essential
for developing a VB Application. Controls are tools such as boxes,
buttons, labels and other objects draw on a form to get input or
display output. They also add visual appeal.
Figure 2: The Visual Basic Environment.
8
Introduction to Visual Basic
1.3 BUILDING VB APPLICATIONS
Visual Basic for Applications is a programming language that is
similar to Visual Basic, only it is embedded in an individual Microsoft
application such as Excel or Access. Using VBA you can create
macros or small programs that perform tasks within the Microsoft
application.
1.3.1 Creating Your First Application
First of all, launch Microsoft Visual Basic 6 compiler that you have
installed earlier. In the New Project Dialog, choose Standard EXE
to enter Visual Basic 6 integrated development environment. In the
VB6 IDE, a default form with the name Form1 will be presented
to you. Next, double click on Form1 to bring up the source code
window for Form1, as shown in Figure 3. The top of the source
code window consists of a list of objects and their associated events
or procedures. In the source code window, the object displayed
isForm1 and the associated procedure is Load.
Figure 3: The VB6 Source Code Window.
9
Basic Computer Coding: Visual Basic
When you click on the object box, the drop-down list will display a
list of objects you have inserted into your form, as shown in figure
4. Here, you can see a form with the name Form1, a command
button with the name Command1, a Label with the name Label1
and a Picture Box with the name Picture1.
Figure 4: List of Objects.
Similarly, when you click on the procedure box, a list of procedures
associated with the object will be displayed, as shown in Figure
5. Some of the procedures associated with the object Form1 are
Activate, Click, DblClick (which means Double-Click), DragDrop,
keyPress and more. Each object has its own set of procedures. You
can always select an object and write codes for any of its procedure
in order to perform certain tasks.
Figure 5: List of Procedures.
10
Introduction to Visual Basic
You do not have to worry about the beginning and the end statements
(i.e. Private Sub Form_Load.......End Sub.); Just key in the lines in
between the above two statements exactly as are shown here. When
you press F5 to run the program, you will be surprised that nothing
showed up .In order to display the output of the program, you have
to add the [Link] statement like in Example 1 or you can
just use Form_Activate ( ) event procedure as shown in example 2.
The command Print does not mean printing using a printer but it
means displaying the output on the computer screen. Now, press
F5 or click on the run button to run the program and you will get
the output as shown in Figure 6.
Example 1
Private Sub Form_Load ( )
[Link]
Print “Welcome to Visual Basic tutorial”
End Sub
Example 2
Private Sub Form_Activate ( )
Print 20 + 10
Print 20 - 10
Print 20 * 10
Print 20 / 10
End Sub
11
Basic Computer Coding: Visual Basic
Figure 6: The output of Example 1.
Figure 6: The output of Example 2.
This snippet makes a counter that moves up 1 every
second (a label and a timer control need to be added
to the form for this to work) until the form is closed
or an integer overflow occurs:
Option Explicit
Dim Count As Integer
Private Sub Form_Load()
Count = 0
[Link] = 1000 ‘ units of milliseconds
12
Introduction to Visual Basic
End Sub
Private Sub Timer1_Timer()
Count = Count + 1
[Link] = Count
End Sub
1.3.2 Steps in Building a Visual Basic Application
Step 1: Design the interface by adding controls to the form and set
their properties
Step 2: Write code for the event procedures
Example 3 Changing Background and Foreground Color
at Random
In this example, we want to show you how to write code to change
the background and the foreground color randomly. We will place
two command buttons and a label on the form. One of the command
buttons will be used to change the background color while the other
one will be used to change the foreground color. The Label is for
displaying the foreground color. There are two events here, change
background color and change foreground color. Therefore, we need
to write code for the two event procedures.
To make the program more interesting, we will use the Rnd()
function, the Int() function and the RGB codes to change the color
randomly. The Rnd() function creates a random number between 0
and 1 and the RGB code uses a combination of three integers to form
a certain color. 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(0.2)=0, Int(2.4)=2, Int(4.8)=4. Therefore, Int(Rnd()*256) returns the
smallest integer 0 and the biggest integer 255. The format of RGB
code is RGB(a,b,c), where a, b, c range from 0 to 255. For example,
RGB(255,0,0) is red, RGB(255,255,255) is white and (0,0,0) is black.
13
Basic Computer Coding: Visual Basic
Now, rename the controls as follows:
■ Form1-MyForm
■ Label1-LblMessage
■ Command1-cmd_bgColor
■ Command2-cmd_fgColor
Next, change the caption of the Label to “Please Change My Color”.
In addition, change the caption of Command1 button to “Change
Background Color” and change the caption of Command2 button
to “Change Foreground Color”
Now, enter the following code
Private Sub cmd_bgColor_Click()
Dim r, g, b As Integer
r = Int(Rnd() * 256)
g = Int(Rnd() * 256)
b = Int(Rnd() * 256)
[Link] = RGB(r, g, b)
End Sub
Private Sub Cmd_fgColor_Click()
Dim r, g, b As Integer
r = Int(Rnd() * 256)
g = Int(Rnd() * 256)
b = Int(Rnd() * 256)
Lbl_Msg.ForeColor = RGB(r, g, b)
End Sub
When you run the program, each time you press on the ‘Change
Background Color’ button, you will see different background color.
Similarly, each time you press on the ‘Change Foreground Color’,
14
Introduction to Visual Basic
you will see the message on the Label changes
color. The output is shown in Figure 7.
Figure 7:
1.3.3 Structure of a Visual Basic
Application
Application (Project) is made up of: The user interface in the
■ Forms - Windows that you create for industrial design field
of human–computer
user interface interaction, is the space
■ Controls - Graphical features drawn where interactions
on forms to allow user interaction (text between humans and
machines occur.
boxes, labels, scroll bars, command
buttons, etc.) (Forms and Controls are
objects.)
■ Properties - Every characteristic of
a form or control is specified by a
property. Example properties include
names, captions, size, color, position,
and contents. Visual Basic applies
default properties. You can change
properties at design time or run time.
■ Methods - Built-in procedure that can
be invoked to impart some action to
a particular object.
15
Basic Computer Coding: Visual Basic
■ Event Procedures - Code related to
some object. This is the code that is
executed when a certain event occurs.
■ General Procedures - Code not related
to objects. This code must be invoked
by the application.
■ Modules - Collection of general
procedures, variable declarations,
and constant definitions used by
application.
1.3.4 Drawing the User Interface
and Setting Properties
Visual Basic operates in three modes.
■ Design mode - used to build application
■ Run mode - used to run the application
■ Break mode - application halted and
debugger is available
Six windows appear when you start Visual
Basic.
■ The Main Window consists of the title
bar, menu bar, and toolbar. The title
bar indicates the project name, the
current Visual Basic operating mode,
A menu bar is a and the current form. The menu bar
graphical control
element which contains has drop-down menus from which
drop-down menus. you control the operation of the Visual
Basic environment. The toolbar has
buttons that provide shortcuts to
some of the menu options. The main
window also shows the location of
the current form relative to the upper
left corner of the screen (measured in
twips) and the width and length of
the current form.
16
Introduction to Visual Basic
■ The Form Window is central to developing Visual Basic
applications. It is where you draw your application.
■ The Toolbox is the selection menu for controls used in
your application.
17
Basic Computer Coding: Visual Basic
■ The Properties Window is used to establish initial property
values for objects. The drop-down box at the top of the
window lists all objects in the current form. Two views are
available: Alphabetic and Categorized. Under this box are
the available properties for the currently selected object.
■ The Form Layout Window shows where (upon program
execution) your form will be displayed relative to your
monitor’s screen:
18
Introduction to Visual Basic
■ The Project Window displays a list of all forms and modules
making up your application. You can also obtain a view of
the Form or Code windows (window containing the actual
Basic coding) from the Project window.
■ As mentioned, the user interface is ‘drawn’ in the form
window. There are two ways to place controls on a form:
• Double-click the tool in the toolbox and it is created
with a default size on the form. You can then move
it or resize it.
• Click the tool in the toolbox, then move the mouse
pointer to the form window. The cursor changes to a
crosshair. Place the crosshair at the upper left corner of
where you want the control to be, press the left mouse
button and hold it down while dragging the cursor
toward the lower right corner. When you release the
mouse button, the control is drawn.
■ To move a control you have drawn, click the object in the
form window and drag it to the new location. Release the
mouse button.
■ To resize a control, click the object so that it is select and
sizing handles appear. Use these handles to resize the object.
19
Basic Computer Coding: Visual Basic
1.3.5 Saving Projects
Even the simplest Visual Basic project comprises
multiple files which must each be saved on
your system to store the project.
Follow these steps to save the current New
Project to disk:
A toolbar is a graphical
control element on ■ Click the Save All button on the Tool
which on-screen Bar, or click File, Save All on the Menu
buttons, icons, menus,
Bar, or press the Ctr+Shift+S keys, to
or other input or output
elements are placed. open the Save Project dialog
20
Introduction to Visual Basic
■ In the Save Project dialog you can optionally change the
Project name if it is part of a larger Solution – for simple
applications just leave the Project name the same as the
Solution Name
■ Choose a Location at which to save your project, or accept
the suggested Location
■ Ensure that the “Create directory for solution” box is
checked, then click the Save button to save all your project
files
21
Basic Computer Coding: Visual Basic
ROLE MODEL
Alan Cooper: Father of
Visual Basic
Born in San Francisco in 1952 and
raised in Marin County, California,
Alan Cooper has always taken the path less traveled. A rebellious
teenager, he dropped out of high school, but eventually made his
way to the College of Marin to pursue his interest in architecture.
After an exploratory course in programming, it became clear that
his future was in architecture—software architecture. After getting
his associate degree and a COBOL programming job, he saw an
advertisement for one of the first personal computers and conceived
an idea for a new business venture.
In 1976, Cooper founded Structured Systems Group (SSG), a company
Fire in the Valley authors Paul Freiberger and Michael Swaine said
created “the first serious business software for microcomputers.” In
four years, Cooper wrote and shipped a dozen application programs.
SSG became the archetype for many software startups in the early
days of the personal computer revolution.
During the 1980s, after leaving SSG, Cooper invented, wrote, and
sold three major software packages to prominent publishers. One of
those was the visual programming front-end code named “Ruby,” for
what became Visual BASIC. Bill Gates purchased it from Cooper in
1988, noting that it would have significant impact across Microsoft’s
entire product line. Visual BASIC was deemed both a commercial
and critical success, earning Cooper the moniker “Father of Visual
BASIC.” Visual BASIC has influenced integrated development
languages ever since.
In 1990 Cooper became fascinated with the challenge of making
software products that were easy to use and understand. He and his
wife, Susan, founded Cooper Interaction Design (now “Cooper”) to
assist in what Cooper calls “interaction design.” In the design field,
Cooper’s software development background was unique and, over
the next few years, he invented many of the tools and techniques
now standard in the user experience industry, including personas
22
Introduction to Visual Basic
and scenarios, pair design, and possibility thinking. He calls this
ensemble “goal-directed design.” In the 1990s, Cooper published
two books on interaction design, About Face and The Inmates are
Running the Asylum, which have become required reading for
practitioners.
While Alan still leads Cooper as a director, he and his wife have
moved to a former dairy ranch in Petaluma, California. Cooper
has become a vocal advocate for sustainable and regenerative
agriculture, not coincidentally pointing out the parallels between
ethics in agribusiness and ethics in the software business.
In 1995 Bill Gates awarded Cooper the first of only seven Windows
Pioneer awards in recognition of Cooper’s contributions to the success of
the Windows operating system. In 1998 the Silicon Valley Forum awarded
Cooper one of its first Visionary Awards for his ongoing contributions.
23
Basic Computer Coding: Visual Basic
SUMMARY
■ Visual Basic is a high level programming language evolved
from the earlier DOS version called BASIC. BASIC means
Beginners’ Allpurpose Symbolic Instruction Code. It is a
fairly easy programming language to learn. The codes look
a bit like English Language.
■ Visual Basic is a programming language and development
environment created by Microsoft. It is an extension of
the BASIC programming language that combines BASIC
functions and commands with visual controls. Visual Basic
provides a graphical user interface GUI that allows the
developer to drag and drop objects into the program as
well as manually write program code.
■ The Properties window which displays the properties
of various controls and objects that are created in your
applications.
■ Visual Basic for Applications is a programming language
that is similar to Visual Basic, only it is embedded in an
individual Microsoft application such as Excel or Access.
Using VBA you can create macros or small programs that
perform tasks within the Microsoft application.
■ The Main Window consists of the title bar, menu bar, and
toolbar. The title bar indicates the project name, the current
Visual Basic operating mode, and the current form.
24
Introduction to Visual Basic
KNOWLEDGE CHECK
1. Visual Basic is a tool that allows you to develop application
in…………
a. Real time
b. Graphical User Interface
c. Menu Driven
d. None Of These
2. Microsoft’s Visual Basic language were launched early in
a. 1960s
b. 1970s
c. 1980s
d. 1990s
3. Which windows displays a list of all forms and modules
making up your application
a. Project window
b. Properties window
c. Form layout window
d. All of the above
4. When the user clicks a button, _________ is triggered.
a. an event
b. a method
c. a setting
d. a property
5. Which of the following windows is the central to the
development of Visual Basic applications
a. Project window
b. Form window
c. Properties window
d. All of the above
25
Basic Computer Coding: Visual Basic
REVIEW QUESTIONS
1. What is visual basic? Why are importance of visual
basic programming language?
2. What is visual basic environment?
3. Describe the structure of a visual basic application.
4. How to creating your first application?
5. Discuss the saving projects in VB.
Check Your Result
1. (b) 2. (d) 3. (a) 4. (a) 5. (b)
26
Introduction to Visual Basic
REFERENCES
1. [Link]
vb
2. [Link]
Visual-Basic
3. [Link]
pdf
4. [Link]
5. [Link]
site-3424549
6. [Link]
computers-and-electrical-engineering/computers-and-
computing/visual-basic
7. [Link]
8. [Link]
Development/Manuals/EN/vbNet_programming.pdf
9. [Link]
Visual_basic_6.[Link]
10. [Link]
visual-basic-environment-3
11. [Link]
[Link]
12. [Link]
13. [Link]
US/10ca93b4-4f96-4f5c-a30b-939b71be441f/faq-item-how-
do-i-save-an-existing-project-to-different-local-location-
via-ide-menu?forum=vbgeneral
14. [Link]
15. [Link]
files/[Link]
16. [Link]
create-a-windows-forms-application-project?view=vs-2017
27
Basic Computer Coding: Visual Basic
17. [Link]
advantages-and-disadvantages-of-visual-basic/
18. [Link]
programming-language-fareed
28
CHAPTER 2
DATA TYPES,
CONSTANTS AND
VARIABLES
“Programming today is a race between software engineers striving to build bigger
and better idiot-proof programs, and the Universe trying to produce bigger and
better idiots. So far, the Universe is winning.”
―Rick Cook
Learning Objectives
After studying this chapter, you will be able to:
■ Learn about the data types
■ Explain the useful variable in visual basic
■ Know about the constants in visual basic
Basic Computer Coding: Visual Basic
INTRODUCTION
A data type, in programming, is a classification that specifies which
type of value a variable has and what type of mathematical, relational
or logical operations can be applied to it without causing an error.
A string, for example, is a data type that is used to classify text and
an integer is a data type used to classify whole numbers.
The data type defines which operations can safely be performed
to create, transform and use the variable in another computation.
When a program language requires a variable to only be used in
ways that respect its data type, that language is said to be strongly
typed. This prevents errors, because while it is logical to ask the
computer to multiply a float by an integer (1.5 x 5), it is illogical
to ask the computer to multiply a float by a string (1.5 x Alice).
When a programming language allows a variable of one data type
to be used as if it were a value of another data type, the language
is said to be weakly typed.
Technically, the concept of a strongly typed or weakly typed
programming language is a fallacy. In every programming language,
all values of a variable have a static type -- but the type might be
one whose values are classified into one or more classes. And while
some classes specify how the data type’s value will be compiled or
interpreted, there are other classes whose values are not marked
with their class until run-time. The extent to which a programming
language discourages or prevents type error is known as type safety.
A variable is a named memory location which temporarily stores
data that can change while the program is running. A variable is
something that may change in value. A variable might be the number
of words on different pages of this booklet, the air temperature
each day, or the exam marks given to a class of school children. A
variable could be likened to a storage box whose contents may often
change. The box, or variable must be given a name to distinguish
it from others.
A constant is a value that never changes. The other type of values
that programs use is variables, symbols that can represent different
values throughout the course of a program.
30
Data Types, Constants and Variables
A constant can be
• a number, like 25 or 3.6
• a character, like a or $
• a character string, like “this is a string”
Constants are also used in spreadsheet applications to place non-
changing values in cells. In contrast, a spreadsheet formula can
produce a different value each time the spreadsheet is opened or
changed.
2.1 DATA TYPES
All programs are composed of two items: Data and Operations on
that Data. Because, at their heart, computers are simple devices, they
can only represent very simple pieces of information. All complex
information must be built up from these basic Data Types. The data
types can roughly be described as: numbers, Booleans, characters,
arrays, and structures.
Data types refer to an extensive system used for declaring variables
or functions of different types. The type of a variable determines
how much space it occupies in storage and how the bit pattern
stored is interpreted.
The following table shows the Visual Basic data types, their supporting
common language runtime types, their nominal storage allocation,
and their value ranges.
Visual Basic type Common Nominal Value range
language storage
runtime type allocation
structure
Boolean Boolean Depends on True or False
implementing
platform
Byte Byte 1 byte 0 through 255 (unsigned)
Char(single Char 2 bytes 0 through 65535 (unsigned)
character)
31
Basic Computer Coding: Visual Basic
Date DateTime 8 bytes 0:00:00 (midnight) on January
1, 0001 through 11:59:59 PM on
December 31, 9999
Decimal Decimal 16 bytes 0 through +/-79,228, 162,514,264,
337,593, 543,950,335 (+/-7.9...
E+28) † with no decimal point;
0 through +/-7.9228162514
264337593543950335 with 28
places to the right of the decimal;
smallest nonzero number is +/-
0.000000000 0000 000000000000001
(+/-1E-28) †
Double(double- Double 8 bytes -1.79769313486231570E+308
precision floating- through -4.94065645841246544E-
point) 324 † for negative values;
4.94065645841246544E-324 through
1.79769313486231570E+308 † for
positive values
Integer Int32 4 bytes -2,147,483,648 through
2,147,483,647 (signed)
Long (long Int64 8 bytes -9,223,372,036,854,775,808 through
integer) 9,223,372,036,854,775,807 (9.2...
E+18 †) (signed)
Object Object(class) 4 bytes on 32- Any type can be stored in a
bit platform 8 variable of type Object
bytes on 64-bit
platform
SByte SByte 1 byte -128 through 127 (signed)
Short(short Int16 2 bytes -32,768 through 32,767 (signed)
integer)
Single(single- Single 4 bytes -3.4028235E+38 through
precision floating- -1.401298E-45 † for negative
point) values; 1.401298E-45 through
3.4028235E+38 † for positive values
String(variable- String(class) Depends on 0 to approximately 2 billion
length) implementing Unicode characters
platform
UInteger UInt32 4 bytes 0 through 4,294,967,295 (unsigned)
32
Data Types, Constants and Variables
ULong UInt64 8 bytes 0 through
18,446,744,073,709,551,615 (1.8...
E+19 †) (unsigned)
User- (inherits from Depends on Each member of the structure
Defined(structure) ValueType) implementing has a range determined by its
platform data type and independent of the
ranges of the other members
UShort UInt16 2 bytes 0 through 65,535 (unsigned)
†
In scientific notation, “E” refers to a power of 10. So 3.56E+2
signifies 3.56 x 102 or 356, and 3.56E-2 signifies 3.56 / 102 or 0.0356.
2.1.1 Memory Consumption
When you declare an elementary data type, it is not safe to assume
that its memory consumption is the same as its nominal storage
allocation. This is due to the following considerations:
■ Storage Assignment. The common language runtime can
assign storage based on the current characteristics of the
platform on which your application is executing. If memory
is nearly full, it might pack your declared elements as
closely together as possible. In other cases it might align
their memory addresses to natural hardware boundaries
to optimize performance.
■ Platform Width. Storage assignment on a 64-bit platform
is different from assignment on a 32-bit platform.
2.1.2 Composite Data Types
The same considerations apply to each member of a composite
data type, such as a structure or an array. You cannot rely on
simply adding together the nominal storage allocations of the type’s
members. Furthermore, there are other considerations, such as the
following:
■ Overhead. Some composite types have additional memory
requirements. For example, an array uses extra memory for
the array itself and also for each dimension. On a 32-bit
platform, this overhead is currently 12 bytes plus 8 bytes
for each dimension. On a 64-bit platform this requirement
is doubled.
33
Basic Computer Coding: Visual Basic
■ Storage Layout. You cannot safely
assume that the order of storage in
memory is the same as your order of
declaration. You cannot even make
assumptions about byte alignment,
such as a 2-byte or 4-byte boundary.
If you are defining a class or structure
and you need to control the storage
layout of its members, you can apply
the StructLayoutAttribute attribute to
the class or structure.
2.1.3 Boolean Data Type
Holds values that can be only True or False.
The keywords True and False correspond to
the two states of Boolean variables.
Use the Boolean Data Type (Visual Basic) to
contain two-state values such as true/false, yes/
no, or on/off.
The default value of Boolean is False.
Boolean values are not stored as numbers,
Boolean data type is a and the stored values are not intended to be
data type that has one
of two possible values equivalent to numbers. You should never write
(usually denoted true code that relies on equivalent numeric values
and false), intended to for True and False. Whenever possible, you
represent the two truth
values of logic and should restrict usage of Boolean variables to
Boolean algebra. the logical values for which they are designed.
Type Conversions
When Visual Basic converts numeric data type
values to Boolean, 0 becomes False and all other
values become True. When Visual Basic converts
Boolean values to numeric types, Falsebecomes
0 and True becomes -1.
When you convert between Boolean values
and numeric data types, keep in mind that
the .NET Framework conversion methods do
34
Data Types, Constants and Variables
not always produce the same results as the Visual Basic conversion
keywords. This is because the Visual Basic conversion retains
behavior compatible with previous versions. For more information,
see “Boolean Type Does Not Convert to Numeric Type Accurately”
in Troubleshooting Data Types.
Programming Tips
■ Negative Numbers. Boolean is not a numeric type and
cannot represent a negative value. In any case, you should
not use Boolean to hold numeric values.
■ Type Characters. Boolean has no literal type character or
identifier type character.
■ Framework Type. The corresponding type in the .NET
Framework is the System. Boolean structure.
Example: In the following example, running VB is a Boolean variable,
which stores a simple yes/no setting.
Dim runningVB As Boolean
‘ Check to see if program is running on Visual Basic engine.
If scriptEngine = “VB” Then
runningVB = True
End If
2.1.4 Byte Data Type
Holds unsigned 8-bit (1-byte) integers that range in value from 0
through 255. Use the Byte data type to contain binary data. The
default value of Byte is 0.
Programming tips
■ Negative Numbers. Because Byte is an unsigned type, it
cannot represent a negative number. If you use the unary
minus (-) operator on an expression that evaluates to type
Byte, Visual Basic converts the expression to Short first.
■ Format Conversions. When Visual Basic reads or writes
35
Basic Computer Coding: Visual Basic
files, or when it calls DLLs, methods, and properties, it can
automatically convert between data formats. Binary data
stored in Bytevariables and arrays is preserved during such
format conversions. You should not use a String variable for
binary data, because its contents can be corrupted during
conversion between ANSI and Unicode formats.
■ Widening. The Byte data type widens to Short, UShort,
Integer, UInteger, Long, ULong, Decimal, Single, or Double.
This means you can convert Byte to any of these types
without encountering a [Link] error.
■ Type Characters. Byte has no literal type character or
identifier type character.
■ Framework Type. The corresponding type in the .NET
Framework is the [Link] structure.
Example: In the following example, b is a Byte variable. The
statements demonstrate the range of the variable and the application
of bit-shift operators to it.
‘ The valid range of a Byte variable is 0 through 255.
Dim b As Byte
b = 30
‘ The following statement causes an error because the value is
too large.
‘b = 256
‘ The following statement causes an error because the value is
negative.
‘b = -5
‘ The following statement sets b to 6.
b = CByte(5.7)
‘ The following statements apply bit-shift operators to b.
‘ The initial value of b is 6.
36
Data Types, Constants and Variables
[Link](b)
‘ Bit shift to the right divides the number in half. In this
‘ example, binary 110 becomes 11.
b >>= 1
‘ The following statement displays 3.
[Link](b)
‘ Now shift back to the original position, and then one more bit
‘ to the left. Each shift to the left doubles the value. In this
‘ example, binary 11 becomes 1100.
b <<= 2
‘ The following statement displays 12.
[Link](b)
2.1.5 Char Data Type
Holds unsigned 16-bit (2-byte) code points ranging in value from
0 through 65535. Each code point, or character code, represents a
single Unicode character.
Use the Char data type when you need to hold only a single character
and do not need the overhead of String. In some cases you can use
Char(), an array of Char elements, to hold multiple characters. The
default value of Char is the character with a code point of 0.
Unicode Characters
The first 128 code points (0–127) of Unicode correspond to the
letters and symbols on a standard U.S. keyboard. These first 128
code points are the same as those the ASCII character set defines.
The second 128 code points (128–255) represent special characters,
such as Latin-based alphabet letters, accents, currency symbols, and
fractions. Unicode uses the remaining code points (256-65535) for
37
Basic Computer Coding: Visual Basic
a wide variety of symbols, including worldwide textual characters,
diacritics, and mathematical and technical symbols.
You can use methods like IsDigit and IsPunctuation on a Char
variable to determine its Unicode classification.
Type Conversions
Visual Basic does not convert directly between Char and the numeric
types. You can use the Asc or AscW function to convert a Char
value to an Integer that represents its code point. You can use the
Chr or ChrW function to convert an Integer value to a Char that
has that code point.
If the type checking switch (Option Strict Statement) is on, you
must append the literal type character to a single-character string
literal to identify it as the Char data type. The following example
illustrates this.
Option Strict On
Dim charVar As Char
‘ The following statement attempts to convert a String literal to Char.
‘ Because Option Strict is On, it generates a compiler error.
charVar = “Z”
‘ The following statement succeeds because it specifies a Char literal.
charVar = “Z”C
Programming Tips
■ Negative Numbers. Char is an unsigned type and cannot
represent a negative value. In any case, you should not
use Char to hold numeric values.
■ Interop Considerations. If you interface with components not
written for the .NET Framework, for example Automation or
COM objects, remember that character types have a different
data width (8 bits) in other environments. If you pass an
38
Data Types, Constants and Variables
8-bit argument to such a component,
declare it as Byte instead of Char in
your new Visual Basic code.
■ Widening. The Char data type widens
to String. This means you can convert
Char to String and will not encounter
a [Link] error.
■ Type Characters. Appending the
literal type character C to a single-
character string literal forces it to the
Char data type. Char has no identifier
type character.
■ Framework Type. The corresponding
type in the .NET Framework is the
[Link] structure.
Remember
2.1.6 Decimal Data Type The Decimal data
Holds signed 128-bit (16-byte) values type provides the
representing 96-bit (12-byte) integer numbers greatest number of
scaled by a variable power of 10. The significant digits
scaling factor specifies the number of digits for a number. It
to the right of the decimal point; it ranges supports up to 29
from 0 through 28. With a scale of 0 (no significant digits
decimal places), the largest possible value and can represent
is +/-79,228,162,514,264,337,593,543,950,335 values in excess of
(+/-7.9228162514264337593543950335E+28). 7.9228 x 10^28. It is
With 28 decimal places, the largest value particularly suitable
is +/-7.9228162514264337593543950335, for calculations,
and the smallest nonzero value is +/- such as financial,
0.0000000000000000000000000001 (+/-1E-28). that require a large
■ Precision. Decimal is not a floating- number of digits
point data type. The Decimal structure but cannot tolerate
holds a binary integer value, together rounding errors.
with a sign bit and an integer scaling The default value
factor that specifies what portion of of Decimal is 0.
the value is a decimal fraction. Because
of this, Decimal numbers have a more
39
Basic Computer Coding: Visual Basic
precise representation in memory than floating-point types
(Single and Double).
■ Performance. The Decimal data type is the slowest of all
the numeric types. You should weigh the importance of
precision against performance before choosing a data type.
■ Widening. The Decimal data type widens to Single or Double.
This means you can convert Decimal to either of these types
without encountering a [Link] error.
■ Trailing Zeros. Visual Basic does not store trailing zeros
in a Decimal literal. However, a Decimal variable preserves
any trailing zeros acquired computationally. The following
example illustrates this.
Dim d1, d2, d3, d4 As Decimal
d1 = 2.375D
d2 = 1.625D
d3 = d1 + d2
d4 = 4.000D
MsgBox(“d1 = “ & CStr(d1) & “, d2 = “ & CStr(d2) &
“, d3 = “ & CStr(d3) & “, d4 = “ & CStr(d4))
The output of MsgBox in the preceding example is as follows:
d1 = 2.375, d2 = 1.625, d3 = 4.000, d4 = 4
■ Type Characters. Appending the literal type character D
to a literal forces it to the Decimaldata type. Appending
the identifier type character @ to any identifier forces it
to Decimal.
■ Framework Type. The corresponding type in the .NET
Framework is the [Link].
Range
You might need to use the D type character to assign a large value
to a Decimal variable or constant. This requirement is because the
40
Data Types, Constants and Variables
compiler interprets a literal as Long unless a literal type character
follows the literal, as the following example shows.
Dim bigDec1 As Decimal = 9223372036854775807 ‘ No overflow.
Dim bigDec2 As Decimal = 9223372036854775808 ‘ Overflow.
Dim bigDec3 As Decimal = 9223372036854775808D ‘ No
overflow.
The declaration for bigDec1 doesn’t produce an overflow because
the value that’s assigned to it falls within the range for Long. The
Long value can be assigned to the Decimal variable.
The declaration for bigDec2 generates an overflow error because the
value that’s assigned to it is too large for Long. Because the numeric
literal can’t first be interpreted as a Long, it can’t be assigned to
the Decimal variable.
For bigDec3, the literal type character D solves the problem by
forcing the compiler to interpret the literal as a Decimal instead
of as a Long.
2.1.7 Double Data Type
Holds signed IEEE 64-bit (8-byte) double-precision floating-point
numbers that range in value from -1.79769313486231570E+308
through -4.94065645841246544E-324 for negative values and from
4.94065645841246544E-324 through 1.79769313486231570E+308 for
positive values. Double-precision numbers store an approximation
of a real number.
The Double data type provides the largest and smallest possible
magnitudes for a number. The default value of Double is 0.
Programming Tips
■ Precision. When you work with floating-point numbers,
remember that they do not always have a precise
representation in memory. This could lead to unexpected
results from certain operations, such as value comparison
and the Mod operator. For more information, see
Troubleshooting Data Types.
41
Basic Computer Coding: Visual Basic
■ Trailing Zeros. The floating-point
data types do not have any internal
representation of trailing zero
Floating-point data characters. For example, they do not
types are stored in distinguish between 4.2000 and 4.2.
the IEEE SINGLE and Consequently, trailing zero characters
DOUBLE precision do not appear when you display or
formats. Both formats
have a sign bit field, an print floating-point values.
exponent field, and a ■ Type Characters. Appending the literal
fraction field. type character R to a literal forces it to
the Doubledata type. For example, if
an integer value is followed by R, the
value is changed to a Double.
Visual Basic expands the 4 in the statement
Dim dub As Double = 4R to 4.0:
Dim dub As Double = 4.0R
Appending the identifier type character # to any
identifier forces it to Double. In the following
example, the variable num is typed as a Double:
Dim num# = 3
■ Framework Type. The corresponding
type in the .NET Framework is the
[Link].
2.1.8 Integer data type
Holds signed 32-bit (4-byte) integers that
range in value from -2,147,483,648 through
2,147,483,647. The Integer data type provides
optimal performance on a 32-bit processor. The
other integral types are slower to load and
store from and to memory. The default value
of Integer is 0.
In the following example, integers equal
to 16,342 that are represented as decimal,
hexadecimal, and binary literals are assigned
to Integer values.
42
Data Types, Constants and Variables
Dim intValue1 As Integer = 90946
[Link](intValue1)
Dim intValue2 As Integer = &H16342
[Link](intValue2)
Dim intValue3 As Integer = &B0001_0110_0011_0100_0010
[Link](intValue3)
The example displays the following output:
‘ 90946
‘ 90946
‘ 90946
Range
If you try to set a variable of an integral type to a number outside
the range for that type, an error occurs. If you try to set it to a
fraction, the number is rounded up or down to the nearest integer
value. If the number is equally close to two integer values, the value
is rounded to the nearest even integer. This behavior minimizes
rounding errors that result from consistently rounding a midpoint
value in a single direction. The following code shows examples of
rounding.
The valid range of an Integer variable is -2147483648 through
+2147483647.
Dim k As Integer
The following statement causes an error because the value is too
large.
k = 2147483648
The following statement sets k to 6.
k = 5.9
The following statement sets k to 4
43
Basic Computer Coding: Visual Basic
k = 4.5
The following statement sets k to 6
Note, Visual Basic uses banker’s rounding (toward nearest even
number)
k = 5.5
2.2 VARIABLES IN VISUAL BASIC
A variable is temporary storage space for numbers, text, and objects.
Variables are constantly being created and destroyed and will not
hold any values after your program has ended. If you want to save
the values of variables or other data. Before allocating storage space
for a variable, decide what the variable’s lifetime will be, or in other
words, which procedures and which modules should have access
to the variable’s value.
Procedure-level variables are created with a Dim statement placed
right in the procedure where it’s going to be used. The value of a
procedure level variable cannot be accessed outside it’s procedure.
When the procedure finishes (End Sub or End Function), the variable
is destroyed and memory allocated to the variable is released.
Module-level variables are created with a Private statement in the
general declarations section of a Form or code module. The value
of the module level variable is available to every procedure in
that module. Memory allocated to the module-level variable is not
destroyed until the module is Unloaded.
Global variables are created with a Public statement in the general
declarations section of a Form or code module. The value of a
Global variable is available to any procedure, in any Form or code
module. Memory allocated to a Global variable is not released until
your program shuts down.
It would certainly be easier to make every variable Global. You
wouldn’t have to think twice about it’s availability at any given
time. But sometimes, every byte of memory counts, so don’t give
your variables any more life than they actually require.
44
Data Types, Constants and Variables
2.2.1 Declaring Variables
There are two principle ways to add variables to your applications.
The first method – called implicit declaration – is to let Visual Basic
automatically create the variable for you. Implicit declaration means
that Visual Basic automatically creates a variant for each identifier
it recognizes as a variable in an application.
The second approach to declaring variable is to explicitly declare
them with one of the following keywords: Dim, Static, Private,
and Public. The choice of keyword has a profound effect on the
variable’s scope within the application and determines where the
variable can be used in the program.
The syntax for explicitly declaring a variable is quite simple:
Code:
Dim VariableName As DataType
Static VariableName As DataType
Private VariableName As DataType
Public VariableName As DataType
In each case, the name of the variable and its data type are provided
as part of the declaration.
Visual Basic reserves the amount of memory required to hold the
variable as soon as the declaration statement is executed. After
a variable is declared, it is not possible to change its data type,
although it is quite easy to convert the value of a variable and
assign the converted value to another variable.
2.2.2 Comparing Implicit and Explicit Variable
Performance
The default data type for Visual Basic variables is the variant. This
means that, unless you specify otherwise, every variable in your
application will be a variant. The data type is not very efficient. Its
data storage requirements are greater than the equivalent simple
data type. The computer spends more time keeping track of the
data type contained in a variant than for other data types.
45
Basic Computer Coding: Visual Basic
An explicit declaration statically types the
variable it declares. In a language that requires
explicit declaration, you will get a compilation
error for any reference to a variable that has
not been explicitly declared.
By contrast, in a language that supports implicit
declaration, simply using a variable in code
implies the declaration. If your code assigns
a string to the variable, then it is declared to
be a string.
Convenient, yes? Not so much. Any time you
misspell a variable name you get a new one
and the program moves on, with incorrect
conditional behavior or a wrongly computed
Visual Studio Code value.
is a source code editor
developed by Microsoft
Given the rise of very smart editors like Visual
for Windows, Linux Studio Code, implicit declaration need not be
and macOS. It includes the menace it was, at least for languages that
support for debugging,
support the notion of optional declaration,
embedded Git control,
syntax highlighting, for example Visual Basic. Smart editors can
intelligent code highlight references to undeclared variables
completion, snippets, and list them in warnings. Great for rapid
and code refactoring.
prototyping, especially if the editor provides
an alphabetical list of symbol names - which
would make typos obvious.
2.2.3 Providing Names for the
Variables
Visual Basic provides extremely liberal rules
for naming variables. Briefly, all variable names
must conform to the following requirements:
The name must being with a letter of the
alphabet.
The name must consist only of letters, digits,
and the underscore character. (No punctuation
marks are allowed.)
46
Data Types, Constants and Variables
The name can be as long as 255 characters.
Variable names can’t be duplicated with the same scope.
This means, that you can’t have two variables of the same
name within a procedure. You can, however, have two
variables with the same name in two different procedures.
2.2.4 Static Variables
Only Procedure-level variables can be declared
Static. This means the variable is not destroyed
and will retain it’s value between multiple calls
to the procedure. This might not sound any
different than a module-level variable which
is used in more than one procedure while the
Static variable is associated with only one.
Here’s a class (TestClass) with a private Integer
field that can be access by all class member.
Meanwhile, inside of a method is a local VB
Static variable that can only be accessed inside
the method. Note that no other members of
the class can access it yet it maintains state
between calls to the method.
Public Class TestClass
Private ClassLevelCount As Integer = 0
Public Sub ClassLevelAddOne()
ClassLevelCount += 1
[Link](“ClassLevelCount = {0}”,
ClassLevelCount)
End Sub
Public Sub ClassLevelAddTen()
ClassLevelCount += 10 ‘ This method can
47
Basic Computer Coding: Visual Basic
change it too! :)
[Link](“ClassLevelCount = {0}”, ClassLevelCount)
End Sub
Public Sub UltraPrivateAddTen()
‘ ========================================================
==========
‘ Doesn’t work. This method doesn’t have access to UltraPrivateCount
‘ I can’t change this and had to comment it out. :(
‘ ========================================================
==========
‘UltraPrivateCount += 1
‘[Link](“UltraPrivateCount = {0}”, UltraPrivateCount)
End Sub
Public Sub LocalVarAddOne()
Dim LocalVarCount As Integer = 0
LocalVarCount += 1
[Link](“LocalVarAddOne = {0}”, LocalVarCount)
End Sub
Public Sub UltraPrivateAddOne()
‘ Local variable that holds state between method invocations.
Static UltraPrivateCount As Integer = 0
UltraPrivateCount += 1
[Link](“UltraPrivateCount = {0}”, UltraPrivateCount)
End Sub
End Class
Look how the VB Static variable is defined in the sub call
UltraPrivateAddOne(). Even though we are assigning 0 to it the
first time the method is called, that piece of initialization code will
be ignored when the method is called again because it is declared
as Static.
48
Data Types, Constants and Variables
Now we need a Main() method that calls these methods so we can
analyze the results. Here we go:
Module Module1
Sub Main()
[Link](“tc1”)
Dim tc1 As New TestClass()
Dim tc2 As New TestClass()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link](“tc2”)
[Link]()
[Link]()
End Sub
End Module
Note that we are trying to add one and ten to a class-level variable.
Then we try adding one to a local variable. We can do all this in
C# as well. However, we try adding one to the Static variable (only
in VB!), and it continues to increment in value inside the method.
For fun, we also create another object (tc2) and see if it has the
same VB Static variable, which it does not.
49
Basic Computer Coding: Visual Basic
Here are the results:
Need a super private variable just for one method? Consider declaring
it as Static: the VB Static variable. Happy coding!
2.2.5 Forcing Explicit Declaration
Visual Basic provides a simple complier directive that forces you to
always declare the variables in your applications. When the Option
explicit statement is inserted at the top of a module, it instructs Visual
Basic to require explicit declaration of all variables in the module.
If, for example, you are working with an application that contains
several implicitly declared variables, inserting Option Explicit at the
top of each module results in a check of all variable declarations
the next time the application is complied.
Because explicit declaration is such a good idea, it might not come as
a surprise that Visual Basic provides a way to automatically ensure
that every module in your applications uses explicit declaration. The
Editor tab of the Options dialog box includes a Require Variable
Declaration check box. This option automatically inserts the Option
Explicit directive at the top of very module from this point in time.
Note: The Require Variable Declaration option does not effect modules
already written. This option applies only to modules created after
this option is selected. Therefore, you must insert the Option Explicit
directive in existing modules.
50
Data Types, Constants and Variables
2.2.6 Using a Naming Convention
Like most programming languages, applications
written in Visual Basic tend to be long and
complex, often occupying several thousand
lines of code. Even simple Visual Basic
programs might require hundreds of different
variables. Visual Basic forms often have dozens
of different controls on them, including text Naming convention
boxes, command buttons, option groups, is a set of rules for
and other controls. Keeping track of the choosing the character
sequence to be used
variables, procedures, forms, and controls in for identifiers which
even a moderately complicated Visual Basic denote variables, types,
application is a daunting task. functions, and other
entities in source code
One way to ease the burden of managing the and documentation.
code and objects in an application is to use
naming conventions. A naming convention
applies a standardized method of supplying
names to the objects and variables in an
application.
Using a naming convention is not difficult.
In most case, when the use of the variable is
obvious a one-character prefix is used to keep
code examples short and simple. In longer
procedures, three-character prefixes are used
on most variables.
2.2.7 Understanding Variable Scope
and Lifetime
A variable is more than just a simple data
repository. Every variable is a dynamic part
of the application and can be used at different
times during the program’s execution. The
declaration of a variable establishes more than
just the name and data type of the variable.
Depending on the keyword used to declare the
variable and the placement of the variable’s
declaration in the program’s code, the variable
51
Basic Computer Coding: Visual Basic
might be visible to large portions of the
application’s code. Alternatively, a different
placement might severely limit where the
variable can be referenced in the procedures
within the application.
The visibility of a variable or procedure is called
its scope. A variable that can be seen and used
by any procedure in the application is said to
have public scope. Another variable, one that
is usable by a single procedure, is said to have
scope that is private to that procedure.
Remember
There are many analogies for public and private
scope. Variables declared within a procedure
Variables are
are local to that procedure and cannot be used
often used in all
or referenced outside that procedure.
programs and they
help you store In each case, the Dim keyword was used to
values temporarily define the variable.
while the program Dim is shorthand for dimension and is a rather
is executing. You archaic expression that instructs Visual Basic to
can have long-term
allocate enough memory to contain the variable
variables(global)
that follows the Dim keyword. Therefore, Dim i
which are used
As Integer allocates less memory (2 bytes) than
while the program
is been used or you Dim s As Double (8 bytes). There is no way to
can have private make a variable declared within a procedure
variables which visible outside of that procedure.
are used only on The public keyword is used to make a variable
one form of the visible throughout an application. Public can be
program and even used only at the module level and cannot be
local variables used within a procedure. Usually, the Public
which are only
keyword is used only in standard modules that
used on a specific
are not part of a form. Every variable declared
procedure inside a
form.
in the general section of the standard module
is public throughout the application unless the
Private keyword is used. Private restricts the
visibility of a variable to the module in which
the variable is declared.
52
Data Types, Constants and Variables
2.3 CONSTANTS IN VISUAL BASIC
A constant is a meaningful name that takes the place of a number
or string that does not change. Constants store values that, as the
name implies, remain constant throughout the execution of an
application. You can use constants that are defined by the controls or
components you work with, or you can create your own. Constants
you create yourself are described as user-defined.
You can greatly improve the readability of your code and make it
easier to maintain by using constants. Use them in code that contains
values that reappear or that depends on certain numbers that are
difficult to remember or have no obvious meaning.
How to Create and Use Constants: Visual Basic contains a number
of predefined constants, mainly using for printing and displaying.
You can also create your own constants with the Const statement,
using the same guidelines you would for creating a variable name.
If Option Strict is On, you must explicitly declare the constant type.
A constant’s scope, which is the set of all code that can refer to it
without qualifying its name, is the same as that of a variable declared
in the same location. To create a constant that exists within the
scope of a particular procedure, declare it inside that procedure. To
create a constant that is available throughout an application, declare
it using the Public keyword in the declarations section of the class.
Although constants somewhat resemble variables, you cannot modify
them or assign new values to them as you can to variables.
The constants you use in your code can be defined by the object
model for controls or components you work with, or they can be
user-defined (that is, those you create yourself).
Compile-time and Run-time Constants: A compile-time constant
is computed at the time the code is compiled, while a run-time
constant can only be computed while the application is running.
A compile-time constant will have the same value each time an
application runs, while a run-time constant may change each time.
Compile-time constants are required for cases such as array bounds,
case expressions, or enumerator initializers.
53
Basic Computer Coding: Visual Basic
You declare a constant with the Const statement, using the same
guidelines you would for creating a variable name. If Option Strict
is On, you must explicitly declare the constant type.
2.3.1 User-Defined Constants
A constant is a meaningful name that takes the place of a number
or string that does not change. Constants store values that, as the
name implies, remain constant throughout the execution of an
application. You can use constants that are defined by the controls or
components you work with, or you can create your own. Constants
you create yourself are described as user-defined.
You declare a constant with the Const statement, using the same
guidelines you would for creating a variable name. If Option Strict
is On, you must explicitly declare the constant type.
Const Statement Usage
A Const statement can represent a mathematical or date/time quantity:
Const conPi = 3.14159265358979
Public Const conMaxPlanets As Integer = 9
Const conReleaseDate = #1/1/1995#
It also can define String constants:
Public Const conVersion = “07.10.A”
Const conCodeName = “Enigma”
The expression on the right side of the equal sign ( = ) is often a
number or literal string, but it also can be an expression that results
in a number or string (although that expression cannot contain calls
to functions). You can even define constants in terms of previously
defined constants:
Const conPi2 = conPi * 2
54
Data Types, Constants and Variables
Scope of User-Defined Constants
A Const statement›s scope is the same as that of a variable declared
in the same location. You can specify scope in any of the following
ways:
■ To create a constant that exists only within a procedure,
declare it within that procedure.
■ To create a constant available to all procedures within a
class, but not to any code outside that module, declare it
in the declarations section of the class.
■ To create a constant that is available to all members of
an assembly, but not to outside clients of the assembly,
declare it using the Friend keyword in the declarations
section of the class.
■ To create a constant available throughout the application,
declare it using the Publickeyword in the declarations
section the class.
Avoiding Circular References
Because constants can be defined in terms of other constants, it is
possible to inadvertently create a cycle, or circular reference, between
two or more constants. A cycle occurs when you have two or more
public constants, each of which is defined in terms of the other, as
in the following example:
Public Const conA = conB * 2
Public Const conB = conA / 2
If a cycle occurs, Visual Basic generates a compiler error.
2.3.2 Declare a Constant
You use the Const statement to declare a constant and set its value.
By declaring a constant, you assign a meaningful name to a value.
Once a constant is declared, it cannot be modified or assigned a
new value.
You declare a constant within a procedure or in the declarations
section of a module, class, or structure. Class or structure-level
constants are Private by default, but may also be declared as Public,
55
Basic Computer Coding: Visual Basic
Friend, Protected, or Protected Friend for the
appropriate level of code access.
The constant must have a valid symbolic name
(the rules are the same as those for creating
variable names) and an expression composed
of numeric or string constants and operators
(but no function calls).
To declare a constant
String constants
are a special type of Write a declaration that includes an access
constants which store specifier, the Const keyword, and an expression,
fixed sequences of as in the following examples:
characters.
Public Const DaysInYear = 365
Private Const WorkDays = 250
When Option Infer is Off and Option Strict is
On, you must declare a constant explicitly by
specifying a data type (Boolean, Byte, Char,
DateTime, Decimal, Double, Integer, Long,
Short, Single, or String).
When Option Infer is On or Option Strict is Off,
you can declare a constant without specifying
a data type with an As clause. The compiler
determines the type of the constant from the
type of the expression.
To declare a constant that has an
explicitly stated data type
■ Write a declaration that includes the
As keyword and an explicit data type,
as in the following examples:
Public Const MyInteger As Integer = 42
Private Const DaysInWeek As Short = 7
Protected Friend Const Funday As String =
“Sunday”
56
Data Types, Constants and Variables
You can declare multiple constants on a single line, although your
code is more readable if you declare only a single constant per
line. If you declare multiple constants on a single line, they must
all have the same access level (Public, Private, Friend, Protected,
or Protected Friend).
To declare multiple constants on a single line
Separate the declarations with a comma and a space, as in the
following example:
Public Const Four As Integer = 4, Five As Integer = 5, Six As
Integer = 44
2.3.3 Constant and Literal Data Types
A literal is a value that is expressed as itself rather than as a variable’s
value or the result of an expression, such as the number 3 or the
string “Hello”. A constant is a meaningful name that takes the place
of a literal and retains this same value throughout the program, as
opposed to a variable, whose value may change.
When Option Infer is Off and Option Strict is On, you must declare
all constants explicitly with a data type. In the following example,
the data type of MyByte is explicitly declared as data type Byte:
Option Strict On
Public Class Sample
Public Const MyByte As Byte = 2
End Class
When Option Infer is On or Option Strict is Off, you can declare
a constant without specifying a data type with an As clause. The
compiler determines the type of the constant from the type of the
expression. A numeric integer literal is cast by default to the Integer
data type. The default data type for floating-point numbers is Double,
and the keywords True and Falsespecify a Boolean constant.
57
Basic Computer Coding: Visual Basic
Literals and Type Coercion
In some cases, you might want to force a
literal to a particular data type; for example,
when assigning a particularly large integral
literal value to a variable of type Decimal. The
following example produces an error:
Dim myDecimal as Decimal
myDecimal = 100000000000000000000 ‘
This causes a compiler error.
The error results from the representation of
the literal. The Decimal data type can hold
a value this large, but the literal is implicitly
represented as a Long, which cannot.
All versions of You can coerce a literal to a particular data type
the Visual Basic in two ways: by appending a type character to
development
environment from
it, or by placing it within enclosing characters.
1.0 to 6.0 were A type character or enclosing characters must
retired by Microsoft immediately precede and/or follow the literal,
by 2008, and are with no intervening space or characters of any
therefore no longer kind.
supported. The
associated runtime To make the previous example work, you can
environments are append the D type character to the literal, which
also unsupported, causes it to be represented as a Decimal:
except for the Visual Dim MyDecimal As Decimal =
Basic 6 core runtime
100000000000000000000D
environment, which
Microsoft officially
The following example demonstrates correct
supports for the
lifetime of Windows usage of type characters and enclosing
8 and Windows 10. characters:
Default to Integer.
Public Const DefaultInteger As
Integer = 100
Default to Double.
Public Const DefaultDouble As
58
Data Types, Constants and Variables
Double = 54.3345612
Force constant to be type Char.
Public Const MyCharacter As Char = “a”c
DateTime constants.
Public Const MyDate As DateTime = #1/15/2001#
Public Const MyTime As DateTime = #1:15:59 AM#
Force data type to be Long.
Public Const MyLong As Long = 45L
Force data type to be Single.
Public Const MySingle As Single = 45.55!
The following table shows the enclosing characters and type characters
available in Visual Basic.
Data type Enclosing character Appended type character
Boolean (none) (none)
Byte (none) (none)
Char “ C
Date # (none)
Decimal (none) D or @
Double (none) R or #
Integer (none) I or %
Long (none) L or &
Short (none) S
Single (none) F or !
String “ (none)
59
Basic Computer Coding: Visual Basic
CASE STUDY
FUJITSU FACILITATES SMOOTH MIGRATION TO [Link]
AT AN POST
Fujitsu has an excellent technical team, which works closely with our
staff. We have had a good working relationship for many years and
Fujitsu has an in-depth knowledge of our mission-critical application
gained from several years’ development and support work.
Challenge
A Post, one of Ireland’s largest companies, is a major commercial
organization providing a wide range of postal, communication,
retail and financial services. With 9,600 employees throughout
its national network of retail, processing and delivery points, the
business also provides services to government departments, the
National Treasury Management Agency and its own National Lottery
Company. A decade ago, A Post implemented a new nationwide
time and attendance system to calculate and record staff salary
and wages functions. The Staff Remuneration and Administration
Management System (STREAMS) is a bespoke, mission-critical
application developed by Fujitsu as a reliable, scalable client server
system using Microsoft technologies. The STREAMS front-end
system gathers information and feeds the data to the company’s
HR, payroll and financial departments. It primarily creates more
efficient processes for A Post to capture data for the weekly payroll
run whilst simultaneously minimizing the number of payroll queries
by employees. Following deployment, STREAMS improved cost
center reporting, significantly lowered the time to record pay
details and enhanced the processing of casual staff pay. During this
period, Fujitsu provided quality support and maintenance services
and application enhancements to increase functionality, ensuring
the long-term reliability of STREAMS. For instance, as employee
numbers steadily increased to exceed original expectations, Fujitsu
boosted system performance by upgrading the infrastructure and
optimizing the software. STREAMS originally employed Visual Basic
(VB), a third-generation event-driven programming language and
integrated development environment (IDE) from Microsoft. IDE
60
Data Types, Constants and Variables
provides programmers with comprehensive facilities for software
development and comprises a source code editor, a compiler and/
or an interpreter, build automation tools and a debugger. However,
Microsoft no longer supports VB version 6.0, the edition employed
by A Post. Syl Byrne, IT Manager Remuneration Services, A Post,
explains: “To ensure that our business-critical application is future-
proof, we needed to move to a platform that Microsoft will support
for the foreseeable future.” A Post therefore decided to migrate
STREAMS to the [Link] platform, an object-orientated programming
language. This strategy would protect its investment for the next
10 years by creating a secure, scalable and supported environment
with lower management costs. “Migrating to [Link] was the best
solution because it would provide our 400 end-users with the same
look-and-feel that they were accustomed to with VB6.
Moreover, for the next phase of the project, [Link] allows us to
move away from a client server product to a more flexible web-
based environment,” continues Syl Byrne. Recently, A Post renewed
its three-year technical development and support contract with
Fujitsu and also asked it to manage the STREAMS migration project.
“Choosing Fujitsu was never an issue,” says Syl Byrne. “Fujitsu has
an excellent technical team, which works closely with our staff. We
have had a good working relationship for many years and it has
in-depth knowledge of our mission-critical application gained from
several years’ development and support work.”
Solution
Fujitsu managed the migration project in three phases. Stage one
consisted of a proof-of-concept (POC) whilst the second and third
stages comprised dealing with the CSAD subset and managing
the main STREAMS migration respectively. The migration process
involved over 194,000 lines of code. From the onset, Fujitsu
realized that identifying the correct migration tools and process
were paramount. In addition, it appreciated that some code would
undoubtedly require manual processing. Fujitsu therefore used the
POC to assess several automated migration tools. Each tool dealt with
various screen samples and approximately 13,000 lines of code. This
approach demonstrated the feasibility and effectiveness of proposed
tools and, after identifying the most appropriate solution, would
reduce any potential problems during future developments. Fujitsu
61
Basic Computer Coding: Visual Basic
recommended a solution by NewCode Technologies. NewCode’s
suite of .NET migration products provides leading modernization
technology for migrating, enhancing and reengineering legacy
applications. During the POC, this solution migrated test code three-
times faster than Microsoft’s migration wizard, completed more code
successfully and rapidly determined the proportion of code requiring
manual resolution. “It’s not surprising that some companies find
moving from VB6 to [Link] a daunting task especially when they
decide to perform it manually,” comments, Syl Byrne. “The process
is very tedious, lengthy and fraught with difficulties because some
code simply gets lost in translation. I believe many businesses are
spending a fortune to get code rewritten manually because they do
not have appropriate in-house resources. However, Fujitsu proved
that we could migrate 90 per cent of our legacy code automatically
in a cost-effective manner.” Before the migration, Fujitsu helped
NewCode fine tune the tool and, compared to manual analysis,
determined that this technology would reduce the migration time
by 85 per cent. The POC also identified any potential risks during
the main migration, rework areas and over 30 code errors. The
STREAMS migration project involved design, systems integration,
code deployment and performance testing. Fujitsu also piloted the
new [Link] code alongside the VB6 code at 10 offices to ensure
end-users would not see any changes to the application environment.
“We liked Fujitsu’s idea of appointing a test manager to oversee the
entire test cycle. This approach was very apt because we intended
to migrate the entire application. We had to test the product from
the beginning to end so that its performance was identical to the
old product. This involved testing every screen and every field,”
states Syl Byrne.
Impact
Fujitsu successfully completed the migration in four months and
to budget. Today, A Post has a secure, scalable and supported
Microsoft platform for its mission-critical STREAMS application.
With a combination of mainstream and extended support covering 10
years, A Post has protected its considerable investment in STREAMS
and continues to benefit from efficient processes that capture data
for the weekly payroll run. In effect, migrating from VB6 to [Link]
has given this important application a new lease of life. To ensure
optimum performance, Fujitsu will provide biannual updates.
62
Data Types, Constants and Variables
From an end-user perspective, they safely use the application with
confidence because it looks and feels the same as the earlier VB6
platform. Consequently, processes appear identical, eliminating
a potential threat to business continuity. At the same time, by
moving away from a client server product, A Post will not waste
time, money and resources on VB6 development and can focus on
the next stage of the project; creating a more flexible web-based
environment, which shares libraries with other .NET components.
Expertise
Fujitsu’s Microsoft Gold Partner status and in-depth knowledge of the
required technologies, especially the .NET framework were a key benefit
for A Post. Fujitsu’s Microscope® Productivity center™ is a robust,
structured and dynamic development approach encapsulating more than
30 years of know-how and described by Gartner, the World’s leading
information technology research and advisory company, as ‘the most
extensive set of integrated methods, techniques and tools in the marketplace’.
“During the project, Fujitsu was very professional. We were assigned a
dedicated project manager to control the whole project and, unlike some
other organizations, its staff rigidly adhered to the correct processes and
procedures,” concludes Syl Byrne.
63
Basic Computer Coding: Visual Basic
SUMMARY
■ A data type, in programming, is a classification that
specifies which type of value a variable has and what
type of mathematical, relational or logical operations can
be applied to it without causing an error.
■ The data type defines which operations can safely be
performed to create, transform and use the variable in
another computation. When a program language requires
a variable to only be used in ways that respect its data
type, that language is said to be strongly typed.
■ A variable is a named memory location which temporarily
stores data that can change while the program is running. A
variable is something that may change in value. A variable
might be the number of words on different pages of this
booklet, the air temperature each day, or the exam marks
given to a class of school children.
■ A constant is a value that never changes. The other type
of values that programs use is variables, symbols that
can represent different values throughout the course of a
program.
■ All programs are composed of two items: Data and
Operations on that Data. Because, at their heart, computers
are simple devices, they can only represent very simple
pieces of information. All complex information must be
built up from these basic Data Types. The data types can
roughly be described as: numbers, Booleans, characters,
arrays, and structures.
■ When Visual Basic converts numeric data type values to
Boolean, 0 becomes False and all other values become True.
When Visual Basic converts Boolean values to numeric
types, Falsebecomes 0 and True becomes -1.
■ A variable is temporary storage space for numbers, text,
and objects. Variables are constantly being created and
destroyed and will not hold any values after your program
has ended. If you want to save the values of variables or
other data.
■ The default data type for Visual Basic variables is the
variant. This means that, unless you specify otherwise,
64
Data Types, Constants and Variables
every variable in your application will be a variant. The
data type is not very efficient. Its data storage requirements
are greater than the equivalent simple data type.
■ Visual Basic provides extremely liberal rules for naming
variables. Briefly, all variable names must conform to the
following requirements:
■ Visual Basic provides a simple complier directive that forces
you to always declare the variables in your applications.
When the Option explicit statement is inserted at the top
of a module, it instructs Visual Basic to require explicit
declaration of all variables in the module.
■ A variable is more than just a simple data repository. Every
variable is a dynamic part of the application and can be
used at different times during the program’s execution.
The declaration of a variable establishes more than just
the name and data type of the variable.
■ A constant is a meaningful name that takes the place of
a number or string that does not change. Constants store
values that, as the name implies, remain constant throughout
the execution of an application. You can use constants that
are defined by the controls or components you work with,
or you can create your own.
■ A constant is a meaningful name that takes the place of
a number or string that does not change. Constants store
values that, as the name implies, remain constant throughout
the execution of an application.
65
Basic Computer Coding: Visual Basic
KNOWLEDGE CHECK
1. Which property determines whether a control is displayed
to the user?
a. Hide
b. Show
c. Visible
d. Enabled
2. The Visual Basic Code Editor will automatically detect certain
types of errors as you are entering code.
a. True
b. False
3. Visual Basic responds to events using which of the following?
a. a code procedure
b. an event procedure
c. a form procedure
d. a property
4. Statement “130 num(subs) = 2*subs-1” is an example of
a. array in COMAL
b. array in Pascal
c. array in COBOL
d. array in BASIC
5. Data types are differed on basis of
a. the way of storage
b. the type of operations
c. the type of operators used
d. both a and b
66
Data Types, Constants and Variables
REVIEW QUESTIONS
1. Discuss about the Boolean data type.
2. Explain the characteristics of char data type.
3. Define the range of decimal data type.
4. What is static variables in visual basic? Write a program
on it.
5. What do you mean by user-defined constants?
6. How to declare a constant in visual basic?
Check Your Result
1. (c) 2. (a) 3. (b) 4. (d) 5. (d)
67
Basic Computer Coding: Visual Basic
REFERENCES
1. Content Development Group, “Visual Basic 6.0
Programming” , Tata McGraw – Hill Publishing Company
Limited , New Delhi , 2005 , Pp.1-6.
2. [Link]
3. [Link]
language-reference/data-types/integer-data-type
4. [Link]
programming-guide/language-features/constants-enums/
constant-and-literal-data-types
5. [Link]
6. [Link]
[Link]
7. [Link]
type
8. [Link]
[Link]
9. [Link]
basic-t3689/
10. [Link]
basic-t3626/
11. [Link]
[Link]
12. [Link]
private-local-variable/
13. [Link]
an-implicit-and-an-explicit-declaration
14. [Link]
htm
15. [Link]
68
CHAPTER 3
CONTROL STATEMENTS
AND TOOLS
“Programming language is very specific to instructing a computer to do a particular
structure of a sequence. It›s the very way you tell the machine what you want it to
do.”
―Brian Kernighan
Learning Objectives
After studying this chapter, you will be able to:
■ Describe the statement
■ Learn about decision making structures
■ Understand the visual basic control
■ Discuss about visual basic control tools
Basic Computer Coding: Visual Basic
INTRODUCTION
Control statement is often necessary to control
the sequence of operations in a program. This
can be done by using control statements.
Control Statements are used to control the flow
of program’s execution. Visual Basic supports
control structures such as if... Then, if...Then
...Else, Select...Case, etc. method.
3.1 STATEMENT
A statement is a complete instruction in Visual
Basic programs. It may contain keywords,
operators, variables, literal values, constants
and expressions.
Statements could be categorized as −
Assignment statement ■ Declaration statements − these are the
sets and/or re-sets the
statements where you name a variable,
value stored in the
storage location(s) constant, or procedure, and can also
denoted by a variable specify a data type.
name; in other words, it
■ Executable statements − these are
copies a value into the
variable. the statements, which initiate actions.
These statements can call a method
or function, loop or branch through
blocks of code or assign values or
expression to a variable or constant. In
the last case, it is called an Assignment
statement.
3.1.1 Declaration Statements
The declaration statements are used to name
and define procedures, variables, properties,
arrays, and constants. When you declare a
programming element, you can also define its
data type, access level, and scope.
70
Control Statements and Tools
The programming elements you may declare include variables,
constants, enumerations, classes, structures, modules, interfaces,
procedures, procedure parameters, function returns, external
procedure references, operators, properties, events, and delegates.
Following are the declaration statements in [Link] −
[Link] Statements and Description Example
1 Dim Statement Dim number As Integer
Declares and allocates storage Dim quantity As Integer = 100
space for one or more variables.
Dim message As String = “Hello!”
2 Const Statement Const maximum As Long = 1000
Declares and defines one or Const naturalLogBase As Object
more constants.
= CDec(2.7182818284)
3 Enum Statement Enum CoffeeMugSize
Declares an enumeration Jumbo
and defines the values of its
members. ExtraLarge
Large
Medium
Small
End Enum
4 Class Statement Class Box
Declares the name of a class Public length As Double
and introduces the definition
of the variables, properties, Public breadth As Double
events, and procedures that the
class comprises. Public height As Double
End Class
71
Basic Computer Coding: Visual Basic
5 Structure Statement Structure Box
Declares the name of a Public length As Double
structure and introduces the
definition of the variables, Public breadth As Double
properties, events, and
procedures that the structure Public height As Double
comprises.
End Structure
6 Module Statement Public Module myModule
Declares the name of a module Sub Main()
and introduces the definition
of the variables, properties, Dim user As String =
events, and procedures that the
module comprises. InputBox(“What is your name?”)
MsgBox(“User name is” & user)
End Sub
End Module
7 Interface Statement Public Interface MyInterface
Declares the name of an Sub doSomething()
interface and introduces the
definitions of the members that End Interface
the interface comprises.
8 Function Statement Function myFunction
Declares the name, parameters, (ByVal n As Integer) As Double
and code that define a Function
procedure. Return 5.87 * n
End Function
9 Sub Statement Sub mySub(ByVal s As String)
Declares the name, parameters, Return
and code that define a Sub
procedure. End Sub
72
Control Statements and Tools
10 Declare Statement Declare Function getUserName
Declares a reference to a Lib “[Link]”
procedure implemented in an
external file. Alias “GetUserNameA”
ByVal lpBuffer As String,
ByRef nSize As Integer) As
Integer
11 Operator Statement Public Shared Operator +
Declares the operator symbol, (ByVal x As obj, ByVal y As obj)
operands, and code that define As obj
an operator procedure on a
class or structure. Dim r As New obj
‘ implemention code for r = x + y
Return r
End Operator
12 Property Statement ReadOnly Property quote() As
String
Declares the name of a
property, and the property Get
procedures used to store
and retrieve the value of the Return quoteString
property.
End Get
End Property
13 Event Statement Public Event Finished()
Declares a user-defined event.
14 Delegate Statement Delegate Function MathOperator(
Used to declare a delegate. ByVal x As Double,
ByVal y As Double
) As Double
3.1.2 Executable Statements
An executable statement performs an action. Statements calling a
procedure, branching to another place in the code, looping through
73
Basic Computer Coding: Visual Basic
several statements, or evaluating an expression
Expression is a are executable statements. An assignment
combination of one statement is a special case of an executable
or more constants, statement.
variables, operators,
and functions that the
programming language Example
interprets and computes
to produce another The following example demonstrates a decision
value. making statement −
Module decisions
Sub Main()
‘local variable definition ‘
Dim a As Integer = 10
‘ check the boolean condition using if
statement ‘
If (a < 20) Then
‘ if condition is true then print the
following ‘
[Link](“a is less than 20”)
End If
[Link](“value of a is : {0}”, a)
[Link]()
End Sub
End Module
When the above code is compiled and executed,
it produces the following result −
a is less than 20;
value of a is : 10
3.2 DECISION MAKING
STRUCTURES
Decision making structures require that the
programmer specify one or more conditions to
74
Control Statements and Tools
be evaluated or tested by the program, along with a statement or
statements to be executed if the condition is determined to be true,
and optionally, other statements to be executed if the condition is
determined to be false.
Following is the general form of a typical decision making structure
found in most of the programming languages −
[Link] provides the following types of decision making statements.
Statement Description
If ... Then statement An If...Then statement consists of a boolean
expression followed by one or more
statements.
If...Then...Else statement An If...Then statement can be followed by an
optional Else statement, which executes when
the boolean expression is false.
nested If statements You can use one If or Else if statement inside
another If or Else if statement(s).
Select Case statement A Select Case statement allows a variable to
be tested for equality against a list of values.
nested Select Case statements You can use one select case statement inside
another select case statement(s).
75
Basic Computer Coding: Visual Basic
3.2.1 If...Then Statement
It is the simplest form of control statement,
frequently used in decision making and
changing the control flow of the program
execution. Syntax for if-then statement is –
Execution is the If condition Then
process by which a
computer or virtual [Statement(s)]
machine executes
the instructions of a
End If
computer program. Where, condition is a Boolean or relational
condition and Statement(s) is a simple or
compound statement. Example of an If-Then
statement is −
If (a <= 20) Then
c= c+1
End If
If the condition evaluates to true, then the block
of code inside the If statement will be executed.
If condition evaluates to false, then the first set
of code after the end of the If statement (after
the closing End If) will be executed.
Flow Diagram
76
Control Statements and Tools
Example
Module decisions
Sub Main()
‘local variable definition
Dim a As Integer = 10
‘ check the boolean condition using if
statement
If (a < 20) Then
‘ if condition is true then print the
following
[Link](“a is less than 20”)
End If
[Link](“value of a is : {0}”, a)
[Link]()
End Sub
End Module
When the above code is compiled and executed,
it produces the following result −
a is less than 20
value of a is : 10
3.2.2 If...Then...Else Statement Boolean expression
is an expression in a
An If statement can be followed by an optional programming language
Else statement, which executes when the that produces a
Boolean expression is false. Boolean value when
evaluated, i.e. one of
true or false.
Syntax
The syntax of an If...Then... Else statement in
[Link] is as follows −
If(boolean_expression)Then
‘statement(s) will execute if the Boolean
77
Basic Computer Coding: Visual Basic
expression is true
Else
‘statement(s) will execute if the Boolean expression is false
End If
If the Boolean expression evaluates to true, then the if block of code
will be executed, otherwise else block of code will be executed.
Flow Diagram
Example
Module decisions
Sub Main()
‘local variable definition ‘
Dim a As Integer = 100
‘ check the boolean condition using if statement
If (a < 20) Then
‘ if condition is true then print the following
[Link](“a is less than 20”)
Else
78
Control Statements and Tools
‘ if condition is false then print the
following Remember
[Link](“a is not less than
20”) When using If...
End If Else If... Else
statements, there
[Link](“value of a is : {0}”, a) are few points to
[Link]() keep in mind.
End Sub • An If can have
End Module zero or one Else’s
and it must come
When the above code is compiled and executed,
after an Else If’s.
it produces the following result −
• An If can have
a is not less than 20 zero to many Else
value of a is : 100 If’s and they must
come before the
Else.
3.2.3 The If...Else If...Else Statement • Once an Else if
An If statement can be followed by an optional succeeds, none of
Else if...Else statement, which is very useful the remaining Else
to test various conditions using single If...Else If’s or Else’s will be
If statement. tested.
Syntax
The syntax of an if...else if...else statement in
[Link] is as follows −
If(boolean_expression 1)Then
‘ Executes when the boolean expression 1
is true
ElseIf( boolean_expression 2)Then
‘ Executes when the boolean expression 2
is true
ElseIf( boolean_expression 3)Then
‘ Executes when the boolean expression 3
is true
Else
‘ executes when the none of the above
79
Basic Computer Coding: Visual Basic
condition is true
End If
Example
Module decisions
Sub Main()
‘local variable definition ‘
Dim a As Integer = 100
‘ check the boolean condition ‘
If (a = 10) Then
‘ if condition is true then print the following ‘
[Link](“Value of a is 10”) ‘
ElseIf (a = 20) Then
‘if else if condition is true ‘
[Link](“Value of a is 20”) ‘
ElseIf (a = 30) Then
‘if else if condition is true
[Link](“Value of a is 30”)
Else
‘if none of the conditions is true
[Link](“None of the values is matching”)
End If
[Link](“Exact value of a is: {0}”, a)
[Link]()
End Sub
End Module
When the above code is compiled and executed, it produces the
following result −
None of the values is matching
Exact value of a is: 100
80
Control Statements and Tools
3.2.4 Nested If Statements
It is always legal in [Link] to nest If-Then-Else statements, which
means you can use one If or ElseIf statement inside another If ElseIf
statement(s).
Syntax
The syntax for a nested If statement is as follows −
If( boolean_expression 1)Then
‘Executes when the boolean expression 1 is true
If(boolean_expression 2)Then
‘Executes when the boolean expression 2 is true
End If
End If
You can nest ElseIf...Else in the similar way as you have nested If
statement.
Example
Module decisions
Sub Main()
‘local variable definition
Dim a As Integer = 100
Dim b As Integer = 200
‘ check the boolean condition
If (a = 100) Then
‘ if condition is true then check the following
If (b = 200) Then
‘ if condition is true then print the following
[Link](“Value of a is 100 and b is 200”)
End If
End If
[Link](“Exact value of a is : {0}”, a)
81
Basic Computer Coding: Visual Basic
[Link](“Exact value of b is :
{0}”, b)
[Link]()
End Sub
End Module
When the above code is compiled and executed,
it produces the following result −
Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200
3.2.5 Select Case Statement
A Select Case statement allows a variable to be
Value is the
representation of tested for equality against a list of values. Each
some entity that can value is called a case, and the variable being
be manipulated by a switched on is checked for each select case.
program.
Syntax
The syntax for a Select Case statement in [Link]
is as follows −
Select [ Case ] expression
[ Case expressionlist
[ statements ] ]
[ Case Else
[ elsestatements ] ]
End Select
Where,
■ expression − is an expression that must
evaluate to any of the elementary
data type in [Link], i.e., Boolean,
Byte, Char, Date, Double, Decimal,
Integer, Long, Object, SByte, Short,
82
Control Statements and Tools
Single, String, UInteger, ULong, and UShort.
■ expressionlist − List of expression clauses representing
match values for expression. Multiple expression clauses
are separated by commas.
■ statements − statements following Case that run if the select
expression matches any clause in expressionlist.
■ elsestatements − statements following Case Else that run
if the select expression does not match any clause in the
expressionlist of any of the Case statements.
Flow Diagram
Example
Module decisions
Sub Main()
‘local variable definition
Dim grade As Char
grade = “B”
83
Basic Computer Coding: Visual Basic
Select grade
Case “A”
[Link](“Excellent!”)
Case “B”, “C”
[Link](“Well done”)
Case “D”
[Link](“You passed”)
Case “F”
[Link](“Better try again”)
Case Else
[Link](“Invalid grade”)
End Select
[Link](“Your grade is {0}”, grade)
[Link]()
End Sub
End Module
When the above code is compiled and executed, it produces the
following result −
Well done
Your grade is B
3.2.6 Nested Select Case Statement
It is possible to have a select statement as part of the statement
sequence of an outer select statement. Even if the case constants
of the inner and outer select contain common values, no conflicts
will arise.
Example
Module decisions
Sub Main()
‘local variable definition
Dim a As Integer = 100
Dim b As Integer = 200
84
Control Statements and Tools
Select a
Case 100
[Link](“This is part of outer case “)
Select Case b
Case 200
[Link](“This is part of inner case “)
End Select
End Select
[Link](“Exact value of a is : {0}”, a)
[Link](“Exact value of b is : {0}”, b)
[Link]()
End Sub
End Module
When the above code is compiled and executed, it produces the
following result −
This is part of outer case
This is part of inner case
Exact value of a is : 100
Exact value of b is : 200
3.3 VISUAL BASIC CONTROL
An object is a type of user interface element you create on a Visual
Basic form by using a toolbox control. In fact, in Visual Basic, the
form itself is an object. Every Visual Basic control consists of three
important elements −
■ Properties which describe the object,
■ Methods cause an object to do something and
■ Events are what happens when an object does something.
85
Basic Computer Coding: Visual Basic
3.3.1 Control Properties
All the Visual Basic Objects can be moved,
resized or customized by setting their properties.
A property is a value or characteristic held by
a Visual Basic object, such as Caption or Fore
Color.
Properties can be set at design time by using
the Properties window or at run time by using
The origins of statements in the program code.
Visual Basic Object. Property = Value
are found in a
programming Where
language created ■ Object is the name of the object you’re
in 1964 by John customizing.
Kemeny and
Thomas Kurtz. ■ Property is the characteristic you want
BASIC (Beginners to change.
All-purpose ■ Value is the new property setting.
Symbolic Instruction
Code) was originally
an interpreted For example,
language that was
[Link] = “Hello”
designed to simplify
the programming You can set any of the form properties using
process and make Properties Window. Most of the properties can
programming more be set or read during application execution.
accessible to the
You can refer to Microsoft documentation for
world at large.
a complete list of properties associated with
different controls and restrictions applied to
them.
3.3.2 Control Methods
A method is a procedure created as a member of
a class and they cause an object to do something.
Methods are used to access or manipulate the
characteristics of an object or a variable. There
are mainly two categories of methods you will
use in your classes −
86
Control Statements and Tools
■ If you are using a control such as one
of those provided by the Toolbox, you
can call any of its public methods.
The requirements of such a method
depend on the class being used.
■ If none of the existing methods can
perform your desired task, you can
add a method to a class.
The MessageBox control has a method named Show, which
is called in the code snippet below −
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.
Object, ByVal e As [Link])
Handles [Link]
[Link](“Hello, World”)
End Sub
End Class
3.3.3 Control Events
An event is a signal that informs an application
Subroutine is a
that something important has occurred. For
sequence of program
example, when a user clicks a control on a form, instructions that
the form can raise a Click event and call a performs a specific
procedure that handles the event. There are task, packaged as a
various types of events associated with a Form unit.
like click, double click, close, load, resize, etc.
Following is the default structure of a form
Load event handler subroutine. You can see
this code by double clicking the code which
will give you a complete list of the all events
associated with Form control −
Private Sub Form1_Load(sender As Object, e
As EventArgs) Handles [Link]
87
Basic Computer Coding: Visual Basic
‘event handler code goes here
End Sub
Here, Handles [Link] indicates that Form1_Load() subroutine
handles Load event. Similar way, you can check stub code for click,
double click. If you want to initialize some variables like properties,
etc., then you will keep such code inside Form1_Load() subroutine.
Here, important point to note is the name of the event handler, which
is by default Form1_Load, but you can change this name based on
your naming convention you use in your application programming.
3.4. VISUAL BASIC CONTROL TOOLS
Visual Basic toolbox contains the controls which are used in the
form design. The controls are used by users to interact with the
applications.
The controls are categorized as
3.4.1 Intrinsic Controls
The built-in VB controls are called as intrinsic controls; these controls
are always available in the toolbox. The intrinsic controls are
■ Check box
■ Combo box
■ Command button
■ Data control
■ Dirlist
■ Drive list
■ Frame
■ Horizontal scrollbar
■ Vertical scrollbar
■ Image control
■ Label
■ Line
■ List box
■ Ole container
88
Control Statements and Tools
■ Option button
■ Picture box
■ Shape control
■ Text box, and
■ Timer.
3.4.2 ActiveX Controls
All the controls which exist as separate files with an extension.
ocx are called ActiveX controls. These controls are available in all
versions of the professional and enterprise visual basic editions.
The ActiveX controls are:
■ Common Dialog
■ DataCombo Box
■ DataList
■ MSFlexGrid
■ ADO Data Control
■ Animation Control
■ Communication control
■ CoolBar Control, etc.
3.4.3 Insertable Objects
In Visual Basic, it is possible to include other application objects in
a program and automate it, the applications are inserted as objects.
89
Basic Computer Coding: Visual Basic
ROLE MODEL
Thomas E. Kurtz
Thomas Eugene Kurtz (born February
22, 1928) is a retired Dartmouth
professor of mathematics and
computer scientist, who along with
his colleague John G. Kemeny set
in motion the then revolutionary
concept of making computers
as freely available to college students as library books were, by
implementing the concept of time-sharing at Dartmouth College. In
his mission to allow non-expert users to interact with the computer,
he co-developed the BASIC programming language (Beginners All-
purpose Symbolic Instruction Code) and the Dartmouth Time Sharing
System during 1963 to 1964.
A native of Oak Park Illinois, United States, Kurtz graduated from
Knox College in 1950, and was awarded a Ph.D. degree from Princeton
University in 1956, where his advisor was John Tukey, and joined
the Mathematics Department of Dartmouth College that same year,
where he taught statistics and numerical analysis.
In 1983, Kurtz and Kemeny co-founded a company called True BASIC,
Inc. to market True BASIC, an updated version of the language.
Kurtz has also served as Council Chairman and Trustee of EDUCOM,
as well as Trustee and Chairman of NERComP, and on the Pierce
Panel of the President’s Scientific Advisory Committee. Kurtz also
served on the steering committees for the CONDUIT project and
the CCUC conferences on instructional computing.
In 1974, the American Federation of Information Processing Societies
gave an award to Kurtz and Kemeny at the National Computer
Conference for their work on BASIC and time-sharing. In 1991, the
Computer Society honored Kurtz with the IEEE Computer Pioneer
Award and in 1994 he was inducted as a Fellowof the Association
for Computing Machinery.
90
Control Statements and Tools
Early Life and Education
In 1951, Kurtz’ first experience with computing came at the Summer
Session of the Institute for Numerical Analysis at University of
California, Los Angeles. His interests have included numerical
analysis, statistics, and computer science ever since. He graduated in
1950 when he obtained his bachelor’s degree majoring in mathematics
and in 1956, at the age of 28, he went on to acquire his PhD from
Princeton University. His thesis was on a problem of multiple
comparisons in mathematical statistics. Kurtz composed his first
computer program in 1951 while working with computers at UCLA
in the institute of numerical analysis. He performed this feat just
after finishing grad school and one year into his tuition at Princeton
University.
Dartmouth
In 1963 to 1964, Kurtz and Kemeny developed the first version of
the Dartmouth Time-Sharing System, a time-sharing system for
university use, and the BASIC language.
From 1966 to 1975, Kurtz served as Director of the Kiewit Computation
Center at Dartmouth, and from 1975 to 1978, Director of the Office
of Academic Computing. From 1980 to 1988 Kurtz was Director of
the Computer and Information Systems program at Dartmouth, a
ground-breaking multidisciplinary graduate program to develop IS
leaders for industry. Subsequently, Kurtz returned to teaching full-
time as a Professor of Mathematics, with an emphasis on statistics
and computer science.
BASIC
As part of the Dartmouth Time-Sharing System, Kemeny and Kurtz
created the BASIC programming language. The very first BASIC
program ran on May 1, 1964 at 4 a.m., and neither Kemeny nor
Kurtz thought of this as a start to something grand. They merely
hoped it would help students learn something about the computers
they were using. The pair made certain that their invention was
dispersed to the public straight away and made no real money from
it. Dartmouth Collegecopyrighted BASIC; however it made BASIC
available and free to anyone wanting to use it. The name for the
91
Basic Computer Coding: Visual Basic
language originated from Kurtz’s wish to have a simple acronym
that meant something as well. Kurtz states that, “We wanted a word
that was simple but not simple-minded, and BASIC was that one.”
BASIC along with the books published on it earned a lot of positive
feedback, for example: “This second edition of Basic Programming
gives a thorough description of BASIC, which is useful not only for
the beginner, but also for the more experienced programmer.”; “
My overall evaluation of BASIC programming is that it is ideal for
the individual who wishes to program with a minimum of effort
and of equal value for group or classroom instruction.”
The theme that BASIC was for the average computer user is stressed
by Kurtz. In an open letter he reiterates upon past statements
that BASIC was invented to give students a simple programming
language that was easy to learn, as all the current languages of the
time were dedicated to professionals. He then went on to say that
BASIC was for people who did not want to dedicate their lives to
programming. The repetition of this idea by Kurtz accentuates that
even through all of his success the language he wrote would remain
implemented for the masses and not just specialists.
BASIC standards were created in the 1980s for the ECMA, and ANSI
with their versions being released in 1986 and 1987 respectively.
BASIC popularity skyrocketed in 1975 after a pair of youngsters in
a Harvard dormitory, Bill Gates and Paul Allen, created a version
of BASIC that was viable on one of the earliest personal computers.
Gates and Allen’s version became the most prominent iterations of
BASIC.
Influence
The road to BASIC itself was a long one. Kemeny and Kurtz had
forged DARSIMCO – Dartmouth Simplified Code – Dartmouth’s
inaugural attempt at making a computing language in 1956;
however DARSIMCO soon became obsolete when the language
FORTRAN manifested itself. In 1962 Kemeny and a Dartmouth
undergraduate, Sidney Marshall, created the language DOPE,
Dartmouth Oversimplified Programming Experiment, which was
a direct predecessor of BASIC. DOPE itself was little used, and
Kurtz preferred trying to implement successful languages such
as FORTRAN and ALGOL. Kurtz’s experience with Dartmouth
92
Control Statements and Tools
ALGOL 30 for the LGP-30 convinced him that devising subsets of
these languages was not quite practical, and this led him to adopt
Kemeny’s notion of creating a new language entirely.
Critics
Although BASIC was widely regarded as a success, many computing
professionals thought it was a poor choice for larger and more
complicated programs. Larger programs became confusing and
messy when they used the “GO TO” statement to jump from one
line of a program to another. A further criticism of the original
language was that it was unstructured, which made it difficult to
split programs into separate parts to improve readability. BASIC not
being structured also hindered the ability to debug and modify parts
of the code, and this limited its use by larger companies. Hence it
largely remained a language used for only smaller programs.
True BASIC
In 1983, in response to a proliferation of “Street BASICs,” a group
of graduating Dartmouth students persuaded Kemeny and Kurtz
to offer the Dartmouth version of the language as a commercial
product. The first offering of their company, True Basic, Inc., was
based on Dartmouth BASIC 7, which featured modern programming
constructs such as “IF..THEN..ELSE, DO..LOOP and EXIT DO”. The
company described its product as “Simple. Elegant. Powerful. True
BASIC.“ Upon Kemeny’s advice, True BASIC was not limited to a
single OS or computer system. “Today versions of True BASIC are
available for DOS, Mac OS, Windows, Unix, and Linux systems”.
When Kurtz retired from Dartmouth College in 1993, he continued
to develop and maintain True Basic.
93
Basic Computer Coding: Visual Basic
SUMMARY
■ A statement is a complete instruction in Visual Basic
programs. It may contain keywords, operators, variables,
literal values, constants and expressions.
■ The declaration statements are used to name and define
procedures, variables, properties, arrays, and constants.
When you declare a programming element, you can also
define its data type, access level, and scope.
■ An executable statement performs an action. Statements
calling a procedure, branching to another place in the
code, looping through several statements, or evaluating
an expression are executable statements. An assignment
statement is a special case of an executable statement.
■ Decision making structures require that the programmer
specify one or more conditions to be evaluated or tested
by the program, along with a statement or statements to
be executed if the condition is determined to be true, and
optionally, other statements to be executed if the condition
is determined to be false.
■ An object is a type of user interface element you create on
a Visual Basic form by using a toolbox control. In fact, in
Visual Basic, the form itself is an object.
■ All the Visual Basic Objects can be moved, resized or
customized by setting their properties. A property is a
value or characteristic held by a Visual Basic object, such
as Caption or Fore Color.
■ A method is a procedure created as a member of a class
and they cause an object to do something. Methods are
used to access or manipulate the characteristics of an object
or a variable.
■ An event is a signal that informs an application that
something important has occurred. For example, when a
user clicks a control on a form, the form can raise a Click
event and call a procedure that handles the event. There
are various types of events associated with a Form like
click, double click, close, load, resize, etc.
94
Control Statements and Tools
■ Visual Basic toolbox contains the controls which are used in
the form design. The controls are used by users to interact
with the applications.
■ The built-in VB controls are called as intrinsic controls;
these controls are always available in the toolbox.
■ All the controls which exist as separate files with an
[Link] are called ActiveX controls. These controls are
available in all versions of the professional and enterprise
visual basic editions.
95
Basic Computer Coding: Visual Basic
KNOWLEDGE CHECK
1. Which of the following statement declares the name of a class
and introduces the definition of the variables, properties,
events, and procedures that the class comprises?
a. Dim
b. Const
c. Enum
d. Class
2. Which of the following statement declares the name of a
property, and the property procedures used to store and
retrieve the value of the property?
a. Sub
b. Declare
c. Operator
d. Property
3. Which of the following statement declares the name,
parameters, and code that define a Sub procedure?
a. Sub
b. Declare
c. Operator
d. Property
4. Which of the following statement declares an enumeration
and defines the values of its members?
a. Dim
b. Const
c. Enum
d. Class
5. Which of the following directive helps in collapsing and
hiding sections of code in Visual Basic files?
a. #Const
b. #Region
96
Control Statements and Tools
c. #ExternalSource
d. #If...Then...#Else
REVIEW QUESTIONS
1. Discuss about declaration statements and executable
statements.
2. What do you understand by decision making structures?
3. What is visual basic control?
4. Describe the visual basic control tools.
5. Discuss about intrinsic controls and ActiveX controls.
Check Your Result
1. (d) 2. (d) 3. (a) 4. (c) 5. (b)
97
Basic Computer Coding: Visual Basic
REFERENCES
1. Dan, Brust, (14 September 2015). “Installing Visual Basic/
Studio 6 on Windows 10”. [Link].
2. George, Mack. “History of Visual Basic”. June 2002.
George Mack, 3rd edition, Copyright June 2002. Retrieved
10 April 2014.
3. [Link]
samplechapter/[Link]
4. [Link]
visual-basic-control-tools-3
5. [Link]
[Link]
6. [Link]
htm
7. ISpliter. “Visual Basic 6.0: A giant more powerful than
ever”. [Link]. Retrieved 3 April 2014.
8. Jeff, Martin. “Visual Basic 6 Renewed to Run on Windows
8”. INFOQ. Retrieved 5 April 2014.
9. Platt, David (2012-06-01). “Don’t Get Me Started – The
Silent Majority: Why Visual Basic 6 Still Thrives”. MSDN
Magazine. Retrieved 2012-06-09.
10. PSC. “Visual Basic 6.0 third party components for modern
standards (a review)”. Planet Source Code. Retrieved 4
April 2014.
11. Richard, Grigonis. “Where Is the Successor to Visual
Basic?”. Thursday, 27 Mar 2014 03:20 PM. INFOQ.
Retrieved 8 April 2014.
98
CHAPTER 4
MENU BAR AND
DIALOG BOXES
“That›s the thing about people who think they hate computers. What they really hate
is lousy programmers.”
―Larry Niven
Learning Objectives
After studying this chapter, you will be able to:
■ Understanding the menu bar
■ Explain the dialog boxes
Basic Computer Coding: Visual Basic
4.1 MENU BAR
The menu bar is the standard feature of most Windows applications.
The main purpose of the menus is for easy navigation and control
of an application. Some of the most common menu items are File,
Edit, View, Tools, Help and more. Each item on the main menu bar
also provides a list of options in the form of a pull-down menu.
When you create a Visual Basic 6 program, you need not include
as many menu items as a full-fledged Windows application. What
you need is to include those menu items that can improve the ease
of usage by the user. There are two ways to add menus to your
application, using the Visual Basic’s Application Wizard and or the
menu editor.
4.1.1 Adding Menu Bar Using Visual Basic’s
Application Wizard
The easiest way to add a menu bar to your application is by using
Visual Basic’s Application Wizard. This wizard allows the user to
insert fully customized standard Windows menu into his or her
application. To start using Visual Basic’s Application Wizard, click
on the Application Wizard icon at the Visual Basic new project
dialog box, as shown in Figure 1:
Figure 1: New Project Window
100
Menu Bar and Dialog Boxes
When you click on the VB Application wizard, the introduction
dialog box will appear, as shown in Figure 2. As you are not loading
any default setting, just click on the Next button.
Figure 2
After clicking the Next button, the interface type dialog box will be
displayed, as shown in Figure 3. There are three choices of interface
available for your project. As we currently not creating a Multiple
Document Interface (MDI), we choose Single Document Interface
(SDI). You can also type the project name in the textbox, here I am
using MyFirstMenu.
Figure 3
101
Basic Computer Coding: Visual Basic
Clicking the Next button will bring up a list of menus and submenus
that you can add them to your application. Check to select a menu
item and uncheck to unselect a menu item as shown in Figure 4.
Let say we choose all the menus and click next, then you will get
an interface comprises File, Edit, View and Help menus, as shown
in Figure 5
Figure 4
Figure 5
102
Menu Bar and Dialog Boxes
When you click on any menu item, a list of drop-down submenu
items will be displayed. For example, if you click on the File menu,
the list of submenu items such as New, Open, Save, Save As and
more will be displayed, as shown in Figure 6
Figure 6:
Clicking on any of the dropped down menu item will show the
code associated with it, and this is where you can modify the code
to suit your programming needs. For example, clicking on the item
Open will reveal the following code:
Figure 7:
103
Basic Computer Coding: Visual Basic
Now, I will show you how to modify the code in order to open a
graphic file and display it in an image box. For this program, you
have to insert a Image box into the form. Next add the following
lines so that the user can open graphic files of different formats.
Filter = “Bitmaps(*.BMP) |*.BMP|Metafiles(*.WMF) |*. WMF|Jpeg
Files(*.jpg)|*.jpg|GIF Files(*.gif)|*.gif|Icon Files(*.ico)|*.ico|All
Files(*.*)|*.*”.
Then, you need to load the image into the Image box with the
following code:
[Link] = LoadPicture(.FileName)
Also set the Stretch property of the Image box to true so that the image
loaded can resize by itself. Please note that each menu item is a special
control, so it has a name too. The name for the menu File in this example
is mnuFileOpen.
The Code
Private Sub mnuFileOpen_Click()
Dim sFile As String
With dlgCommonDialog
.DialogTitle = “Open”
.CancelError = False
‘Set the flags and attributes of the common dialog control
.Filter = “Bitmaps(*.BMP)|*.BMP|Metafiles(*.WMF)|*. WMF|Jpeg
Files(*.jpg)|*.jpg|GIF Files(*.gif)|*.gif|Icon Files(*.ico)|*.ico|All
Files(*.*)|*.*”
.ShowOpen
[Link] = LoadPicture(.FileName)
If Len(.FileName) = 0 Then
Exit Sub
End If
sFile = .FileName
End With
End Sub
104
Menu Bar and Dialog Boxes
When you run the program and click on the
File menu and then the submenu Open, the File menu is a graphical
following Open dialog box will be displayed, control element
formerly common to
where you can look for graphic files of various
most file-handling
formats to load it into the image box. computer programs,
but more recently often
replaced by a toolbar or
ribbon.
Figure 8:
For example, selecting the jpeg file will allow
you to choose the images of jpeg format, as
shown in Figure 9.
Figure 9:
105
Basic Computer Coding: Visual Basic
Clicking on the particular picture will load it into the image box,
as shown in Figure 10
Figure 10
4.1.2 Adding Menu Bar Using Menu Editor
To start adding menu items to your application, open an existing
project or start a new project, then click on Tools in the menu bar
of the Visual Basic IDE and select Menu Editor. When you click on
the Menu Editor, the Menu Editor dialog will appear. In the Menu
Editor dialog, key in the first item File in the caption text box.
You can use the ampersand (&) sign in front of F so that F will be
underlined when it appears in the menu, and F will become the hot
key to initiate the action under this item by pressing the Alt key
and the letter F. After typing &File in the Caption text box, move
to the name textbox to enter the name for this menu item, you can
type in muffle here. Now, click the Next button and the menu item
&File will move into the empty space, as shown in Figure 11:
Figure 11:
106
Menu Bar and Dialog Boxes
You can then add in other menu items on the menu bar by following
the same procedure, as shown in Figure 12:
Figure 12:
When you click Ok, the menu items will be shown on the menu
bar of the form.
Figure 13
107
Basic Computer Coding: Visual Basic
Now, you may proceed to add the sub menus.
In the Menu Editor, click on the Insert button
between File and Exit and then click the right
Arrow keys are
buttons on a computer arrow key, and the dotted line will appear.
keyboard that are This shows the second level of the menu, or
either programmed or the submenu. Now key in the caption and the
designated to move the
cursor in a specified
name. Repeat the same procedure to add other
direction. submenu items. Here, we are adding New,
Open, Save, Save As and Exit.
Figure 14:
Figure 15:
108
Menu Bar and Dialog Boxes
Now click the OK button and go back to your form. You can see
the dropped down submenus when you click on the item File, as
shown.
Figure 16:
Finally, you can enter the code by clicking on any of the submenu
items.
4.2 DIALOG BOXES
An application’s object is programmatically referred to as a parent
when it can host, hold, or carry other objects. For this reason, such
a window is also referred to as a container. Although the first object
that comes in mind is the form, this is not the only window that
can act as parent. This means that, in your application programming
adventure, you will get acquainted with various types of containers
and they are meant to play different roles.
In some cases, two or more containers can be used to implement
the same functionality. In some other cases, your choice will be
narrowed based on your goal.
The most common and the most widely used container is the form.
In an application, a form can be configured to display like a regular
dialog box, to become a Single Document Interface (SDI) or to
participate in a Multiple Document Interface (MDI) application.
109
Basic Computer Coding: Visual Basic
As mentioned already, there are two categories
Multiple document of controls: parents and children:
interface (MDI) is a ■ Parent: The child controls are
graphical user interface positioned on a parent. To keep track
in which multiple
windows reside under a of its children, a parent control has the
single parent window. Controls property. To create a control
inside of a parent, a child control is
added to the Controls property of
the parent using the [Link]()
method. When a parent control is
created, it «gives life» to other windows
that can depend on it. When a parent is
destroyed, it also destroys its children.
A parent control «carries», «holds»,
or hosts the controls positioned on it.
When a parent is created, made active,
or made visible, it gives existence and
visibility to its controls. When a parent
gets hidden, it also hides its controls.
If a parent moves, it moves with its
children. The controls keep their
.NET Framework
positions and dimensions inside the
is a software
framework developed parent. The .NET Framework provides
by Microsoft that various parent controls.
runs primarily on
■ Child: A window is referred to as child
Microsoft Windows.
when its existence, its visibility, and its
availability depend on another window
referred to as its parent. Except for the
forms, all of the Windows controls you
will use in your applications are child
controls and they must be parented
by another control.
A child window can be a parent of another
control. For example, the Standard toolbar of
Visual Studio 2005 is the parent of the buttons
on it. If you close or hide the toolbar, its children
disappear. At the same time, the toolbar is a
child of the application’s form. If you close the
application, the toolbar disappears, along with
110
Menu Bar and Dialog Boxes
its own children. In this example, the toolbar is a child of the form
but is a parent to its buttons.
4.2.1 Using a Parent Control
The type of container you want to use dictates how you acquire
that container and add it to your application. Parent controls are
somewhat divided in two broad categories: primary parents and
intermediate parents. Once you have spent time with them, you
will decide which one and when to use a particular control.
The primary type of control parenting you will use is a form. This
is used as the platform for other controls, including other containers.
Therefore, when you start your application, you first decide on the
type of application. If you create a Windows Forms application, it
gets automatically equipped with a form on which you can add
child controls. When the application executes, it can present its
contents to the user:
The second category of parents you will encounter qualify as
intermediate. Theses containers cannot be the base of an application
as does the form. These parents must be positioned on another
parent first, then they can host their own children. An example
of such a parent is the property page also called tab control. This
control must be hosted by a form or dialog box. Here is an example
of a property sheet (dialog box) that hosts three property pages
(tab controls) and each property page hosts its own child controls:
111
Basic Computer Coding: Visual Basic
Another type of intermediary container is the toolbar that is usually
used to host various buttons.
4.2.2 Dialog Box Creation
To create a dialog box, you start with a form, which you can get
by creating a Windows Application or deriving a class from Form.
Here is an example:
Imports [Link]
Imports [Link]
Module Exercise
Public Class Starter
Inherits Form
Dim components As [Link]
Public Sub New()
InitializeComponent()
End Sub
Public Sub InitializeComponent()
Text = “Domain Configuration”
Width = 320
Height = 150
112
Menu Bar and Dialog Boxes
Location = New Point(140, 100)
StartPosition = [Link]
End Sub
End Class
Function Main() As Integer
Dim frmStart As Starter = New Starter
[Link](frmStart)
Return 0
End Function
End Module
This would produce:
4.2.3 Characteristics of Dialog Boxes
The Border Style of a Dialog Box
There are a few actions you should perform on a form to transform it
into a dialog box; but normally, these are only suggestions, not rules.
Based on the Microsoft Windows design and standards, to create
a dialog box, you should set a form’s FormBorderStyle property to
FixedDialog. Setting this property changes the borders of the form
to the standard borders of a dialog box (the border of a dialog box
113
Basic Computer Coding: Visual Basic
is thinner than that of a regular form). You can
set this characteristic in the Properties window
or programmatically. Here is an example:
Public Sub InitializeComponent()
Text = “Domain Configuration”
Width = 320
Height = 150
Location = New Point(140, 100)
StartPosition = [Link]
Before the
F o r m B o r d e r S t y l e = Wi n d o w s . F o r m s .
computer mouse
[Link]
was widespread,
arrow keys were End Sub
the primary way of
moving a cursor on
screen. Mouse keys
is a feature that The Minimize and Maximize Boxes
allows controlling a
mouse cursor with Besides taking care of the border, you should
arrow keys instead. also set both the MinimizeBox and the
MaximizeBox properties to False. This causes
the window to display only the system Close
button. You can set these characteristics in the
Properties window or programmatically. Here
is an example:
Public Sub InitializeComponent()
Text = “Domain Configuration”
Width = 320
Height = 150
Location = New Point(140, 100)
StartPosition = [Link]
F o r m B o r d e r S t y l e = Wi n d o w s . F o r m s .
[Link]
MinimizeBox = False
MaximizeBox = False
End Sub
114
Menu Bar and Dialog Boxes
This would produce:
Configuring a Dialog Box
1. To transform the PropertyEditor form into a dialog box,
in the Properties window, change its characteristics as
follows:
FormBorderStyle: FixedDialog
StartPosition: CenterParent
MinimizeBox: False
MaximizeBox: False
ShowInTaskbar: False
2. Design the dialog box as follows:
Control Text Name
Label Property Type:
TextBox TxtPropertyType
115
Basic Computer Coding: Visual Basic
Button Cancel BtnCancel
Label Bedrooms:
TextBox TxtBedrooms
Button OK BtnOK
Label Bathrooms:
TextBox TxtBatrooms
Label Monthly Rent:
TextBox TxtMonthlyRent
Closing a Dialog Box
You should provide a way for the user to close
the dialog box. A dialog box should have at
least one button labeled OK. This button allows
the user to acknowledge the message of the
dialog box and close it by clicking the button.
Remember
If the user press
Accepting an Action
Enter, the dialog Often the user will be presented with various
box should also be options on a dialog box and may be asked
closed as if the OK to make a decision on the available controls.
button was clicked. Most of the time, if you are creating such a
dialog box, besides the OK button, it should
also have a Cancel button. The OK button
should be the default so that if the user presses
Enter, the dialog box would be closed as if the
user had clicked OK. Clicking OK or pressing
Enter would indicate that, if the user had
made changes on the controls of the dialog
box, those changes would be acknowledged
and kept when the dialog box is closed and
usually the changed values of the control would
be transferred to another dialog box or form.
Keep in mind that you are responsible for
implementing this functionality.
116
Menu Bar and Dialog Boxes
To fulfill this functionality of the OK button, after adding it to a
dialog box (or form), open the Accept Button combo box in the
Properties window for the form and select the name of the button.
Canceling an Action
The Cancel button is used to allow the user to dismiss whatever
changes would have been made on the controls of the dialog box.
The dialog box should also be configured so that if the user presses
Esc, the dialog box would be closed as if the user had clicked Cancel.
To fulfill this functionality of the Cancel button, after adding it to
a dialog box (or form), open the Cancel Button combo box in the
Properties window for the form and select the name of the button.
Besides the OK and the Cancel buttons, a dialog box can be created
with additional buttons such as Finish or Help, etc. It depends on its
role and the decision is made by the application developer.
The Help Button
Besides the system Close button, if you are planning to provide help
on a dialog box, you can equip it with a Help button. To support
this, the Form class is equipped with a Boolean property named Help
Button. The default value of this property is false. In the Properties
window, you can set it to True. If you are programmatically creating
the dialog box, you can access this property and set its value to
true. Here is an example:
Public Sub InitializeComponent()
Text = “Domain Configuration”
Width = 320
Height = 150
Location = New Point(140, 100)
StartPosition = [Link]
FormBorderStyle = [Link].
FixedDialog
117
Basic Computer Coding: Visual Basic
MinimizeBox = False
MaximizeBox = False
HelpButton = True
End Sub
This would produce:
When the user clicks the help button, the mouse cursor becomes
equipped with a question mark. Here is an example:
You can then write code so that, when the user clicks a control on
the dialog box, some guiding help is provided as a tool tip.
118
Menu Bar and Dialog Boxes
4.2.4 Modal and Modeless Dialog Boxes
Modal Dialog Boxes
There are two types of dialog boxes: modal and modeless.
A Modal dialog box is one that the user must first close in order to
have access to any other framed window or dialog box of the same
application. One of the scenarios in which you use a dialog box is
to create an application that is centered around one. In this case, if
either there is no other form or dialog box in your application or
all the other forms or dialog boxes depend on this central dialog
box, it must be created as modal. Such an application is referred
to as dialog-based.
Some applications require various dialog boxes to complete their
functionality. When in case, you may need to call one dialog box
from another and display it as modal. Here is an example:
The Date and Time dialog box of WordPad is modal: when it is
displaying, the user cannot use any other part of WordPad unless
he or she closes this object first
After creating a dialog used as an addition to an existing form or
an existing dialog box, to call it as modal, use the Show Dialog()
method.
119
Basic Computer Coding: Visual Basic
Modeless Dialog Boxes
A dialog box is referred to as modeless if
the user does not have to close it in order to
continue using the application that owns the
dialog box. A modeless dialog box has the
following characteristics
■ It has a thin border
■ It can be neither minimized nor
maximized. This means that it is not
equipped with the Minimize or the
Maximize buttons
■ It is not represented on the taskbar
with a button
■ It must provide a way for the user
to close it
Here is an example:
WordPad is a basic The Find (and the Replace) dialog box of
word processor that is WordPad (also the Find and the Replace dialog
included with almost boxes of most applications) is an example of a
all versions of Microsoft
Windows from
modeless dialog box. If it is opened, the user
Windows 95 onwards. does not have to close it in order to use the
application or the document in the background.
120
Menu Bar and Dialog Boxes
Since the modeless dialog box does not display its button on the
task bar, the user should know that the dialog box is opened. To
make the presence of a modeless dialog box obvious to the user,
it typically displays on top of its host application until the user
closes it.
A modeless dialog box is created from a form but it should look
like a regular dialog box or a tool window. Therefore, to create
a modeless dialog box, set the FormBorderStyle property to an
appropriate value such as FixedSingle, FixedToolWindow, Sizable or
SizableToolWindow. Also, set its ShowInTaskbar property to False.
After creating the dialog box, to display it as modeless, call the Show
() method. The fundamental difference between the Show Dialog
() and the Show() methods is that the former displays a modal
dialog box, which makes sure that the called dialog box cannot go
in the background of the main application. By contrast, the Show()
method only calls the dialog box every time it is requested. For this
reason, it is up to you to make sure that the modeless dialog box
always remains on top of the application. This is easily taken care
of by setting the Boolean TopMost property of the form to True.
There are two main ways a normal modeless dialog box can be
dismissed:
■ If the user has finished using it, he or she can close it and
recall it at will
■ When the form or application that owns the modeless dialog
box is closed, the form or application closes the modeless
dialog if it is opened; this means that you don’t need to
find out whether a modeless dialog box is still opened
when the application is being destroyed: either the user or
the application itself will take care of closing it
An Application with Various Forms or Dialog boxes
When you create a Windows Forms Application, the starting form is
made available to you. If one form is not enough for your application,
you can add as many as necessary. To add (or to create) a (new)
form, you have various options:
■ On the main menu, you can click Project -> Add New Item...
■ On the main menu, you can click File -> Add New Item...
121
Basic Computer Coding: Visual Basic
■ In Solution Explorer, you can right-click the name of the
project, position the mouse on Add, and click Add New
Item...
In the Add New Item dialog box and in the middle section, click
Window Form (.NET), provide a name in the Name edit box then
click Open.
If your application is using various forms and you want to display
a particular one at design time:
■ In the Forms Designer, you can click the tab that corresponds
to the desired form and that has [Design]
■ On the main menu, you can click Window and click the
name of the form in the list under Close All Documents
■ In Solution Explorer, expand the Header Files node if
necessary and double-click the name of the desired form
that has the .h extension
If you visually add two (or more) forms to your application, you
may need to link them, allow one to call the other. To do this, in
the top section of the file, type #include followed by the name of
the header file in which the form was defined. In the section where
you want to access the form, declare a handle to the class of the
form and use the new operator to allocate memory for it. To display
the other form, you can call its Show () method.
122
Menu Bar and Dialog Boxes
SUMMARY
■ The menu bar is the standard feature of most Windows
applications. The main purpose of the menus is for easy
navigation and control of an application.
■ The easiest way to add a menu bar to your application is
by using Visual Basic’s Application Wizard.
■ To start adding menu items to your application, open an
existing project or start a new project, then click on Tools
in the menu bar of the Visual Basic IDE and select Menu
Editor.
■ An application’s object is programmatically referred to as
a parent when it can host, hold, or carry other objects.
■ The type of container you want to use dictates how you
acquire that container and add it to your application.
■ To create a dialog box, you start with a form, which you
can get by creating a Windows Application or deriving a
class from Form.
■ There are a few actions you should perform on a form to
transform it into a dialog box; but normally, these are only
suggestions, not rules.
■ Besides taking care of the border, you should also set both
the MinimizeBox and the MaximizeBox properties to False.
■ Often the user will be presented with various options on
a dialog box and may be asked to make a decision on the
available controls.
■ A Modal dialog box is one that the user must first close
in order to have access to any other framed window or
dialog box of the same application.
123
Basic Computer Coding: Visual Basic
KNOWLEDGE CHECK
1. What is the name of the control for putting menus on a
form?
a. FormMenu
b. MainMenu
c. MenuForm
d. MenuControl
2. A GUI:
a. uses buttons, menus, and icons.
b. should be easy for a user to manipulate.
c. stands for Graphic Use Interaction.
d. Both a and b.
3. Why are standard dialog boxes used?
a. They are easy to create.
b. They provide functionality familiar to users.
c. Developers can create their own versions of Dialog
boxes.
d. Both a and b.
4. How are dialog boxes implemented in a program?
a. A dialog box is generated programmatically.
b. A dialog control is placed in the component tray.
c. A dialog control is placed on the form.
d. Both a and b.
5. Which is not a feature of a GUI that makes learning a
program easy for users?
a. Online help
b. Detailed key strokes and commands
c. WYSIWYG formatting
d. Dialog boxes
124
Menu Bar and Dialog Boxes
REVIEW QUESTIONS
1. How to Return Value of a Message Box?
2. Write a program Default Button of a Message Box.
3. Write a program Icon of a Message Box.
4. Write a program Caption of a Message Box.
5. Write a program Buttons of a Message Box.
Check Your Result
1. (b) 2. (d) 3. (d) 4. (d) 5. (b)
125
Basic Computer Coding: Visual Basic
REFERENCES
1. Bardohl, Roswitha, Ribeiro Leila, towards a Compositional
Approach to Define Graphical Animation of Software
Applications.
2. Casella, Giovanni, Gennaro Costagliola, Vincenzo
Deufemia, Maurizio Martelli, Viviana Mascardi, An Agent-
Based Framework for Context-Driven Interpretation of
Symbols in Diagrammatic Sketches.
3. Cheesman, John and John Daniels. UML Components: A
Simple Process for Specifying Component-Based Software.
Addison-Wesley, 2001.
4. Cox, Philip T, Visual Programming Languages. In in
Encyclopedia of Computer Science and Engineering, B.W.
Wah (Ed.), John Wiley & Sons Inc., Hoboken, (June 2008).
5. Gudgin, Martin. Essential IDL: Interface Design for COM.
Reading, MA: Addison-Wesley, 2001.
6. [Link]
7. Kim, Chul H, John Hosking and John Grundy, A Suite
of Visual Languages for Statistical Survey Specification.
8. Kindborg, Mikael, How Children Understand Concurrent
Comics: Experiences from LOFI and HIFI Prototypes.
In 2001 IEEE Symposia on Human-Centric Computing
Languages and Environments, Stresa, Italy, September
2001.
9. Kong, Jun, Kang Zhang, Graph-based Consistency
Checking in Spatial Information Systems. In 2003 IEEE
Symposium on Visual Languages and Formal Methods,
Auckland, New Zealand, October 2003.
10. Störrle, Harald, VMQL: A Generic Visual Model Query
Language. In IEEE Symposium on Visual Languages/
Human Centric Computing, Corvallis, Oregon, September
2009.
126
CHAPTER 5
EXECUTING THE
DEBUGGING
“If debugging is the process of removing software bugs, then programming must be
the process of putting them in.”
―Edsger Dijkstra
Learning Objectives
After studying this chapter, you will be able to:
■ Describe the error types
■ Explain the debugging visual basic programs
■ Describe the debugging tools
■ Understand the error handling
Basic Computer Coding: Visual Basic
INTRODUCTION
Errors, bugs, and therefore debugging are a part of life for a
programmer. As the saying goes, if you haven’t made any mistakes,
then you aren’t trying hard enough. Dealing with errors actually
involves two very different processes: error handling and debugging.
Error handling is a combination of coding and methodology that
allows your program to anticipate user and other errors. It allows
you to create a robust program. In general, error handling should
be part of your overall program plan, so that when you have an
error-free script, nothing is going to bring it to a screeching halt.
With some sturdy error handling in place, your program should be
able to keep running despite all the misuse that your users can—and
certainly will—throw at it.
5.1 ERROR TYPES
In writing VB software, three types of errors can occur:
■ Syntax errors (Compile errors)
■ Run-time errors
■ Logic errors
5.1.1 Syntax Errors
These are grammatical errors in the formulation of statements and
are picked up by the interpreter while you are typing in the code
(providing the syntax checking option - under environment options
- is set to yes). In the example below the syntax of the assignment
statement is incorrect - the property of Label1 is missing (the
statement should be [Link] = current_day). Visual Basic
has signalled this error at design time by placing the cursor at the
point of omission and displaying a pop up error message.
128
Executing the Debugging
5.1.2 Run-time Errors
These are errors that cannot be detected until the program is running.
The syntax of the statements is correct, but on execution they cause
a situation to arise that results in a crash or an undefined value.
Error handlers can be used to trap such errors and deal with them.
Examples of run-time errors are attempted division by zero or trying
to access a non-existent object as in the example below (where
Label2 has not been created).
129
Basic Computer Coding: Visual Basic
5.1.3 Logic Errors
These are errors that cause the program to
behave incorrectly. They generally arise through
failure on the part of the programmer to arrive
at a correct algorithm for the task. Typical
problems might be incorrect ordering of
statements, failure to initialize or reinitialize
a variable, assignment to an incorrect variable,
use of ‘<’ instead of ‘<=’, use of ‘and’ instead
of ‘or’, or omission of a crucial step in the
processing. Logic errors may lurk in a program
even when it appears to work - they may only
surface under certain conditions. This is why
The terms “bug” careful testing is so important.
and “debugging”
are popularly
attributed to
Admiral Grace
5.2 DEBUGGING VISUAL BASIC
Hopper in the
1940s.
PROGRAMS
We now consider the search for, and elimination
of, logic errors. These are errors that don’t
prevent an application from running, but cause
incorrect or unexpected results. Visual Basic
provides an excellent set of debugging tools to
aid in this search. Debugging a code is an art,
not a science. There are no prescribed processes
that you can follow to eliminate all logic errors
in your program. The usual approach is to
eliminate them as they are discovered.
What we’ll do here is present the debugging
tools available in the Visual Basic environment
(several of which appear as buttons on the
toolbar) and describe their use with an example.
You, as the program designer, should select the
debugging approach and tools you feel most
comfortable with.
130
Executing the Debugging
The interface between your application and
the debugging tools is via three different
debug windows: the Immediate Window, the
Locals Window, and the Watch Window. These
windows can be accessed from the View menu
(the Immediate Window can be accessed by
pressing Ctrl+G). Or, they can be selected from A toolbar is a graphical
the Debug Toolbar (accessed using the Toolbars control element on
option under the View menu): which on-screen buttons,
icons, menus, or other
input or output elements
are placed.
All debugging using the debug windows is done
when your application is in break mode. You
can enter break mode by setting breakpoints,
pressing Ctrl+Break, or the program will go into
break mode if it encounters an untrapped error
or a Stop statement. Once in break mode, the
debug windows and other tools can be used to:
■ Determine values of variables
■ Set breakpoints
■ Set watch variables and expressions
■ Manually control the application
■ Determine which procedures have
been called
■ Change the values of variables and
properties
131
Basic Computer Coding: Visual Basic
Debugging Example
1. Unlike other examples, we’ll do this one as
a group. It will be used to demonstrate use
of the debugging tools.
2. The example simply has a form with a single
command button. The button is used to
execute some code. We won’t be real careful
about proper naming conventions and such
in this example.
3. The code attached to this button’s Click event
is a simple loop that evaluates a function at
several values.
Private Sub Command1_Click()
Dim X As Integer, Y As Integer
X=0
Do
Y = Fcn(X)
X=X+1
Loop While X <= 20
End Sub
This code begins with an X value of 0 and computes the Y
value using the general integer function Fcn. It then increments
X by 1 and repeats the Loop. It continues looping While X is
less than or equal to 20. The function Fcn is computed using:
Function Fcn(X As Integer) As Integer
Fcn = CInt(0.1 * X ^ 2)
End Function
132
Executing the Debugging
Admittedly, this code doesn’t do much, especially without any
output, but it makes a good example for looking at debugger use.
Set up the application and get ready to try debugging.
5.3 DEBUGGING TOOLS
There are several debugging tools available
for use in Visual Basic. Access to these tools is
provided with both menu options and buttons
on the Debug toolbar. These tools include
breakpoints, watch points, calls, step into, step
over, and step out. The simplest tool is the
use of direct prints to the immediate window.
Printing to the Immediate Window:
You can print directly to the immediate window A logic error is a bug
while an application is running. Sometimes, in a program that
this is all the debugging you may need. A few causes it to operate
carefully placed print statements can sometimes incorrectly, but not to
terminate abnormally
clear up all logic errors, especially in small (or crash). A logic error
applications. produces unintended
To print to the immediate window, use the or undesired output or
other behavior, although
Print method: it may not immediately
[Link] Example: be recognized as such.
■ Place the following statement in the
Command1_Click procedure after the
line calling the general procedure Fcn:
[Link] X; Y
and run the application.
■ Examine the immediate window. Note
how, at each iteration of the loop, the
program prints the value of X and
Y. You could use this information to
make sure X is incrementing correctly
and that Y values look acceptable.
133
Basic Computer Coding: Visual Basic
■ Remove the [Link] statement.
Breakpoints:
In the above examples, the program ran to completion before we
could look at the debug window. In many applications, we want
to stop the application while it is running, examine variables and
then continue running. This can be done with breakpoints.
A breakpoint is a line in the code where you want to stop (temporarily)
the execution of the program that is force the program into break
mode. To set a breakpoint, put the cursor in the line of code you
want to break on. Then, press or click the Breakpoint button on
the toolbar or select Toggle Breakpoint from the Debug menu. The
line will be highlighted.
When you run your program, Visual Basic will stop when it reaches
lines with breakpoints and allow you to use the immediate window
to check variables and expressions. To continue program operation
after a breakpoint, press, click the Run button on the toolbar, or
choose Start from the Run menu. You can also change variable
values using the immediate window. Simply type a valid Basic
expression. This can sometimes be dangerous, though, as it may
change program operation completely.
Breakpoint Example:
■ Set a breakpoint on the X = X + 1 line in the sample
program. Run the program.
■ When the program stops, display the immediate window
and type the following line: Print X;Y
■ The values of these two variables will appear in the debug
window. You can use a question mark (?) as shorthand for
the command Print, if you’d like. Restart the application.
Print the new variable values.
■ Try other breakpoints if you have time. Once done, all
breakpoints can be cleared by Ctrl+Shift+<f9> or by choosing
Clear All Breakpoints from the Debug menu. Individual
breakpoints can be toggled using <f9> or the Breakpoint
button on the toolbar.
134
Executing the Debugging
Viewing Variables in the Locals Window:
The locals window shows the value of any
variables within the scope of the current
procedure. As execution switches from
procedure to procedure, the contents of this
window changes to reflect only the variables
applicable to the current procedure. Repeat the
above example and notice the values of X and
Y also appear in the locals window.
Watch Expressions
The Add Watch option on the Debug menu
allows you to establish watch expressions for
your application. Watch expressions can be
variable values or logical expressions you want
to view or test. Values of watch expressions
A debug menu or
are displayed in the watch window. In break
debug mode is a user
mode, you can use the Quick Watch button interface implemented
on the toolbar to add watch expressions you in a computer program
need. Simply put the cursor on the variable that allows the user to
or expression you want to add to the watch view and/or manipulate
the program’s internal
list and click the Quick Watch button. Watch state for the purpose of
expressions can be edited using the Edit Watch debugging.
option on the Debug menu.
Watch Expression Example:
■ Set a breakpoint at the X = X + 1 line
in the example.
■ Set a watch expression for the variable
X. Run the application. Notice X
appears in the watch window. Every
time you re-start the application, the
value of X changes.
■ At some point in the debug procedure,
add a quick watch on Y. Notice it is
now in the watch window.
■ Clear the breakpoint. Add a watch
on the expression: X = Y. Set Watch
Type to ‘Break When Value Is True.’
135
Basic Computer Coding: Visual Basic
Run the application. Notice it goes into break mode and
displays the watch window whenever X = Y. Delete this
last watch expression.
Call Stack:
Selecting the Call Stack button from the toolbar (or pressing Ctrl+L
or selecting Call Stack from the View menu) will display all active
procedures that is those that have not been exited. Call Stack helps
you unravel situations with nested procedure calls to give you some
idea of where you are in the application.
Call Stack Example:
■ Set a breakpoint on the Fcn = Cint() line in the general
function procedure. Run the application. It will break at
this line.
■ Press the Call Stack button. It will indicate you are currently
in the Fcn procedure which was called from the Command1_
Click procedure. Clear the breakpoint.
Single Stepping (Step Into):
While at a breakpoint, you may execute your program one line at a
time by pressing, choosing the Step Into option in the Debug menu,
or by clicking the Step Into button on the toolbar. This process is
single stepping. It allows you to watch how variables change (in the
locals window) or how your form changes, one step at a time. You
may step through several lines at a time by using Run To Cursor
option. With this option, click on a line below your current point
of execution. Then press Ctrl+<f8> (or choose Run To Cursor in the
Debug menu). The program will run through every line up to the
cursor location, then stop.
Step Into Example:
■ Set a breakpoint on the Do line in the example. Run the
application.
■ When the program breaks, use the Step Into button to
single step through the program.
■ At some point, put the cursor on the Loop While line. Try
the Run To Cursor option (press Ctrl+< f8>).
136
Executing the Debugging
Procedure Stepping (Step Over):
While single stepping your program, if you
come to a procedure call you know functions
properly, you can perform procedure stepping.
This simply executes the entire procedure at
once, rather than one step at a time. To move
through a procedure in this manner, press
Shift+, choose Step Over from the Debug menu,
or press the Step Over button on the toolbar.
Step Over Example:
■ Run the previous example. Single step
through it a couple of times.
■ One time through, when you are at
the line calling the Fcn function, press
the Step over button. Notice how the
program did not single step through
the function as it did previously.
Function Exit (Step Out):
While stepping through your program, if you
wish to complete the execution of a function
you are in, without stepping through it line -by-
line, choose the Step Out option. The function
will be completed and you will be returned
to the procedure accessing that function. To
perform this step out, press Ctrl+Shift+<f8>,
choose Step Out from the Debug menu, or
press the Step Out button on the toolbar.
The debug window
Using the Debug Window provides information
about the state of your
Sometimes debugging requires analysis of what patch as it is executing.
is happening to data. A problem may have been By setting a break
watchpoint, you can
traced to the value of a variable or property look at the suspended
but you need to know where the incorrect execution of your
assignment occurred. The Debug window lets patch to learn more
you display the value of variables either while a information about its
program is running or after it has been halted. behavior.
The window consists of two panes:
137
Basic Computer Coding: Visual Basic
1. Watch Pane
Located directly beneath the Debug window title bar, this pane is
visible only if you have selected a watch expression to be monitored
during code execution. The displayed information includes the
context of the watch expression, the expression itself and its value
at the time of the transition to break mode. If the context of the
expression is not in scope when going to break mode, the current
value is not displayed.
2. Immediate Pane
Located below the title bar, or below the Watch pane if it is displayed,
the Immediate pane is where you enter code to execute it immediately.
While working in the Immediate pane:
■ You can execute only one line of code at a time.
■ You can type or paste a line of code and press to run it.
■ You cannot save code, but you can copy and paste it into
the Code window.
■ In Break mode, a statement in the Debug window is executed
in the context displayed in the Debug window title bar.
For example, if you type Print variable name your output
is the value of a local variable. This is the same as if the
Print method had actually occurred in the procedure you
were executing when the program halted.
The Debug window can do different things depending on what
mode Visual Basic is in:
138
Executing the Debugging
Break Mode
When execution of a program has been
temporarily halted and VB is in Break mode
the Debug window can be used to execute
single line commands entered by the user.
For example, the user can click on the Debug
window, type ‘Print Time$’, and hit. The result
is the current system time is displayed in the
Debug window. Almost any line of code can
be executed from the Debug window. You can
also use the Debug window to monitor the
value of expressions you have selected as watch
expressions.
Run time Mode
Remember
At run time, although you can’t enter statements
into the Debug window, you can use it to The VB program
display internal values without printing them which is still
to the actual forms. The Debug window is running may
an object which has a single Print method. obscure the Debug
For example, the following line will send the window, thus it
name of the font used in ‘Label1’ to the debug is advisable to
window at run time: move it so that
■ [Link] [Link] the contents of the
debug window can
Variables or constants can also be printed in
be seen.
the same way:
■ [Link] intCurrentDay
■ [Link] “Reached here in the
code”
5.4 ERROR HANDLING
Most or early errors occur in your code. If you
are using the IDE to write your code, it can
help you detect syntax errors and fix them.
If you are using Notepad and the free vbc
compiler as we have done so far, you can start
139
Basic Computer Coding: Visual Basic
by paying attention to your code. When you
think everything is fine, compile your code.
If there is a syntax error, the compiler will
let you know. If there is no syntax error, the
A compiler is compilation will be over and the executable will
computer software
that transforms
be ready. You can then execute the application
computer code written to see the result. If the user is not asked to
in one programming provide value(s), you are less likely to get a
language into another run-time error.
programming
language. A run-time error is one that occurs when
using your application. Suppose you write the
following code:
Module Exercise
Public Function Main() As Integer
Dim Number As Double
Dim Twice As Double
[Link](“Enter a number: “)
Number = [Link]()
Twice = Number * 2
[Link](“{0} * 2 = {1}”, Number,
Twice)
[Link]()
Return 0
End Function
End Module
Here is an example of executing it:
Enter a number: 246.88
246.88 * 2 = 493.76
140
Executing the Debugging
The first thing your should do is to imagine what could cause a
problem. If you think there is such a possibility, start by creating a
label that could be used to transfer code if a problem occurs. Here
is an example:
Module Exercise
Public Function Main() As Integer
Dim Number As Double
Dim Twice As Double
[Link](“Enter a number: “)
Number = [Link]()
Twice = Number * 2
[Link](“{0} * 2 = {1}”, Number, Twice)
[Link]()
ThereWasAProblem:
[Link](“There was a problem when executing
your instructions”)
Return 0
End Function
End Module
As we saw when we introduced labels, if you create one, you should
tell the compiler when to jump to that label. Here is an example of
running the above version:
Enter a number: 12.46
12.46 * 2 = 24.92
There was a problem when executing your instructions
141
Basic Computer Coding: Visual Basic
We want the label section to execute only when we want it to. You
can add an Exit Sub line above the label method:
Module Exercise
Public Function Main() As Integer
Dim Number As Double
Dim Twice As Double
[Link](“Enter a number: “)
Number = [Link]()
Twice = Number * 2
[Link](“{0} * 2 = {1}”, Number, Twice)
[Link]()
Exit Sub
ThereWasAProblem:
[Link](“There was a problem when executing
your instructions”)
Return 0
End Function
End Module
5.4.1 In Case Of Error, Jump To Label
The above program will compile fine. When executing it, imagine that
the user types an inappropriate value such as 24$.58 instead of 244.58.
The value is not a number and the program would “crash” and let
you know that there was a problem. If you have some experience,
you would know what the problem was, otherwise, you would face
142
Executing the Debugging
a vague explanation. The short story is that the compiler couldn’t
continue because, in this case, it could not multiply 24$.58 by 2.
If a problem occurs when a person is using your program, the
compiler may display a nasty and insignificant message to the user
who would not know what to do with it. Therefore, you can start
by creating an appropriate label as introduced above. An error
normally occurs in a procedure. Therefore, to make your code easier
to read, you should create a label that shows that it is made for an
error instead of being a regular label. The label should also reflect
the name of the procedure. Here is an example:
Module Exercise
Public Function Main() As Integer
Dim Number As Double
Dim Twice As Double
[Link](“Enter a number: “)
Number = [Link]()
Twice = Number * 2
[Link](“{0} * 2 = {1}”, Number, Twice)
[Link]()
Exit Sub
Err_Main:
[Link](“In Main(): The operation could not be
executed”)
Return 0
End Function
143
Basic Computer Coding: Visual Basic
End Module
When you think there will be a problem in your code, somewhere
in the lines under the name of the procedure but before the line that
could cause the problem, type On Error GoTo followed by the name
of the label that would deal with the error. Here is an example:
Module Exercise
Public Function Main() As Integer
On Error GoTo Err_Main
Dim Number As Double
Dim Twice As Double
[Link](“Enter a number: “)
Number = [Link]()
Twice = Number * 2
[Link](“{0} * 2 = {1}”, Number, Twice)
[Link]()
Exit Sub
Err_Main:
[Link](“In Main(): The operation could not be
executed”)
Return 0
End Function
End Module
Here is an example of running the program:
144
Executing the Debugging
Enter a number: 24$.58
In Main(): The operation could not be executed
When the On Error GoTo statement is used, GoTo is a statement
this indicates to the compiler that if any type of found in many
error occurs while the code of this procedure is computer programming
executed, it should transfer the compilation to languages. It performs
a one-way transfer of
the label. As soon as something bad happens,
control to another line
the compiler marks the area where the problem of code; in contrast a
occurred, skips the normal code and jumps to function call normally
the label indicated by the On Error GoTo line. returns control.
The compiler returns where the error occurred.
If there is nothing to solve the problem, the
compiler continues down but without executing
the lines of code involved. In this case, it would
encounter the Exit Subline and get out of the
procedure.
5.4.2 In Case Of Error, Jump To Line
#
Although the label is more explicit, it only
indicates to the compiler what line to jump
to in case of a problem. The alternative is to
specify a numbered label instead of a lettered
label. Here is an example:
Module Exercise
Public Function Main() As Integer
On Error GoTo 624
Dim Number As Double
Dim Twice As Double
[Link](“Enter a number: “)
Number = [Link]()
Twice = Number * 2
145
Basic Computer Coding: Visual Basic
[Link](“{0} * 2 = {1}”, Number, Twice)
[Link]()
Exit Function
624:
[Link](“In Main(): The operation could not be
executed”)
Return 0
End Function
End Module
Here is an example of running the program:
Enter a number: 25G
In Main(): The operation could not be executed
Press any key to continue . . .
5.4.3 Resume
If a problem occurs in your code and you provide a label to display
a friendly message as done above, the compiler would display the
message and exit from the procedure. If this happens, as mentioned
above, when the compiler returns where the problem occurred,
you can provide an alternate. For example, in our program, if the
user provides an inappropriate value that causes the error, you can
provide an alternate value and ask the compiler to continue as if
nothing happened. In this case, you want to compiler to “resume”
its activity.
To indicate that the program should continue, you can use the
Resume keyword. Here is an example:
146
Executing the Debugging
Module Exercise
Public Function Main() As Integer
On Error GoTo Err_Main
Dim Number As Double
Dim Twice As Double
[Link](“Enter a number: “)
Number = [Link]()
Resume
Twice = Number * 2
[Link](“{0} * 2 = {1}”, Number, Twice)
[Link]()
Exit Sub
Err_Main:
[Link](“In Main(): The operation could not be
executed”)
Return 0
End Function
End Module
When an error occurs, if you want the program to continue with an
alternate value than the one that caused the problem, type Resume
Next. Here is an example:
Module Exercise
147
Basic Computer Coding: Visual Basic
Public Function Main() As Integer
On Error GoTo Err_Main
Dim Number As Double
Dim Twice As Double
[Link](“Enter a number: “)
Number = [Link]()
Resume
Twice = Number * 2
[Link](“{0} * 2 = {1}”, Number, Twice)
[Link]()
Exit Sub
Err_Main:
[Link](“In Main(): The operation could not be
executed”)
Resume Next
Return 0
End Function
End Module
Since any numeric variable is initialized with 0, when the compiler
returns to the line of code that caused the problem, it would use
0 as a substitute to the inappropriate value. Here is an example of
running the above program:
Enter a number: 24$.58
148
Executing the Debugging
In Main(): The operation could not be executed
0* 2=0
Based on this, you can provide a new value to use in case of error.
Here is an example:
Module Exercise
Public Function Main() As Integer
On Error GoTo Err_Main
Dim Number As Double
Dim Twice As Double
[Link](“Enter a number: “)
Number = [Link]()
Twice = Number * 2
[Link](“{0} * 2 = {1}”, Number, Twice)
[Link]()
Exit Sub
Err_Main:
[Link](“Invalid Number: The value you provided
is inappropriate”)
[Link](“10 will be used instead”)
Number = 10
Resume Next
Return 0
End Function
End Module
149
Basic Computer Coding: Visual Basic
Here is one example of running the program:
Enter a number: 244.58
244.58 * 2 = 489.16
Here is another example of running the same program:
Enter a number: 24$.58
Invalid Number: The value you provided is inappropriate
10 will be used instead
10 * 2 = 20
150
Executing the Debugging
SUMMARY
■ Error handling is a combination of coding and methodology
that allows your program to anticipate user and other errors.
It allows you to create a robust program.
■ Visual Basic has signalled this error at design time by
placing the cursor at the point of omission and displaying
a pop up error message.
■ The syntax of the statements is correct, but on execution
they cause a situation to arise that results in a crash or an
undefined value. Error handlers can be used to trap such
errors and deal with them (these are beyond the scope of
this course).
■ Visual Basic provides an excellent set of debugging tools to
aid in this search. Debugging a code is an art, not a science.
■ A breakpoint is a line in the code where you want to
stop (temporarily) the execution of the program that is
force the program into break mode. To set a breakpoint,
put the cursor in the line of code you want to break on.
Then, press or click the Breakpoint button on the toolbar
or select Toggle Breakpoint from the Debug menu. The
line will be highlighted.
■ Located directly beneath the Debug window title bar, this
pane is visible only if you have selected a watch expression
to be monitored during code execution. The displayed
information includes the context of the watch expression, the
expression itself and its value at the time of the transition
to break mode.
151
Basic Computer Coding: Visual Basic
KNOWLEDGE CHECK
1. What is an exception?
a. Problem arising during compile time
b. Problem arising during runtime
c. Problem in syntax
d. Problem in IDE
2. Debug window is the same as ………. window.
a. procedure.
b. object.
c. form.
d. code.
3. …………. bar contains a set of tools to provide controls in
the Form.
a. Status.
b. Tool
c. Menu.
d. Progress.
4. Code window consists of a …………… box and procedure
list box.
a. object.
b. event.
c. tool.
d. message.
5. …………..box provides a set of choices to the user.
a. List.
b. Command.
c. Combo.
d. Text.
152
Executing the Debugging
REVIEW QUESTIONS
1. How many types of error?
2. Discuss the general error handling procedure.
3. How to use debugging tools?
4. How to use the debug window?
5. What is error handling?
Check Your Result
1. (b) 2. (d) 3. (c) 4. (c) 5. (a)
153
Basic Computer Coding: Visual Basic
REFERENCES
1. [Link]
2. [Link]
Basic%20Tutorials/[Link]
3. [Link]
vb6_1__1_.0%20-%20visual%20basic%20-%20learn%20
visual%20basic%206.0%20%28nice%20manual%[Link]
4. [Link]
pdf
5. [Link]
programming-guide/language-features/error-types
6. [Link]
7. [Link]
[Link]
8. [Link]
cossdk/debugging-in-the-visual-basic-ide
9. [Link]
10. [Link]
Recovery/using-application-recovery-and-restart
11. [Link]
[Link]
12. [Link]
error-handling
13. [Link]
getting-started-with-the-debugger?view=vs-2017
14. [Link]
asp
15. [Link]
debugging
154
CHAPTER 6
PROCEDURES AND
ARRAYS
“Should array indices start at 0 or 1? My compromise of 0.5 was rejected without, I
thought, proper consideration.”
―Stan Kelly-Bootle
Learning Objectives
After studying this chapter, you will be able to:
■ Understand about the basics of procedures
■ Define the concept of arrays in visual basic
Basic Computer Coding: Visual Basic
INTRODUCTION
A procedure is a set of coded instructions that tell a computer how to
run a program or calculation. Many different types of programming
languages can be used to build a procedure. Depending on the
programming language, a procedure may also be called a subroutine,
subprogram or function. A procedure is an independent code module
that fulfills some concrete task and is referenced within a larger
body of source code. This kind of code item can also be called a
function or a sub-routine. The fundamental role of a procedure is
to offer a single point of reference for some small goal or task that
the developer or programmer can trigger by invoking the procedure
itself. A procedure may also be referred to as a function, subroutine,
routine, method or subprogram.
The basic idea of a code procedure grew out of the desire to make
code more efficient. Early linear code programs often lacked the
versatility and sophistication that would allow for more complex
processes in code. By using a procedure, a programmer can make a
program do that one thing in many different ways, using different
parameters and sets of data, simply by invoking the procedure with
different variables attached.
In many computer programming languages, procedures are
specifically defined in various ways. The code for a procedure will
be stored within identifiers for that procedure to mark it as separate
from the larger code. In some cases, procedures are part of external
libraries that can be called by developers from those library files.
In other cases, they are written in customized ways within the
program. The procedure is a basic building block for what’s called
object oriented programming, which has brought a more powerful
set of tools to today’s developer community.
6.1 BASICS OF PROCEDURES
Visual Basic offers different types of procedures to execute small
sections of coding in applications. The various procedures are
elucidated in details in this section. Visual Basic programs can be
broken into smaller logical components called Procedures. Procedures
are useful for condensing repeated operations such as the frequently
156
Procedures and Arrays
used calculations, text and control manipulation etc. The benefits
of using procedures in programming are:
It is easier to debug a program a program with procedures, which
breaks a program into discrete logical limits.
Procedures used in one program can act as building blocks for other
programs with slight modifications.
A Procedure can be Sub, Function or Property Procedure.
6.1.1 Sub Procedures
A sub procedure can be placed in standard, class and form modules.
Each time the procedure is called, the statements between Sub and
End Sub are executed. The syntax for a sub procedure is as follows:
[Private | Public] [Static] Sub Procedurename [( arglist)]
[ statements]
End Sub
arglist is a list of argument names separated by commas. Each
argument acts like a variable in the procedure. There are two types
of Sub Procedures namely general procedures and event procedures.
A Sub procedure is a series of Visual Basic statements enclosed by
the Sub and End Sub statements. The Sub procedure performs a
task and then returns control to the calling code, but it does not
return a value to the calling code.
Each time the procedure is called, its statements are executed,
starting with the first executable statement after the Sub statement
and ending with the first End Sub, Exit Sub, or Return statement
encountered.
You can define a Sub procedure in modules, classes, and structures.
By default, it is Public, which means you can call it from anywhere
in your application that has access to the module, class, or structure
in which you defined it. The term, method, describes a Sub or
Function procedure that is accessed from outside its defining module,
class, or structure.
157
Basic Computer Coding: Visual Basic
Declaration Syntax
A Sub procedure can
The syntax for declaring a Sub procedure is
take arguments, such
as constants, variables, as follows:
or expressions, which [ modifiers ] Sub subname [( parameterlist )]
are passed to it by the
calling code. Statements of the Sub procedure.
End Sub
The modifiers can specify access level and
information about overloading, overriding,
sharing, and shadowing.
Parameter Declaration
You declare each procedure parameter similarly
to how you declare a variable, specifying the
parameter name and data type. You can also
specify the passing mechanism, and whether
the parameter is optional or a parameter array.
The syntax for each parameter in the parameter
list is as follows:
[Optional] [ByVal | ByRef] [ParamArray]
parametername As datatype
If the parameter is optional, you must also
supply a default value as part of its declaration.
The syntax for specifying a default value is as
follows:
Optional [ByVal | ByRef] parametername As
datatype = defaultvalue
Parameters as Local Variables
When control passes to the procedure, each
parameter is treated as a local variable. This
means that its lifetime is the same as that of the
procedure, and its scope is the whole procedure.
158
Procedures and Arrays
Calling Syntax
You invoke a Sub procedure explicitly with a stand-alone calling
statement. You cannot call it by using its name in an expression. You
must provide values for all arguments that are not optional, and
you must enclose the argument list in parentheses. If no arguments
are supplied, you can optionally omit the parentheses. The use of
the Call keyword is optional but not recommended.
The syntax for a call to a Sub procedure is as follows:
[Call] subname [( argumentlist )]
You can call a Sub method from outside the class that defines it.
First, you have to use the Newkeyword to create an instance of
the class, or call a method that returns an instance of the class.
Then, you can use the following syntax to call the Submethod on
the instance object:
[Link][(argumentlist)]
Illustration of Declaration and Call
The following Sub procedure tells the computer operator which
task the application is about to perform, and also displays a time
stamp. Instead of duplicating this code at the start of every task,
the application just calls tellOperator from various locations. Each
call passes a string in the taskargument that identifies the task
being started.
Sub tellOperator(ByVal task As String)
Dim stamp As Date
stamp = TimeOfDay()
MsgBox(“Starting “ & task & “ at “ & CStr(stamp))
End Sub
The following example shows a typical call to tellOperator.
tellOperator(“file update”)
159
Basic Computer Coding: Visual Basic
Calling a Sub Procedure
Once you have a procedure, whether you created it or it is part
of the Visual Basic language, you can use it. Using a procedure is
also referred to as calling it. Before calling a procedure, you should
first locate the section of code in which you want to use it. To call
a simple procedure, type its name followed by parentheses in the
section where you want to use it. Here is an example:
Module Exercise
Sub Assign()
Dim strFullName As String
strFullName = “Paul Bertrand Yamaguchi”
MsgBox(strFullName)
End Sub
Friend Sub Main()
Assign()
End Sub
End Module
Besides using the name of a procedure to call it, you can also precede
it with the Call keyword. Here is an example:
Module Exercise
Sub Assign()
Dim strFullName As String
strFullName = “Paul Bertrand Yamaguchi”
MsgBox(strFullName)
End Sub
Friend Sub Main()
160
Procedures and Arrays
Call Assign()
End Sub
End Module
6.1.2 Event Procedures
An event procedure is a procedure block that contains the control’s
actual name, an underscore(_), and the event name. The following
syntax represents the event procedure for a Form_Load event.
Private Sub Form_Load()
....statement block..
End Sub
Event Procedures acquire the declarations as Private by default.
The code that performs actions in response to events is written in
event procedures. Each event procedure contains the statements
that execute when a particular event occurs on a particular object.
Event procedure names have the form objectName_event, where
objectName is the name of the object on which the event occurred
and event is the type of the event. For example, an event procedure
named cmdClear_Click will be executed when the user clicks on
the button named cmdClear.
The event procedures are written in the code window. To open the
code window, double click on the control for which you want to
write the event procedure. The code window will open and it will
contain the shell of the event procedure for that object:
Private Sub btnClear_Click(...) Handles [Link]
End Sub
6.1.3 General Procedures
A general procedure is declared when several event procedures
perform the same actions. It is a good programming practice to write
common statements in a separate procedure (general procedure)
and then call them in the event procedure.
161
Basic Computer Coding: Visual Basic
In order to add General procedure:
■ The Code window is opened for the
Programming
module to which the procedure is to
is the process of
taking an algorithm be added.
and encoding it ■ The Add Procedure option is chosen
into a notation,
from the Tools menu, which opens an
a programming
language, so that it Add Procedure dialog box as shown
can be executed by a in the figure given below.
computer.
■ The name of the procedure is typed
in the Name textbox
■ Under Type, Sub is selected to create
a Sub procedure, Function to create
a Function procedure or Property to
create a Property procedure.
■ Under Scope, Public is selected to
create a procedure that can be invoked
outside the module, or Private to create
a procedure that can be invoked only
from within the module.
We can also create a new procedure in the
current module by typing Sub ProcedureName,
Function ProcedureName, or Property
ProcedureName in the Code window. A
Function procedure returns a value and a Sub
Procedure does not return a value.
162
Procedures and Arrays
6.1.4 Function Procedures
Functions are like sub procedures, except they return a value to
the calling procedure. They are especially useful for taking one or
more pieces of data, called arguments and performing some tasks
with them. Then the functions returns a value that indicates the
results of the tasks complete within the function.
The following function procedure calculates the third side or
hypotenuse of a right triangle, where A and B are the other two
sides. It takes two arguments A and B (of data type Double) and
finally returns the results.
Function Hypotenuse (A As Double, B As Double) As Double
Hypotenuse = sqr (A^2 + B^2)
End Function
The above function procedure is written in the general declarations
section of the Code window. A function can also be written by
selecting the Add Procedure dialog box from the Tools menu and
by choosing the required scope and type.
A Function procedure is a series of Visual Basic statements enclosed
by the Function and End Function statements. The Function procedure
performs a task and then returns control to the calling code. When
it returns control, it also returns a value to the calling code.
Each time the procedure is called, its statements run, starting with
the first executable statement after the Function statement and ending
with the first End Function, Exit Function, or Return statement
encountered.
You can define a Function procedure in a module, class, or structure.
It is Public by default, which means you can call it from anywhere
in your application that has access to the module, class, or structure
in which you defined it.
A Function procedure can take arguments, such as constants,
variables, or expressions, which are passed to it by the calling code.
Declaration Syntax
The syntax for declaring a Function procedure is as follows:
[Modifiers] Function FunctionName [(ParameterList)] As ReturnType
163
Basic Computer Coding: Visual Basic
[Statements]
End Function
The modifiers can specify access level and information regarding
overloading, overriding, sharing, and shadowing.
You declare each parameter the same way you do for Sub Procedures.
Data Type
Every Function procedure has a data type, just as every variable does.
This data type is specified by the As clause in the Function statement,
and it determines the data type of the value the function returns to
the calling code. The following sample declarations illustrate this.
Function yesterday() As Date
End Function
Function findSqrt(ByVal radicand As Single) As Single
End Function
Returning Values
The value a Function procedure sends back to the calling code is
called its return value. The procedure returns this value in one of
two ways:
• It uses the Return statement to specify the return value, and
returns control immediately to the calling program. The
following example illustrates this.
Function FunctionName [(ParameterList)] As ReturnType
‘ The following statement immediately transfers control back
‘ to the calling code and returns the value of Expression.
Return Expression
End Function
• It assigns a value to its own function name in one or more
statements of the procedure. Control does not return to the
calling program until an Exit Function or End Functionstatement
164
Procedures and Arrays
is executed. The following example
illustrates this.
Function FunctionName
[(ParameterList)] As ReturnType
‘ The following statement does not
transfer control back to the calling code.
FunctionName = Expression
‘ When control returns to the calling
code, Expression is the return value.
End Function
Function is a block of
The advantage of assigning the return value organized, reusable
to the function name is that control does not code that is used to
perform a single, related
return from the procedure until it encounters
action. It provide better
an Exit Function or End Function statement. modularity for your
This allows you to assign a preliminary value application and a high
and adjust it later if necessary. degree of code reusing.
You have already seen
various functions like
Calling Syntax printf() and main().
You invoke a Function procedure by including
its name and arguments either on the right side
of an assignment statement or in an expression.
You must provide values for all arguments that
are not optional, and you must enclose the
argument list in parentheses. If no arguments
are supplied, you can optionally omit the
parentheses.
The syntax for a call to a Function procedure
is as follows:
lvalue = functionname [( argumentlist )]
If (( functionname [( argumentlist )] / 3) <= expression
) Then
When you call a Function procedure, you do
not have to use its return value. If you do not,
165
Basic Computer Coding: Visual Basic
all the actions of the function are performed,
but the return value is ignored. MsgBox is often
called in this manner.
Illustration of Declaration and Call
The following Function procedure calculates the
longest side, or hypotenuse, of a right triangle,
given the values for the other two sides.
Function hypotenuse(ByVal side1 As
Single, ByVal side2 As Single) As Single
Return [Link]((side1 ^ 2) + (side2
^ 2))
End Function
The following example shows a typical call to
hypotenuse.
Dim testLength, testHypotenuse As
Single
testHypotenuse = hypotenuse(testLength,
10.7)
Remember
6.1.5 Property Procedures
A property A property procedure is used to create and
procedure is a manipulate custom properties. It is used to
series of Visual create read only properties for Forms, Standard
Basic statements modules and Class modules. Visual Basic
that manipulate a provides three kind of property procedures-
custom property on Property Let procedure that sets the value of a
a module, class, or property, Property Get procedure that returns
structure. Property the value of a property, and Property Set
procedures are also procedure that sets the references to an object.
known as property Visual Basic provides for the following property
accessors. procedures:
166
Procedures and Arrays
■ A Get procedure returns the value of a property. It is called
when you access the property in an expression.
■ A Set procedure sets a property to a value, including an
object reference. It is called when you assign a value to
the property.
You usually define property procedures in pairs, using the Get and
Set statements, but you can define either procedure alone if the
property is read-only (Get Statement) or write-only (Set Statement).
You can define properties in classes, structures, and modules.
Properties are Public by default, which means you can call them
from anywhere in your application that can access the property’s
container.
Declaration Syntax
A property itself is defined by a block of code enclosed within the
Property Statement and the End Property statement. Inside this
block, each property procedure appears as an internal block enclosed
within a declaration statement (Get or Set) and the matching End
declaration.
The syntax for declaring a property and its procedures is as follows:
[Default] [Modifiers] Property PropertyName[(ParameterList)]
[As DataType]
[AccessLevel] Get
‘ Statements of the Get procedure.
‘ The following statement returns an expression as the
property’s value.
Return Expression
End Get
[AccessLevel] Set[(ByVal NewValue As DataType)]
‘ Statements of the Set procedure.
‘ The following statement assigns newvalue as the property’s
value.
167
Basic Computer Coding: Visual Basic
LValue = NewValue
End Set
End Property
- or -
[Default] [Modifiers] Property PropertyName [(ParameterList)]
[As DataType]
The Modifiers can specify access level and information regarding
overloading, overriding, sharing, and shadowing, as well as whether
the property is read-only or write-only. The AccessLevel on the Get
or Set procedure can be any level that is more restrictive than the
access level specified for the property itself.
Data Type
A property’s data type and principal access level are defined in the
Property statement, not in the property procedures. A property can
have only one data type. For example, you cannot define a property
to store a Decimal value but retrieve a Double value.
Access Level
However, you can define a principal access level for a property and
further restrict the access level in one of its property procedures.
For example, you can define a Public property and then define a
Private Set procedure. The Get procedure remains Public. You can
change the access level in only one of a property’s procedures, and
you can only make it more restrictive than the principal access level.
For more information.
Parameter Declaration
You declare each parameter the same way you do for Sub Procedures,
except that the passing mechanism must be ByVal.
The syntax for each parameter in the parameter list is as follows:
[Optional] ByVal [ParamArray] parametername As datatype
168
Procedures and Arrays
If the parameter is optional, you must also supply a default value
as part of its declaration. The syntax for specifying a default value
is as follows:
Optional ByVal parametername As datatype = defaultvalue
Property Value
In a Get procedure, the return value is supplied to the calling
expression as the value of the property.
In a Set procedure, the new property value is passed to the parameter
of the Set statement. If you explicitly declare a parameter, you must
declare it with the same data type as the property. If you do not
declare a parameter, the compiler uses the implicit parameter Value
to represent the new value to be assigned to the property.
Calling Syntax
You invoke a property procedure implicitly by making reference to
the property. You use the name of the property the same way you
would use the name of a variable, except that you must provide
values for all arguments that are not optional, and you must enclose
the argument list in parentheses. If no arguments are supplied, you
can optionally omit the parentheses.
The syntax for an implicit call to a Set procedure is as follows:
propertyname[(argumentlist)] = expression
The syntax for an implicit call to a Get procedure is as follows:
lvalue = propertyname[(argumentlist)]
Do While (propertyname[(argumentlist)] > expression)
Illustration of Declaration and Call
The following property stores a full name as two constituent names,
the first name and the last name. When the calling code reads
fullName, the Get procedure combines the two constituent names
and returns the full name. When the calling code assigns a new full
name, the Setprocedure attempts to break it into two constituent
names. If it does not find a space, it stores it all as the first name.
169
Basic Computer Coding: Visual Basic
Dim firstName, lastName As String
Property fullName() As String
Get
If lastName = “” Then
Return firstName
Else
Return firstName & “ “ & lastName
End If
End Get
Set(ByVal Value As String)
Dim space As Integer = [Link](“ “)
If space < 0 Then
firstName = Value
lastName = “”
Else
firstName = [Link](0, space)
lastName = [Link](space + 1)
End If
End Set
End Property
The following example shows typical calls to the property procedures
of fullName.
fullName = “MyFirstName MyLastName”
170
Procedures and Arrays
MsgBox(fullName)
6.2 ARRAYS IN VISUAL BASIC
An array is a set of values, which are termed
elements that are logically related to each
other. For example, an array may consist of
the number of students in each grade in a
grammar school; each element of the array
is the number of students in a single grade.
Similarly, an array may consist of a student’s
grades for a class; each element of the array
is a single grade.
It is possible individual variables to store
each of our data items. For example, if our
application analyzes student grades, we can
use a separate variable for each student’s grade,
such as englishGrade1, englishGrade2, etc. This
approach has three major limitations:
■ We have to know at design time
exactly how many grades we have
to handle.
■ Handling large numbers of grades
quickly becomes unwieldy. This in
turn makes an application much more
likely to have serious bugs.
■ It is difficult to maintain. Each new
grade that we add requires that the Visual Basic (VB)
application be modified, recompiled, is a programming
environment from
and redeployed.
Microsoft in which a
By using an array, you can refer to these related programmer uses a
values by the same name, and use a number graphical user interface
(GUI) to choose and
that’s called an index or subscript to identify modify preselected
an individual element based on its position sections of code
in the array. The indexes of an array range written in the BASIC
programming language.
from 0 to one less than the total number of
elements in the array. When you use Visual
Basic syntax to define the size of an array,
171
Basic Computer Coding: Visual Basic
you specify its highest index, not the total number of elements in
the array. You can work with the array as a unit, and the ability
to iterate its elements frees you from needing to know exactly how
many elements it contains at design time.
Some quick examples before explanation:
Declare a single-dimension array of 5 numbers.
Dim numbers(4) As Integer
Declare a single-dimension array and set its 4 values.
Dim numbers = New Integer() {1, 2, 4, 8}
Change the size of an existing array to 16 elements and retain
the current values.
ReDim Preserve numbers(15)
Redefine the size of an existing array and reset the values.
ReDim numbers(15)
Declare a 6 x 6 multidimensional array.
Dim matrix(5, 5) As Double
Declare a 4 x 3 multidimensional array and set array element
values.
Dim matrix = New Integer(3, 2) {{1, 2, 3}, {2, 3, 4}, {3, 4, 5}, {4, 5,
6}}
172
Procedures and Arrays
Declare a jagged array
Dim sales()() As Double = New Double(11)() {}
6.2.1 Dimension of an Array
An array can be one-dimensional or multidimensional. A one-
dimensional array is like a list of items or a table that consists of
one row of items or one column of items.
A two-dimensional array is a table of items that make up of rows and
columns. The format for a one-dimensional array is ArrayName(x),
the format for a two dimensional array is ArrayName(x,y) and a
three-dimensional array is ArrayName(x,y,z) . Normally it is sufficient
to use a one-dimensional and two-dimensional array, you only need
to use higher dimensional arrays if you need to deal with more
complex problems. Let me illustrate the arrays with tables
Table 1. One dimensional Array
Student Name Name(1) Name(2) Name(3) Name(4)
Table 2. Two Dimensional Array
Name(1,1) Name(1,2) Name(1,3) Name(1,4)
Name(2,1) Name(2,2) Name(2,3) Name(2,4)
Name(3,1) Name(3,2) Name(3,3) Name(3,4)
Declaring Array
We can use Public or Dim statement to declare an array just as the
way we declare a single variable. The Public statement declares an
array that can be used throughout an application while the Dim
statement declares an array that could be used only in a local
procedure.
The general syntax to declare a one dimensional array is as follow:
Dim arrayName(subscript) as dataType
173
Basic Computer Coding: Visual Basic
where subs indicates the last subscript in the array.
When you declare an array, you need to be aware of the
number of elements created by the Dim keyword. In the Dim
arrayName(subscript) statement, subscript actually is a constant that
defines the maximum number of elements allowed. More importantly,
subs start with 0 instead of 1. Therefore, the Dim arrangeName(10)
statement creates 11 elements numbered 0 to 11. There are two ways
to overcome this problem, the first way is by uisng the keyword
Option Base 1, as shown in Example 1.
Example 1
Option Base 1
Dim CusName(10) as String
will declare an array that consists of 10 elements if the statement
Option Base 1 appear in the declaration area, starting from
CusName(1) to CusName(10). Otherwise, there will be 11 elements
in the array starting from CusName(0) through to CusName(10), as
shown in Table 3.
Table 3
CusName(1) CusName(2) CusName(3) CusName(4) CusName(5)
CusName(6) CusName(7) CusName(8) CusName(9) CusName(10)
The second way is to specify the lower bound and the upper bound
of the subscript using To keyword. The syntax is
Dim arrayName(lowerbound To upperbound) As dataType
Declaring two dimensional Array
The general syntax to declare a two dimensional array is as follow:
Dim ArrayName(Sub1,Sub2) as dataType
174
Procedures and Arrays
Example 2
If you wish to compute a summary of students involve in games
according to different year in a high school, you need to declare a
two dimensional array. In this example, let’s say we have 4 games,
football, basketball, tennis and hockey and the classes are from year
7 to year 12. We can create an array as follows:
Dim StuGames(1 to 4,7 to 12 ) As Integer will create an array of
four rows and six columns, as shown in table 4.
Table 4
Year 7 8 9 10 11 12
Football StuGames StuGames StuGames StuGames StuGames(1,11) StuGames(1,12)
(1,7) (1,8) (1,9) (1,10)
Basketball StuGames StuGames StuGames StuGames StuGames(2,11) StuGames(2,12)
(2,7) (2,8) (2,9) (2,10)
Tennis StuGames StuGames StuGames StuGames StuGames(3,11) StuGames(3,12)
(3,7) (3,8) (3,9) (3,10)
Hockey StuGames StuGames StuGames StuGames StuGames(4,11) StuGames(4,12)
(4,7) (4,8) (4,9) (4,10)
Example 3
In this example, we want to summarize the first half-yearly sales
volume for four products. Therefore, we declare a two dimension
array as follows:
Dim saleVol(1 To 4, 1 To 6) As Integer
Besides that, we want to display the output in a table form. Therefore,
we use a list box. We named the list box listVolume. AddItem is a
listbox method to populate the listbox.
The code
Private Sub cmdAdd_Click()
Dim prod, mth As Integer ‘ prod is product and mth is month
Dim saleVol(1 To 4, 1 To 6) As Integer
175
Basic Computer Coding: Visual Basic
Const j = 1
[Link] vbTab & “January” & vbTab & “February”
& vbTab & “March” _
& vbTab & “Apr” & vbTab & “May” & vbTab & “June”
[Link] vbTab & “____________________________
________________”
For prod = 1 To 4
For mth = 1 To 6
saleVol(prod, mth) = InputBox(“Enter the sale volume for” & “
“ & “product” & “ “ & prod & “ “ & “month” & “ “ & mth)
Next mth
Next prod
For i = 1 To 4
[Link] “Product” & “” & i & vbTab & saleVol(i, j)
& vbTab & saleVol(i, j + 1) & vbTab & saleVol(i, j + 2) _
& vbTab & saleVol(i, j + 3) & vbTab & saleVol(i, j + 4) & vbTab
& saleVol(i, j + 5)
Next i
End Sub
The Output
176
Procedures and Arrays
Figure 1
6.2.2 Dynamic Array
So far we have learned how to define the
Static array is a
number of elements in an array during design composite data type in
time. This type of array is known as static UnrealScript that groups
array. However, the problem is sometimes we multiple values of the
might not know how many data items we need same type
to store during run time. In this case, we need
to use dynamic array where the number of
elements will be decided during run time. In
VB6, the dynamic array can be resized when
the program is executing.
The first step in declaring a dynamic array is
by using the Dim statement without specifying
the dimenson list, as follows:
Dim myArray()
Then at run time we can specify the actual array
size using the ReDim statement,as follows:
ReDim myArray(1 to n) when n is
decided during run time
You can also declare a two dimensional array
using ReDim statement, as follows:
ReDim myArray(1 to n, 1 to m) when
m and n are known during run time
177
Basic Computer Coding: Visual Basic
Example 4
In this example, we want to display the elements of an array in a
list box. The size of the array will only be known during run time.
It demonstrates the creation of a dynamic array using the ReDim
keyword.
The Code
Private Sub cmd_display_Click()
Dim myArray() As Integer
Dim i, n As Integer
n = InputBox(“Enter the upper bound of array”)
[Link]
For i = 1 To n
ReDim myArray(i)
myArray(i) = i ^ 2
[Link] myArray(i)
Next
End Sub
The output
178
Procedures and Arrays
In a 1999 paper,
Brodnik et al.
describe a tiered
Figure 2 dynamic array
data structure,
which wastes only
Building Skills n1/2 space for n
elements at any
Another problem related to ReDim is each time point in time, and
you ReDim an array, the values currently stored they prove a lower
in the array are lost. In order to preserve the bound showing that
stored values, we can use the keywords ReDim any dynamic array
Preserve, as follows must waste this
much space if the
ReDim Preserve MyArray(n) operations are to
remain amortized
where n is the new upper bound of the array constant time.
The new Charlotte Church CD came out but
your rack only has three slots. You don’t want
to throw away any of your CDs to make room
for the new one so you decide to use your
ultimate building skills to attach another slot.
You start building:
Dim strCDRack() As String
ReDim strCDRack(0 to 2) As String
strCDRack(0) = “Deftones”
strCDRack(1) = “Tool”
strCDRack(2) = “Disturbed”
179
Basic Computer Coding: Visual Basic
What have you done? Nothing wrong, you’ve just dimensioned your
array another way that allows for expansion. Notice that the subscript
of the Dim statement is missing. This is OK; it tells VB that your array
is a dynamic array, meaning that you can change its size with ReDim.
Now that you’ve rebuilt the structure of your CD rack, allowing for
expansion, it is time to expand:
Dim strCDRack() As String
ReDim strCDRack(0 to 2) As String
strCDRack(0) = “Deftones”
strCDRack(1) = “Tool”
strCDRack(2) = “Disturbed”
ReDim Preserve strCDRack(0 to 3) As String
strCDRack(3) = “Charlotte Church”
This snippet has two more lines, the first redimensioning the array
one element larger and the second setting this element’s value. Notice
the Preserve keyword: it forces Visual Basic to retain all existing
elements’ values. Without this keyword all your old CDs would be
lost and you’d be stuck with just Charlotte Church.
The ReDim keyword’s syntax is:
ReDim [Preserve] ArrayName(Subscript) As DataType
• ReDim is the keyword that denotes we are redimensioning an
array.
• Preserve is an optional keyword that forces Visual Basic to
retain all existing elements’ values. Without it all elements
180
Procedures and Arrays
will return to their default values. (Numeric data types to 0,
variable-length strings to “” (a zero-length string), fixed-length
strings filled with zeros, and variants to empty.)
• ArrayName is the name of the array.
• Subscript is the dimensions of the array.
• DataType is any valid data type. The data type cannot be
changed from its initial declaration when using the ReDim
keyword. (Unless it was initially declared as a Variant.)
6.2.3 Retrieving the Contents of an Array
Now that you know how to build an array, you might ask how to
retrieve its contents. Say you’ve built an array of your friends’ names:
Dim strFriends(0 to 6) As String
strFriends(0) = “Bianca”
strFriends(1) = “Jeana”
strFriends(2) = “Sam”
strFriends(3) = “Jenna”
strFriends(4) = “Erin”
strFriends(5) = “Carolyn”
strFriends(6) = “Kate”
That’s all good and dandy but you want to display their names in
successive message boxes, so you construct a loop:
Dim strFriends(0 to 6) As String, lngPosition as Long
strFriends(0) = “Bianca”
strFriends(1) = “Jeana”
181
Basic Computer Coding: Visual Basic
strFriends(2) = “Sam”
strFriends(3) = “Jenna”
strFriends(4) = “Erin”
strFriends(5) = “Carolyn”
strFriends(6) = “Kate”
For lngPosition = LBound(strFriends) To
UBound(strFriends)
MsgBox strFriends(lngPosition)
Next lngPositionlngPositionlngPosition
There are two new functions in that snippet
of code. LBound and UBound are used to
Snippet is a determine the lower and upper bounds of an
programming term array. Because strFriends has a lower bound of
for a small region of
re-usable source code,
0 and an upper bound of 6. These functions
machine code, or allow you to to iterate through an array with
text. Ordinarily, these a dynamic size and they keep you from having
are formally defined
to keep track of the array›s size yourself. With
operative units to
incorporate into each iteration of that loop, lngPosition will
larger programming count up from 0 to 6. By accessing the array as
modules. strFriends(lngPosition) you are greatly reducing
the amount of code you have to write.
6.2.4 Multidimensional Arrays
So far all of the examples we’ve looked at
have used one dimensional arrays, but arrays
can be multidimensional too. Multidimensional
arrays can be thought of as arrays-of-arrays.
For example, to visualize a two dimensional
182
Procedures and Arrays
array we could picture a row of CD racks. To make things easier,
we can imagine that each CD rack could be for a different artist.
Like the CDs, the racks would be identifiable by number. Below
we’ll define a two dimensional array representing a row of CD
racks. The strings inside of the array will represent album titles.
Here we will define an array where the first dimension contains 2
elements and
‘ the second dimension contains 4 elements
ReDim cdRack(0 to 1, 0 to 3) As String
‘ A CD rack for the Beatles
cdRack(0, 0) = “Rubber Soul”
cdRack(0, 1) = “Revolver”
cdRack(0, 2) = “The White Album”
cdRack(0, 3) = “Let It Be”
‘ A CD rack for the Rolling Stones
cdRack(1, 0) = “Sticky Fingers”
cdRack(1, 1) = “Beggars Banquet”
cdRack(1, 2) = “Let It Bleed”
cdRack(1, 3) = “Tattoo You”
The first item of the first dimension is an array for Beatles CDs while
the second item of the first dimension is an array for Rolling Stones
CDs. You could also add a third dimension if you wanted. Keeping
with our CD rack analogy, you could picture this third dimension
as a hallway with several rooms. Inside of each room would be a
row of CDs racks. If you wanted your hallways to have 10 rooms,
each with CD racks like the ones in the above example, you could
declare your array as follows:
183
Basic Computer Coding: Visual Basic
Dim cdRackHallway(0 to 9, 0 to 1, 0 to 3) As String
In Visual Basic 6.0, you can create arrays with up to 60 dimensions.
In Visual Basic .NET, the maximum number of dimensions an array
can have is 32. Most arrays you will need to deal with will only
be one or two dimensions. Multidimensional arrays can require a
decent amount of memory, so use them with care, especially large
multidimensional arrays.
Lastly, for multidimensional arrays it should be noted that only the
last dimension can be resized. That means that given our example
above, once we created the array with two CD racks, we would not
be able to add more racks, we would only be able to change the
number of CDs each rack held. Example:
‘ Here we will define an array where the first dimension contains 2
elements and
‘ the second dimension contains 4 elements
ReDim cdRack(0 to 1, 0 to 3) As String
‘ A CD rack for the Beatles
cdRack(0, 0) = “Rubber Soul”
cdRack(0, 1) = “Revolver”
cdRack(0, 2) = “The White Album”
cdRack(0, 3) = “Let It Be”
‘ A CD rack for the Rolling Stones
cdRack(1, 0) = “Sticky Fingers”
cdRack(1, 1) = “Beggars Banquet”
cdRack(1, 2) = “Let It Bleed”
cdRack(1, 3) = “Tattoo You”
184
Procedures and Arrays
ReDim Preserve cdRack(0 to 1, 0 to 4) As String
‘ Lets add another Beatles CD
cdRack(0, 4) = “Abby Road”
‘ Lets add another Rolling Stones CD
cdRack(1, 4) = “Exile on Main St.”
185
Basic Computer Coding: Visual Basic
SUMMARY
■ A procedure is a set of coded instructions that tell a
computer how to run a program or calculation. Many
different types of programming languages can be used to
build a procedure.
■ The basic idea of a code procedure grew out of the desire
to make code more efficient. Early linear code programs
often lacked the versatility and sophistication that would
allow for more complex processes in code.
■ The code for a procedure will be stored within identifiers for
that procedure to mark it as separate from the larger code.
■ Visual Basic offers different types of procedures to execute
small sections of coding in applications. The various
procedures are elucidated in details in this section.
Visual Basic programs can be broken into smaller logical
components called Procedures.
■ A sub procedure can be placed in standard, class and form
modules. Each time the procedure is called, the statements
between Sub and End Sub are executed.
■ An event procedure is a procedure block that contains the
control’s actual name, an underscore(_), and the event name.
■ A general procedure is declared when several event
procedures perform the same actions. It is a good
programming practice to write common statements in a
separate procedure (general procedure) and then call them
in the event procedure.
■ Functions are like sub procedures, except they return a value
to the calling procedure. They are especially useful for taking
one or more pieces of data, called arguments and performing
some tasks with them. Then the functions returns a value
that indicates the results of the tasks complete within the
function.
■ A property procedure is used to create and manipulate
custom properties. It is used to create read only properties
for Forms, Standard modules and Class modules. Visual
Basic provides three kind of property procedures-Property
Let procedure that sets the value of a property, Property
Get procedure that returns the value of a property, and
186
Procedures and Arrays
Property Set procedure that sets the references to an object.
■ An array is a set of values, which are termed elements, that
are logically related to each other. For example, an array
may consist of the number of students in each grade in a
grammar school; each element of the array is the number
of students in a single grade.
■ A two-dimensional array is a table of items that make up
of rows and columns. The format for a one-dimensional
array is ArrayName(x), the format for a two dimensional
array is ArrayName(x,y) and a three-dimensional array is
ArrayName(x,y,z) .
187
Basic Computer Coding: Visual Basic
KNOWLEDGE CHECK
1. To set array[i] to 0, we must first get its address, start by
multiplying i with
a. 0
b. 1
c. 2
d. 4
2. Which of these best describes an array?
a. A data structure that shows a hierarchical behavior
b. Container of objects of similar types
c. Container of objects of mixed types
d. All of the mentioned
3. Which of the following concepts make extensive use of
arrays?
a. Binary trees
b. Scheduling of processes
c. Caching
d. Spatial locality
4. What are the advantages of arrays?
a. Easier to store elements of same data type
b. Used to implement other data structures like stack and
queue
c. Convenient way to represent matrices as a 2D array
d. All of the mentioned
5. Assuming int is of 4bytes, what is the size of int arr[15];?
a. 60
b. 11
c. 15
d. 19
188
Procedures and Arrays
REVIEW QUESTIONS
1. Discuss on sub procedures and event procedures.
2. Write a program on general procedures.
3. What is the concept of property procedures?
4. Explain the dimension of an array.
5. What do you understand by the dynamic array?
6. How to retrieving the contents of an array?
Check Your Result
1. (d) 2. (b) 3. (d) 4. (d) 5. (a)
189
Basic Computer Coding: Visual Basic
REFERENCES
1. Homer, Alex, Dave Sussman, and Mark Fussell. A
First Look at [Link] and [Link] v. 2.0. Boston:
Addison-Wesley, 2004.
2. [Link]
[Link]
3. [Link]
htm#fixedsizearrays
4. [Link]
htm
5. [Link]
[Link]
6. [Link]
programming-guide/language-features/procedures/sub-
procedures
7. [Link]
programming-guide/language-features/arrays/how-to-
initialize-an-array-variable
8. [Link]
9. [Link]
10. [Link]
11. [Link]
12. [Link]
13. Nathan, Adam. Windows Presentation Foundation
Unleashed. Indianapolis: Sams Publishing, 2007.
14. Sells, Chris, and Justin Gehtland. Windows Forms
Programming in Visual Basic .NET. Boston: Addison-
Wesley, 2004.
190
CHAPTER 7
DATA ACCESS
“Computing should be taught as a rigorous - but fun - discipline covering topics like
programming, database structures, and algorithms. That doesn’t have to be boring.”
―Geoff Mulgan
Learning Objectives
After studying this chapter, you will be able to:
■ Understand the [Link] object model
■ Connect to a database
■ Create table, columns and rows
■ Select the data source
Basic Computer Coding: Visual Basic
INTRODUCTION
Data access refers to a user’s ability to access
or retrieve data stored within a database or
other repository. Users who have data access
can store, retrieve, move or manipulate stored
data, which can be stored on a wide range of
hard drives and external devices.
Data access is a feature of Visual Basic that
allows you to access and manipulate any
database from Visual Basic. The database may be
either MS-Access database or FoxPro database
or it may also be any of the relational databases
such as Oracle. You can develop applications in
Visual Basic that can access data in a database.
The database may be on the same machine as
the application or it may be on database server
that is far away from Visual Basic application.
Whatever may be the case, you can access and
manipulate the data using applications written
in Visual Basic.
Applications communicate with a database,
firstly, to retrieve the data stored there and
present it in a user-friendly way, and secondly,
to update the database by inserting, modifying
and deleting data.
Microsoft ActiveX Data [Link] ([Link])
is a model, a part of the .Net framework that
is used by the .Net applications for retrieving,
accessing and updating data.
Object model is a
logical interface,
software or system
that is modeled
7.1 [Link] OBJECT MODEL
through the use [Link] object model is nothing but the
of object-oriented structured process flow through various
techniques.
components. The object model can be pictorially
described as –
192
Data Access
The data residing in a data store or database is retrieved through
the data provider. Various components of the data provider retrieve
data for the application and update data.
An application accesses data either through a dataset or a data reader.
■ Datasets store data in a disconnected cache and the
application retrieves data from it.
■ Data readers provide data to the application in a read-only
and forward-only mode.
7.1.1 Data Provider
A data provider is used for connecting to a database, executing
commands and retrieving data, storing it in a dataset, reading the
retrieved data and updating the database.
The data provider in [Link] consists of the following four objects −
[Link]. Objects & Description
1 Connection
This component is used to set up a connection with a data
source.
2 Command
A command is a SQL statement or a stored procedure used to
retrieve, insert, delete or modify data in a data source.
193
Basic Computer Coding: Visual Basic
3 DataReader
Data reader is used to retrieve data from a data source in a
read-only and forward-only mode.
4 DataAdapter
This is integral to the working of [Link] since data is
transferred to and from a database through a data adapter. It
retrieves data from a database into a dataset and updates the
database. When changes are made to the dataset, the changes
in the database are actually done by the data adapter.
There are following different types of data
providers included in [Link]
■ The .Net Framework data provider
for SQL Server - provides access to
Microsoft SQL Server.
■ The .Net Framework data provider
for OLE DB - provides access to data
sources exposed by using OLE DB.
■ The .Net Framework data provider
for ODBC - provides access to data
sources exposed by ODBC.
■ The .Net Framework data provider
for Oracle - provides access to Oracle
data source.
■ The EntityClient provider - enables
accessing data through Entity Data
Model (EDM) applications.
7.1.2 DataSet
Dataset is a collection
of related, discrete DataSet is an in-memory representation of
items of related data data. It is a disconnected, cached set of records
that may be accessed that are retrieved from a database. When a
individually or in connection is established with the database,
combination or
managed as a whole
the data adapter creates a dataset and stores
entity. data in it. After the data is retrieved and stored
in a dataset, the connection with the database
is closed. This is called the ‘disconnected
194
Data Access
architecture’. The dataset works as a virtual database containing
tables, rows, and columns.
The following diagram shows the dataset object model −
The DataSet class is present in the [Link] namespace. The
following table describes all the components of DataSet −
[Link]. Components & Description
1 DataTableCollection
It contains all the tables retrieved from the data source.
2 DataRelationCollection
It contains relationships and the links between tables in a data set.
3 ExtendedProperties
It contains additional information, like the SQL statement for
retrieving data, time of retrieval, etc.
4 DataTable
It represents a table in the DataTableCollection of a dataset. It
consists of the DataRow and DataColumn objects. The DataTable
objects are case-sensitive.
5 DataRelation
It represents a relationship in the DataRelationshipCollection of
the dataset. It is used to relate two DataTable objects to each other
through the DataColumn objects.
6 DataRowCollection
It contains all the rows in a DataTable.
195
Basic Computer Coding: Visual Basic
7 DataView
It represents a fixed customized view of a DataTable for sorting,
filtering, searching, editing and navigation.
8 PrimaryKey
It represents the column that uniquely identifies a row in a
DataTable.
9 DataRow
It represents a row in the DataTable. The DataRow object and
its properties and methods are used to retrieve, evaluate, insert,
delete, and update values in the DataTable. The NewRow method
is used to create a new row and the Add method adds a row to the
table.
10 DataColumnCollection
It represents all the columns in a DataTable.
11 DataColumn
It consists of the number of columns that comprise a DataTable.
7.2 CONNECTING TO A
DATABASE
Server Explorer is the Begin by launching Visual Studio and creating
server management
console for Visual a new Windows Application project called
Studio. Use this “VBdatabase”. Once the new project has been
window to open created the first task is to connect to the
data connections and Northwind database. Click on the View menu
to log on to servers
and explore their
and select Server Explorer. The Server Explorer
databases and system panel will appear on the left hand side of the
services. main Visual Studio area:
196
Data Access
This panel allows you to browse servers on
your network and locate databases. Click on
the Connect to Database button (highlighted
above). The Add Connection dialog will appear
as follows:
Visual Basic 3.0
was released in the
summer of 1993 and
came in Standard
and Professional
versions. VB3
included version
1.1 of the Microsoft
Jet Database Engine
that could read and
write Jet (or Access)
1.x databases.
Change the Data source field to Microsoft Access
Database if necessary. Click on the Browse button
and locate the [Link] database. Once
you have selected the Northwind database
click on the Test Connection button to verify the
database is accessible. Assuming the connection
is successful, click on the OK button to apply
the connection.
The database is now connected to the application
and it is time to select a data source.
197
Basic Computer Coding: Visual Basic
The .Net Framework provides two types of
Connection classes −
■ SqlConnection − designed for
connecting to Microsoft SQL Server.
■ OleDbConnection − designed for
connecting to a wide range of
databases, like Microsoft Access and
Oracle.
Remember Example
We have a table stored in Microsoft SQL Server,
Login and logout named Customers, in a database named testDB.
events will not be Please consult ‘SQL Server’ tutorial for creating
raised on the server databases and database tables in SQL Server.
when a connection
is fetched from
Let us connect to this database. Take the
or returned to following steps −
the connection ■ Select TOOLS → Connect to Database
pool, because the
connection is not
actually closed
when it is returned
to the connection
pool.
■ Select a server name and the database
name in the Add Connection dialog
box.
198
Data Access
■ Click on the Test Connection button to check if the connection
succeeded.
■ Add a DataGridView on the form.
■ Click on the Choose Data Source combo box.
199
Basic Computer Coding: Visual Basic
■ Click on the Add Project Data Source link.
■ This opens the Data Source Configuration Wizard.
■ Select Database as the data source type
■ Choose DataSet as the database model.
200
Data Access
■ Choose the connection already set up.
■ Save the connection string.
■ Choose the database object, Customers table in our example,
and click the Finish button.
201
Basic Computer Coding: Visual Basic
■ Select the Preview Data link to see the data in the Results
grid −
When the application is run using Start button available at the
Microsoft Visual Studio tool bar, it will show the following window −
202
Data Access
Example
In this example, let us access data in a DataGridView control using
code. Take the following steps −
• Add a DataGridView control and a button in the form.
• Change the text of the button control to ‘Fill’.
• Double click the button control to add the required code for the
Click event of the button, as shown below −
Imports [Link]
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) _
Handles [Link]
‘TODO: This line of code loads data into the ‘TestDBDataSet.
CUSTOMERS’ table.
You can move, or remove it, as needed.
[Link]([Link].
CUSTOMERS)
‘ Set the caption bar text of the form.
[Link] = “[Link]”
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs)
Handles [Link]
Dim connection As SqlConnection = New sqlconnection()
[Link] = “Data Source=KABIR-
DESKTOP; _
203
Basic Computer Coding: Visual Basic
Initial Catalog=testDB;Integrated
Security=True”
[Link]()
Dim adp As SqlDataAdapter = New
SqlDataAdapter _
(“select * from Customers”, connection)
Dim ds As DataSet = New DataSet()
[Link](ds)
[Link] =
[Link](0)
End Sub
End Class
■ When the above code is executed and
Data grid is a system run using Start button available at
composed of multiple the Microsoft Visual Studio tool bar,
servers that work it will show the following window −
together to manage
information and
related operations -
such as computations
- in a distributed
environment.
■ Clicking the Fill button displays the
table on the data grid view control –
204
Data Access
7.3 CREATING TABLE, COLUMNS AND ROWS
We have discussed that the DataSet components like DataTable,
DataColumn and DataRow allow us to create tables, columns and
rows, respectively.
The following example demonstrates the concept −
Example
So far, we have used tables and databases already existing in our
computer. In this example, we will create a table, add columns, rows
and data into it and display the table using a DataGridView object.
Take the following steps −
• Add a DataGridView control and a button in the form.
• Change the text of the button control to ‘Fill’.
• Add the following code in the code editor.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs)
Handles [Link]
‘ Set the caption bar text of the form.
[Link] = “[Link]”
End Sub
205
Basic Computer Coding: Visual Basic
Private Function CreateDataSet() As DataSet
‘creating a DataSet object for tables
Dim dataset As DataSet = New DataSet()
‘ creating the student table
Dim Students As DataTable = CreateStudentTable()
[Link](Students)
Return dataset
End Function
Private Function CreateStudentTable() As DataTable
Dim Students As DataTable
Students = New DataTable(“Student”)
‘ adding columns
AddNewColumn(Students, “System.Int32”, “StudentID”)
AddNewColumn(Students, “[Link]”, “StudentName”)
AddNewColumn(Students, “[Link]”, “StudentCity”)
‘ adding rows
AddNewRow(Students, 1, “Zara Ali”, “Kolkata”)
AddNewRow(Students, 2, “Shreya Sharma”, “Delhi”)
AddNewRow(Students, 3, “Rini Mukherjee”, “Hyderabad”)
AddNewRow(Students, 4, “Sunil Dubey”, “Bikaner”)
AddNewRow(Students, 5, “Rajat Mishra”, “Patna”)
Return Students
206
Data Access
End Function
Private Sub AddNewColumn(ByRef table As DataTable, _
ByVal columnType As String, ByVal columnName As String)
Dim column As DataColumn = _
[Link](columnName, Type.
GetType(columnType))
End Sub
‘adding data into the table
Private Sub AddNewRow(ByRef table As DataTable, ByRef id
As Integer,_
ByRef name As String, ByRef city As String)
Dim newrow As DataRow = [Link]()
newrow(“StudentID”) = id
newrow(“StudentName”) = name
newrow(“StudentCity”) = city
[Link](newrow)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs)
Handles [Link]
Dim ds As New DataSet
ds = CreateDataSet()
[Link] = [Link](“Student”)
207
Basic Computer Coding: Visual Basic
End Sub
End Class
■ When the above code is executed and run using Start
button available at the Microsoft Visual Studio tool bar, it
will show the following window −
■ Clicking the Fill button displays the table on the data grid
view control −
7.4 SELECTING THE DATA SOURCE
Once the database connection is established, the next step is to
select the data source to be used in the application. To achieve
this, select the Data->Add New Data Source menu option. The Data
Source Configuration Wizard will appear as follows:
208
Data Access
Data source is the
location where data
that is being used come
from.
Since we are selecting data from a database,
make sure that Database is highlighted in
this dialog and click Next. Ensure that the
Northwind database is listed in the following
screen and press Next to proceed.
A dialog will appear asking if you wish to
move the database file to your project area.
Click Yes. Finally the wizard will display the
connection string (this the name used to refer to
the database in your code). Accept the default
suggestion and click Next. Finally, you will be
asked to select the data objects you wish to
access from your application. For the purposes
of this example click the Tables option and
press Finish.
7.4.1 Linking Data Sources to an
Application
The next step in our tutorial is to add some
data fields to our application form. The first
task is to display the Data Sources Panel by
selecting the Data->Show Data Sources menu
option. The data source panel will subsequently
appear listing all the data tables and columns
209
Basic Computer Coding: Visual Basic
that are available to us. Click on the ‘+’ sign next to the Customer
table to unfold the list of customer fields:
We are now ready to add some data columns to our form. Drag
and drop the CustomerID, CompanyName, Address and Country fields
onto the form so that they appear as follows:
Once the data fields are added you will notice that Visual Basic
adds a toolbar to the top of the form to provide navigation and the
ability to add and remove records from the database. Press F5 to
build and run the application. When the application starts the fields
will be populated with data from the database. Use the toolbar to
move through the records:
210
Data Access
You have created your first database driven
Visual Basic application.
7.4.2 Adding SQL Statements to a
Visual Basic Application
The next step in our example is to add an SQL
Query to our application. Click on the Company
Name TextBox in the form and select the Data-
>Add Query menu option. In the Search Criteria
Builder dialog change the New Query Name to
France and click on the Query Builder button.
In the Query Builder dialog, scroll down the
table until you reach the Country column. Scroll
horizontally until you reach the Filter field and
enter France as the filter criteria: TextBox is a composite
control that is composed
of several encapsulated
components.
211
Basic Computer Coding: Visual Basic
Click on OK. Visual Studio will generate the appropriate SQL
statement to perform this query.
SELECT CustomerID, CompanyName, ContactName, ContactTitle,
Address, City,
Region, PostalCode, Country, Phone, Fax FROM Customers WHERE
(Country = ‘France’)
Press F5 to rebuild and run the application. An additional toolbar
now appears labeled France which, when pressed, filters the database
entries so that only customers in France are selected:
212
Data Access
ROLE MODEL
Edgar F. Codd
Edgar Frank “Ted” Codd (19 August 1923 – 18
April 2003) was an English computer scientist
who, while working for IBM, invented the
relational model for database management, the
theoretical basis for relational databases and
relational database management systems. He
made other valuable contributions to computer
science, but the relational model, a very influential general theory
of data management, remains his most mentioned, analyzed and
celebrated achievement.
Biography
Edgar Frank Codd was born in Fortuneswell, on the Isle of Portland in
Dorset, England. After attending Poole Grammar School, he studied
mathematics and chemistry at Exeter College, Oxford, before serving
as a pilot in the RAF Coastal Command during the Second World
War, flying Sunderlands. In 1948, he moved to New York to work
for IBM as a mathematical programmer. In 1953, angered by Senator
Joseph McCarthy, Codd moved to Ottawa, Ontario, Canada. In 1957
he returned to the US working for IBM and from 1961–1965 pursuing
his doctorate in computer science at the University of Michigan in
Ann Arbor. Two years later he moved to San Jose, California, to
work at IBM’s San Jose Research Laboratory, where he continued to
work until the 1980s. He was appointed IBM Fellow in 1976. During
the 1990s, his health deteriorated and he ceased work.
Codd received the Turing Award in 1981, and in 1994 he was
inducted as a Fellow of the Association for Computing Machinery.
Codd died of heart failure at his home in Williams Island, Florida,
at the age of 79 on 18 April 2003.
Work
Codd received a PhD in 1965 from the University of Michigan, Ann
Arbor advised by John Henry Holland. His thesis was about self-
213
Basic Computer Coding: Visual Basic
replication in cellular automata, extending on work of von Neumann
and showing that a set of eight states was sufficient for universal
computation and construction. His design for a self-replicating
computer was only implemented in 2010.
In the 1960s and 1970s he worked out his theories of data arrangement,
issuing his paper “A Relational Model of Data for Large Shared Data
Banks” in 1970, after an internal IBM paper one year earlier. To his
disappointment, IBM proved slow to exploit his suggestions until
commercial rivals started implementing them.
Initially, IBM refused to implement the relational model to preserve
revenue from IMS/DB. Codd then showed IBM customers the potential
of the implementation of its model, and they in turn pressured
IBM. Then IBM included in its Future Systems project a System
R subproject – but put in charge of it developers who were not
thoroughly familiar with Codd’s ideas, and isolated the team from
Codd. As a result, they did not use Codd’s own Alpha language
but created a non-relational one, SEQUEL. Even so, SEQUEL was
so superior to pre-relational systems that it was copied, in 1979,
based on pre-launch papers presented at conferences, by Larry
Ellison, of Relational Software Inc, in his Oracle Database, which
actually reached market before SQL/DS – because of the then-
already proprietary status of the original name, SEQUEL had been
renamed SQL.
Codd continued to develop and extend his relational model,
sometimes in collaboration with Christopher J. Date. One of the
normalized forms, the Boyce–Codd normal form, is named after him.
Codd’s theorem, a result proven in his seminal work on the relational
model, equates the expressive power of relational algebra and
relational calculus (both of which, lacking recursion, are strictly
less powerful than first-order logic).
As the relational model started to become fashionable in the early
1980s, Codd fought a sometimes bitter campaign to prevent the
term being misused by database vendors who had merely added
a relational veneer to older technology. As part of this campaign,
he published his 12 rules to define what constituted a relational
database. This made his position in IBM increasingly difficult, so he
left to form his own consulting company with Chris Date and others.
214
Data Access
Codd coined the term Online analytical processing (OLAP) and wrote
the “twelve laws of online analytical processing”. Controversy
erupted, however, after it was discovered that this paper had been
sponsored by Arbor Software (subsequently Hyperion, now acquired
by Oracle), a conflict of interest that had not been disclosed, and
Computerworld withdrew the paper.
In 2004, SIGMOD renamed its highest prize to the SIGMOD Edgar
F. Codd Innovations Award, in his honor.
215
Basic Computer Coding: Visual Basic
SUMMARY
■ Data access refers to a user’s ability to access or retrieve
data stored within a database or other repository. Users who
have data access can store, retrieve, move or manipulate
stored data, which can be stored on a wide range of hard
drives and external devices.
■ Data access is a feature of Visual Basic that allows you
to access and manipulate any database from Visual Basic.
The database may be either MS-Access database or FoxPro
database or it may also be any of the relational databases
such as Oracle. You can develop applications in Visual
Basic that can access data in a database.
■ [Link] object model is nothing but the structured process
flow through various components.
■ A data provider is used for connecting to a database,
executing commands and retrieving data, storing it in
a dataset, reading the retrieved data and updating the
database.
■ DataSet is an in-memory representation of data. It is a
disconnected, cached set of records that are retrieved from
a database. When a connection is established with the
database, the data adapter creates a dataset and stores data
in it. After the data is retrieved and stored in a dataset, the
connection with the database is closed. This is called the
‘disconnected architecture’. The dataset works as a virtual
database containing tables, rows, and columns.
■ Begin by launching Visual Studio and creating a new
Windows Application project called “VBdatabase”. Once
the new project has been created the first task is to connect
to the Northwind database. Click on the View menu and
select Server Explorer.
■ Once the database connection is established, the next step
is to select the data source to be used in the application.
To achieve this, select the Data->Add New Data Source menu
option.
216
Data Access
KNOWLEDGE CHECK
1. A collection of data designed to be used by different people
is called a/an
a. Organization
b. Database
c. Relationship
d. Schema
2. Which of the following is the oldest database model?
a. Relational
b. Deductive
c. Physical
d. Network
3. Which of the following is an attribute that can uniquely
identify a row in a table?
a. Secondary key
b. Candidate key
c. Foreign key
d. Alternate key
4. Which of the following is the process of selecting the data
storage and data access characteristics of the database?
a. Logical database design
b. Physical database design
c. Testing and performance tuning
d. Evaluation and selecting
5. Which of the following terms does refer to the correctness
and completeness of the data in a database?
a. Data security
b. Data constraint
c. Data independence
d. Data integrity
217
Basic Computer Coding: Visual Basic
REVIEW QUESTIONS
1. What is the use of data provider?
2. What is dataset? Describe the components of dataset.
3. How to create table, columns and rows. Discuss.
4. How to select the data source? How to link data sources
to an application? Explain.
5. How to add SQL statements to a visual basic application?
Describe.
Check your Result
1. (b) 2. (d) 3. (b) 4. (b) 5. (d)
218
Data Access
REFERENCES
1. Connolly, Thomas and Carolyn Begg. Database Systems.
New York: Harlow, 2002.
2. Hitchhiker’s Guide to Visual Studio and SQL Server (7th
Edition) Addison Wesley, William Vaughn, ISBN 978-0-
321-24362-1
3. [Link]
[Link]
4. [Link]
ms524771(v=vs.90).aspx
5. [Link]
6. [Link]
Databases_Using_Visual_Basic
7. [Link]
[Link]
8. Kroenke, David M. and David J. Auer. Database Concepts.
3rd ed. New York: Prentice, 2007.
9. Lightstone, S.; Teorey, T.; Nadeau, T. (2007). Physical
Database Design: the database professional’s guide to
exploiting indexes, views, storage, and more. Morgan
Kaufmann Press. ISBN 0-12-369389-6.
10. Ling Liu and Tamer M. Özsu (Eds.) (2009). “Encyclopedia
of Database Systems, 4100 p. 60 illus. ISBN 978-0-387-
49616-0.
11. Teorey, T.; Lightstone, S. and Nadeau, T. Database
Modeling & Design: Logical Design, 4th edition, Morgan
Kaufmann Press, 2005. ISBN 0-12-685352-5
219
INDEX
A command 193
Common language runtime 31,
ActiveX controls 89, 95, 97 33
[Link] object model 191, 192, Const Statement 71
216 Control statement 70
assignment statement 74, 94
D
B
Data access 192, 216
Binary data 35, 36 database 191, 192, 193, 194, 196,
Boolean Data Type 34 197, 198, 200, 201, 208, 209,
Boolean expression 77, 78 210, 211, 212, 213, 214, 216,
C 217, 219
Database system 4
Case statements 75, 83 DataColumn 195, 196, 205, 207
Char data type 37 data provider 193, 194, 216, 218
Class Statement 71 Data reader 194
DataRow 195, 196, 205, 207
Basic Computer Coding: Visual Basic
dataset 193, 194, 195, 206, 216, executable statement 73, 94
218 external devices 192, 216
DataSet class 195
F
data source 191, 193, 194, 195,
197, 200, 208, 209, 216, 218 Floating-point data type 42
data store 193 FoxPro database 192, 216
DataTable 195, 196, 205, 206, 207 Function procedure 163
Data type 30, 33, 34, 35, 36, 38, Function Statement 72
39, 40, 41, 42, 45, 51, 56, 57,
58, 59, 64, 65, 67 G
Debugging 127, 128, 130, 131, General procedure 161, 186
132, 133, 135, 137, 151, 153, Global variable 44
154 Graphical user interface GUI 3,
Debug menu 134, 135, 136, 137, 24
151
Debug toolbar 133 H
Debug window 137, 138, 139, hard drives 192, 216
151, 152
Decimal data type 39 I
Decision making structures 74, If statement 76, 77, 79, 81
94 If-Then-Else statements 81
declaration statements 70, 71, 94, if-then statement 76
97 Insertable Objects 89
Declare Statement 73 Interactive development environ-
Delegate Statement 73 ment (\“IDE\“) 6
Dim Statement 71 Interface Statement 72
disconnected architecture 195, intrinsic controls 88, 95, 97
216
Drop-down 103 L
Dynamic array 177, 178, 179, 180,
Logic errors 128, 130
189
M
E
Memory consumption 33
Else statement 75, 77, 79
Menu Editor 106, 108, 123
EntityClient provider 194
Microsoft Access 197, 198
Entity Data Model (EDM) 194
Microsoft Access Database 197
Enum Statement 71
Microsoft ActiveX Data Objects.
Event procedure 161, 186
Net ([Link]) 192
Event Statement 73
222
Index
Microsoft application 9, 24 Server Explorer 196, 216
Microsoft SQL Server 194, 198 Single Document Interface (SDI)
Module Statement 72 101, 109
MS-Access database 192, 216 SQL Query 211
Multiple Document Interface Statements 69, 70, 71, 73, 81, 94
(MDI) 101, 109 Static array 177
Static variable 47, 48, 49, 50
O
Structure Statement 72
One-dimensional array 173, 187 Sub procedure 158, 159
Operator Statement 73 Sub Statement 72
Syntax errors 128
P
V
Private statement 44
Procedure-level variable 44, 47 VBdatabase 196, 216
Procedure parameter 158 Visual Basic 1, 2, 3, 4, 6, 7, 8, 9,
programming elements 71 11, 13, 15, 16, 17, 20, 22, 24,
Programming languages 156, 186 25, 31, 34, 35, 38, 39, 40, 42,
program’s execution 70 44, 45, 46, 50, 51, 52, 53, 55,
Property procedure 166, 167, 169, 58, 59, 60, 64, 65, 66, 68, 70,
186 85, 86, 88, 89, 94, 95, 96, 98,
Property Statement 73 100, 106, 123, 156, 157, 160,
163, 166, 171, 180, 184, 186,
R 190, 192, 197, 210, 211, 216
Rapid application development Visual Basic application 192, 211
(\“RAD\”) 6 Visual Basic control 85
Resume keyword 146 Visual Basic Objects 86, 94
retrieving data 193, 195, 216 Visual Studio Code 46
Ruby Programming Language 4 W
Run-time errors 128
Windows Application project
S 196, 216
Select Case statement 75, 82
223