0% found this document useful (0 votes)
9 views326 pages

Sanet - St-Basic Computer Coding - Visual Basic 2e

The document is the 2nd edition of 'Basic Computer Coding: Visual Basic', published by BIBLIOTEX Digital Library, which provides an introduction to the Visual Basic programming language. It covers the language's history, features, and its applications in software development, emphasizing its ease of use and graphical interface. The book also includes contributions from various experts in related fields and is structured with chapters that facilitate learning through keywords, review questions, and references.

Uploaded by

a bdo
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views326 pages

Sanet - St-Basic Computer Coding - Visual Basic 2e

The document is the 2nd edition of 'Basic Computer Coding: Visual Basic', published by BIBLIOTEX Digital Library, which provides an introduction to the Visual Basic programming language. It covers the language's history, features, and its applications in software development, emphasizing its ease of use and graphical interface. The book also includes contributions from various experts in related fields and is structured with chapters that facilitate learning through keywords, review questions, and references.

Uploaded by

a bdo
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

BASIC COMPUTER CODING:

VISUAL BASIC

2nd Edition

BIBLIOTEX Digital Library

[Link]
BASIC COMPUTER CODING: VISUAL BASIC

2ND EDITION

BIBLIOTEX Digital Library

[Link]
email: info@[Link]

e-book Edition 2022


ISBN: 978-1-98467-610-8 (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.

© 2022 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-98465-903-3
EDITORIAL BOARD
Aleksandar Mratinković was 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.

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

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.
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.
HOW TO USE THE BOOK
This book has been divided into many chapters. Chapter gives the motivation for this book and the use
of templates. The text is presented in the simplest language. Each paragraph has been arranged under
a suitable heading for easy retention of concept. Keywords are the words that academics use to reveal
the internal structure of an author’s reasoning. Review questions at the end of each chapter ask students
to review or explain the concepts. References provides the reader an additional source through which
he/she can obtain more information regarding the topic.

4 Basic Computer Coding: Visual Basic

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

LEARNING OBJECTIVES
1
a number of programs to show concern. The community members then created a lobby
CHAPTER of users and a petition was signed by them. The basic aim of this petition was to ensure
INTRODUCTION that the product remains alive. However, the petition did not attain its aim effectively.

TO VISUAL BASIC 1.1.2 The Importance of Visual Basic Programming Language

See what you are going to cover and what you Visual Basic is regarded as the third generation event-driven programming language.
It was released in 1987. Being the first visual development tool from Microsoft, it is
considered as one of the most powerful programming languages. As compared to other

should already know at the start of each chapter


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
“I know blind programmers who work in C and Visual Basic in addition to mainframe languages, components that are used on forms having specific attributes and actions with the help
because as long as they can get at a text file, they can do programming. But if the graphical tool kit of those components. On the one hand it allows programmers to develop widows based
you are using requires you to drag and drop items on the screen, you can’t do it.” 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
–Curtis Chong,
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.
LEARNING As compared to other languages, Visual basic may be slower though, yet it is

ABOUT THIS CHAPTER


OBJECTIVES flexible and it can be rightly said that things that are difficult in other languages are
After studying this chapter, comparatively easier in visual basic programming language. It may also be said that,
you will be able to: since it is one of the most popular programming languages, lots of related books
1. Overview of meaning of and material and other resources are available and can be accessed for developing
visual basic
2. Discuss the visual basic
programming skills at visual basic programming language conveniently.

An introduction is a beginning of section which


environment One of the most important things to be considered with regard to programming in
3. Describe the building Visual basic is that the structure of VB is designed in a way that allows programmers
VB applications
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,

states the purpose and goals of the topics which


one can change the abstract ideas into programs or into the whole software while it
INTRODUCTION allows revising and modifying the programs fittingly.
Visual Basic (VB) is an event-driven programming
language and environment from Microsoft that provides

are discussed in the chapter. It also starts the topics


in brief.
3G E-LEARNING

REMEMBER
2 Basic Computer Coding: Visual Basic Introduction to Visual Basic 3

This revitalizes a must read information of the a graphical user interface (GUI) which allows programmers
to modify code by simply dragging and dropping objects and
defining their behavior and appearance. VB is derived from
the programmer. Another feature, called “AutoCorrect,” can
debug the code while the program is running.
Programs created with Visual Basic can be designed to

topic.
the BASIC programming language and is considered to be run on Windows, on the Web, within Office applications, or
event-driven and object-oriented. on mobile devices. Visual Studio, the most comprehensive Remember
VB development environment, or IDE, can be used to create
VB is intended to be easy to learn and fast to write programs for all these mediums. Visual Studio .NET provides Visual
code with; as a result, it is sometimes called a rapid Basic
development tools to create programs based on the .NET is available as
application development (RAD) system and is used framework, such as [Link] applications, which are often a streamlined
to prototype an application that will later be written in a deployed on the Web. application that
more difficult but efficient language. is used primarily
by beginning
1.1.1 History of Visual Basic developers and
for educational
The first version of visual basic, VB 1.0, was announced in the purposes.

KEYWORDS
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 that is programmable for

This section contains some important definitions


Windows 3.0. This system was developed under the code name
The last version of VB, Visual Basic 6, was released in of Ruby, which has no relationship with the Ruby Programming
1998, but has since been replaced by VB .NET, Visual Basic for Language. Tripod did not have any programming language at
applications (VBA) and Visual Stuido .NET. VBA and Visual all. Microsoft then decided to use Ruby in combination with

that are discussed in the chapter. A keyword is


Studio are the two frameworks most commonly used today. basic language to develop visual basic.
Keyword The interface of Ruby contributed the “visual” component
The of the Visual Basic programming language. This was then
graphical 1.1 MEANING OF VISUAL BASIC amalgamated with the Embedded BASIC engine that was

an index entry that identifies a specific record


user interface
(GUI), is a type
Visual Basic is a programming language and development developed for the ceased “Omega” database system of
of user interface environment created by Microsoft. It is an extension of the Microsoft.
that allows users BASIC programming language that combines BASIC functions The introduction of version 5.0, in the month of February
to interact with and commands with visual controls. Visual Basic provides a in 1997, Microsoft exclusively released a visual basic that

or document. It also gives the extra information


electronic devices graphical user interface GUI that allows the developer to was compatible with 32-bit Microsoft Windows versions. The
through graphical
icons and visual drag and drop objects into the program as well as manually programmers who had a preference for writing programs in
indicators such write program code. 16-bit could do it in versions between 4.0 and 5.0. In addition
as secondary to that the programs written Visual Basic 5.0 can be converted
Visual Basic, also referred to as “VB,” is designed to

to the reader and an easy way to remember the


notation, instead to Version 4.0 programs in an easy manner. The version 5.0
of text-based user make software development easy and efficient, while still
also has the ability of compilation with native execution code
interfaces, typed being powerful enough to create advanced programs. For of Windows, and introduction of custom user controls.
command labels or example, the Visual Basic language is designed to be “human
The introduction of Visual Basic 6.0 was made in the

word definition.
text navigation. readable,” which means the source code can be understood
middle of 1998. This version also came with a number of
without requiring lots of comments. The Visual Basic program
also includes features like “IntelliSense” and “Code Snippets,”
which automatically generate code for visual objects added by 3G E-LEARNING

3G E-LEARNING

v
DID YOU KNOW? 38 Basic Computer Coding: Visual Basic
6 Basic Computer Coding: Visual Basic

This section equip readers the interesting facts and 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
■ There are some, fairly minor disadvantages compared
with C. C has better declaration of arrays – its possible

figures of the topic.


to initialize an array of structures in C at declaration
to hold the variable as soon as the declaration statement is
time; this is impossible in VB.
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 1.2 VISUAL BASIC ENVIRONMENT
variable.
Did You On start up, Visual Basic 6.0 will display the following dialog
Know? box as shown in figure 1. You can choose to start a new
2.2.2 Comparing Implicit and Explicit Variable project, open an existing project or select a list of recently
Visual
Performance Basic 1.0 for DOS opened programs. A project is a collection of files that make
was released in up your application. There are various types of applications

EXAMPLE The default data type for Visual Basic variables is the variant. September 1992. we could create, however, we shall concentrate on creating
This means that, unless you specify otherwise, every variable The language Standard EXE programs (EXE means executable program).
itself was not
in your application will be a variant. The data type is not quite compatible
Now, click on the Standard EXE icon to go into the actual
very efficient. Its data storage requirements are greater than with Visual Basic VB programming environment.
for Windows, as

The book cabinets’ examples to illustrate specific


the equivalent simple data type. The computer spends more
time keeping track of the data type contained in a variant it was actually
the next version
than for other data types. of Microsoft’s
DOS-based

ideas in each chapter.


BASIC compilers,
Variable names can’t be duplicated with the same scope. This means, that Microsoft
you can’t have two variables of the same name within a procedure. You can, QuickBASIC
however, have two variables with the same name in two different procedures. compiler and
the BASIC
Professional
Development
An explicit declaration statically types the variable it System 7.1. The
declares. In a language that requires explicit declaration, you interface was
will get a compilation error for any reference to a variable barely graphical,
using extended Figure 1: The Visual Basic Start-up Dialog Box.
that has not been explicitly declared. ASCII characters
By contrast, in a language that supports implicit declaration, to simulate the In figure 2, the Visual Basic Environment consists of the
simply using a variable in code implies the declaration. If your appearance of a ■ The Blank Form window which you can design your
GUI.
code assigns a string to the variable, then it is declared to be application’s interface.
a string. ■ The Project window displays the files that are created
Convenient, yes? Not so much. Any time you misspell a in your application.
variable name you get a new one and the program moves on, ■ The Properties window which displays the properties
with incorrect conditional behavior or a wrongly computed of various controls and objects that are created in
value. your applications.
Given the rise of very smart editors like Visual Studio It also includes a Toolbox that consists of all the controls
Code, implicit declaration need not be the menace it was, essential for developing a VB Application. Controls are tools
at least for languages that support the notion of optional

3G E-LEARNING

ROLE MODEL
Introduction to Visual Basic 19 50 Basic Computer Coding: Visual Basic

A biography of someone who has/had acquired ROLE MODEL CASE STUDY


remarkable success in their respective field as ALAN COOPER: FATHER OF VISUAL BA- FUJITSU FACILITATES SMOOTH MIGRATION TO [Link] AT
SIC AN POST
Role Models are important because they give us Born in San Francisco in 1952 and raised in Marin
County, California, Alan Cooper has always taken the path
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

the ability to imagine our future selves. 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
of our mission-critical application gained from several years’ development and support
work.

course in programming, it became clear that his future was


Challenge
in architecture—software architecture. After getting his
associate degree and a COBOL programming job, he saw an A Post, one of Ireland’s largest companies, is a major commercial organization providing
advertisement for one of the first personal computers and a wide range of postal, communication, retail and financial services. With 9,600
.conceived an idea for a new business venture employees throughout its national network of retail, processing and delivery points,

CASE STUDY 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
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
for microcomputers.” In four years, Cooper wrote and shipped salary and wages functions. The Staff Remuneration and Administration Management

This reveals what students need to create and a dozen application programs. SSG became the archetype
for many software startups in the early days of the personal
System (STREAMS) is a bespoke, mission-critical application developed by Fujitsu as
a reliable, scalable client server system using Microsoft technologies. The STREAMS
computer revolution. front-end system gathers information and feeds the data to the company’s HR, payroll

provide an opportunity for the development of key During the 1980s, after leaving SSG, Cooper invented,
wrote, and sold three major software packages to prominent
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
skills such as communication, group working and
publishers. One of those was the visual programming front-
end code named “Ruby,” for what became Visual BASIC. Bill center reporting, significantly lowered the time to record pay details and enhanced
Gates purchased it from Cooper in 1988, noting that it would the processing of casual staff pay. During this period, Fujitsu provided quality support

problem solving.
have significant impact across Microsoft’s entire product line. and maintenance services and application enhancements to increase functionality,
Visual BASIC was deemed both a commercial and critical ensuring the long-term reliability of [Link] to Visual
For instance, Basic
as employee23numbers

success, earning Cooper the moniker “Father of Visual BASIC.” steadily increased to exceed original expectations, Fujitsu boosted system performance
d. None of the above.
Visual BASIC has influenced integrated development languages by upgrading the infrastructure and optimizing the software. STREAMS originally
8. The Properties window plays an important role in the development of Visual
ever since. employed Visual
Basic Basic (VB),
applications. It isa mainly
third-generation
used event-driven programming language and
integrated development environment (IDE) from Microsoft. IDE provides programmers
In 1990 Cooper became fascinated with the challenge of a. to change how objects look and feel.
making software products that were easy to use and understand.
with comprehensive facilities for software development and comprises a source code
b. when opening programs stored on a hard drive.
He and his wife, Susan, founded Cooper Interaction Design editor, a compiler and/or an interpreter, build automation tools and a debugger.
c. to allow the developer to graphically design program components.
(now “Cooper”) to assist in what Cooper calls “interaction However, Microsoft no longer supports VB version 6.0, the edition employed by A
d. to set program related options like Program Name, Program Location, etc.
design.” In the design field, Cooper’s software development Post. Syl Byrne, IT Manager Remuneration Services, A Post, explains: “To ensure that
9. Pseudocode is
background was unique and, over the next few years, he our business-critical application is future-proof, we needed to move to a platform that
a. data that have been encoded for security.
invented many of the tools and techniques now standard in Microsoft will support for the foreseeable future.” A Post therefore decided to migrate
b. the incorrect results of a computer program.
the user experience industry, including personas and scenarios, STREAMS to the [Link] platform, an object-orientated programming language. This
strategyc. would
a program that doesn’t work.
protect its investment for the next 10 years by creating a secure, scalable
d. the obscure language computer personnel use when speaking.
e. a description of an algorithm similar to a computer language.
3G E-LEARNING
10. Which of the properties in a control’s list of properties is used to give the
3G E-LEARNING
control a meaningful name?
a. Text
b. ContextMenu
c. ControlName
d. Name

KNOWLEDGE CHECK 22 Basic Computer Coding: Visual Basic


REVIEW QUESTIONS
KNOWLEDGE CHECK 1. What is visual basic? Why are importance of visual basic programming

This is given to the students for progress check


language?
1. The Visual Basic Code Editor will automatically detect certain types of errors 2. What is visual basic environment?
as you are entering code.
3. Describe the structure of a visual basic application.
a. True

at the end of each chapter.


4. How to creating your first application?
b. False 5. Discuss the saving projects in VB.
2. Keywords are also referred to as reserved words.
Check Your Result
a. True
b. False 1. (a) 2. (a) 3. (a) 4. (b) 5. (a)
6. (c) 7. (c) 8. (a) 9. (e) 10. (d)
3. The divide-and-conquer-method of problem solving breaks a problem into large,
general pieces first, then refines each piece until the problem is manageable.

REVIEW QUESTIONS
a. True
b. False
4. Visual Basic responds to events using which of the following? 3G E-LEARNING

a. a code procedure 24 Basic Computer Coding: Visual Basic

This section is to analyze the knowledge and ability b.


c.
an event procedure
a form procedure
REFERENCES

of the reader. d. a property 1. Cox, Philip T, Visual Programming Languages. In in Encyclopedia of Computer
Science and Engineering, B.W. Wah (Ed.), John Wiley & Sons Inc., Hoboken,
5. When the user clicks a button, _________ is triggered. (June 2008).
a. an event 2. Kindborg, Mikael, How Children Understand Concurrent Comics: Experiences
b. a method from LOFI and HIFI Prototypes. In 2001 IEEE Symposia on Human-Centric
c. a setting Computing Languages and Environments , Stresa, Italy, September 2001.
d. a property 3. Ryder, Barbara, Mary Lou Soffa and Margaret Burnett, The Impact of Software
Engineering Research on Modern Programming Languages. In ACM Transactions

REFERENCES
6. What property of controls tells the order they receive the focus when the tab
on Software Engineering and Methodology, October, 2005. Pages 431 to 477.
key is pressed during run time?
4. Störrle, Harald, VMQL: A Generic Visual Model Query Language. In IEEE
a. Focus order
Symposium on Visual Languages/Human Centric Computing, Corvallis, Oregon,
b. Focus number September 2009.

References refer those books which discuss the c.


d.
Tab index
Control order
5. Zhang, Kang, Visual Languages and Applications. In Research Manuscript,
Springer, 2007.

topics given in the chapters in almost same man­ner.


7. Sizing Handles make it very easy to resize virtually any control when developing
applications with Visual Basic. When working in the Form Designer, how are
these sizing handles displayed?
a. A rectangle with 4 arrows, one in each corner, around your control.
b. A 3-D outline around your control.
c. A rectangle with small squares around your control.

3G E-LEARNING

vi

3G E-LEARNING
TABLE OF
CONTENTS
Preface xiii

Chapter 1 Introduction to Visual Basic 1


Introduction 1
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 5
1.2 Visual Basic Environment 6
1.3 Building VB Applications 7
1.3.1 Creating Your First Application 7
1.3.2 Steps in Building a Visual Basic Application 11
1.3.3 Structure of a Visual Basic Application 13
1.3.4 Drawing the User Interface and Setting Properties 13
1.3.5 Saving Projects 17
Summary 21
Knowledge Check 22
Review Questions 23
References 24

Chapter 2 Data Types, Constants and Variables 25


Introduction 25
2.1 Data Types 26
2.1.1 Memory Consumption 28
2.1.2 Composite Data Types 28
2.1.3 Boolean Data Type 29
2.1.4 Byte Data Type 30
2.1.5 Char Data Type 31
2.1.6 Decimal Data Type 33
2.1.7 Double Data Type 34
2.1.8 Integer data type 35
2.2 Variables in Visual Basic 37
2.2.1 Declaring Variables 37
2.2.2 Comparing Implicit and Explicit Variable Performance 38
2.2.3 Providing Names for the Variables 39
2.2.4 Static Variables 39
2.2.5 Forcing Explicit Declaration 42
2.2.6 Using a Naming Convention 42
2.2.7 Understanding Variable Scope and Lifetime 43
2.3 Constants in Visual Basic 44
2.3.1 User-Defined Constants 45
2.3.2 Declare a Constant 46
2.3.3 Constant and Literal Data Types 47
Summary 53
Knowledge Check 54
Review Questions 56
References 57

Chapter 3 Control Statements and Tools 59


Introduction 59
3.1 Statement 60
3.1.1 Declaration Statements 60
3.1.2 Executable Statements 63
3.2 Decision Making Structures 64
3.2.1 If...Then Statement 65
3.2.2 If...Then...Else Statement 67
3.2.3 The If...Else If...Else Statement 68
3.2.4 Nested If Statements 70
3.2.5 Select Case Statement 71
3.2.6 Nested Select Case Statement 73
3.3 Visual Basic Control 74
3.3.1 Control Properties 74
3.3.2 Control Methods 75
3.3.3 Control Events 75
3.4. Visual Basic Control Tools 76
3.4.1 Intrinsic Controls 76
3.4.2 ActiveX Controls 77

viii
3.4.3 Insertable Objects 77
Summary 82
Knowledge Check 84
Review Questions 85
References 86

Chapter 4 Menu Bar and Dialog Boxes 87


Introduction 87
4.1 Menu Bar 88
4.1.1 Adding Menu Bar Using Visual Basic’s Application Wizard 88
4.1.2 Adding Menu Bar Using Menu Editor 94
4.2 Dialog Boxes 97
4.2.1 Using a Parent Control 98
4.2.2 Dialog Box Creation 99
4.2.3 Characteristics of Dialog Boxes 100
4.2.4 Modal and Modeless Dialog Boxes 105
Summary 109
Knowledge Check 110
Review Questions 111
References 112

Chapter 5 Executing the Debugging 113


Introduction 113
5.1 Error Types 114
5.1.1 Syntax Errors 114
5.1.2 Run-time Errors 115
5.1.3 Logic Errors 115
5.2 Debugging Visual Basic Programs 116
5.3 Debugging Tools 118
5.4 Error Handling 123
5.4.1 In Case of Error, Jump To Label 126
5.4.2 In Case of Error, Jump To Line # 128
5.4.3 Resume 129
Summary 133
Knowledge Check 135
Review Questions 136
References 137

ix
Chapter 6 Procedures and Arrays 139
Introduction 139
6.1 Basics of Procedures 140
6.1.1 Sub Procedures 140
6.1.2 Event Procedures 144
6.1.3 General Procedures 144
6.1.4 Function Procedures 145
6.1.5 Property Procedures 148
6.2 Arrays in Visual Basic 151
6.2.1 Dimension of an Array 153
6.2.2 Dynamic Array 156
6.2.3 Retrieving the Contents of an Array 159
6.2.4 Multidimensional Arrays 160
Summary 163
Knowledge Check 165
Review Questions 167
References 168

Chapter 7 Data Access 169


Introduction 169
7.1 [Link] Object Model 170
7.1.1 Data Provider 171
7.1.2 DataSet 172
7.2 Connecting to a Database 174
7.3 Creating Table, Columns and Rows 182
7.4 Selecting the Data Source 184
7.4.1 Linking Data Sources to an Application 185
7.4.2 Adding SQL Statements to a Visual Basic Application 186
Summary 190
Knowledge Check 191
Review Questions 192
References 193

Chapter 8 List, Loops and Printing 195


Introduction 195
8.1 List Boxes & Combo Boxes 197
8.1.1 List Box 197
8.1.2 Combo Box 200

x
8.2 Filling the List using Property window 209
8.2.1 Properties of the ListBox Control 209
8.2.2 Methods of the ListBox Control 211
8.2.3 Events of the ListBox Control 212
8.3 Clear Method 217
8.3.1 Syntax 218
8.3.2 Remarks 218
8.3.3 Example 218
8.4 Do/Loops 219
8.4.1 Do Until 219
8.4.2 Do While 220
8.4.3 Operators 220
8.4.4 Loop While and Loop Until 221
8.5 For/Next Loops 222
8.5.1 Syntax 222
8.5.2 Parts 223
8.5.3 Simple Examples 223
8.5.4 Nesting Loops 224
8.5.5 Exit For and Continue For 225
8.5.6 Technical Implementation 226
8.5.7 Step Argument 226
8.5.8 Counter Argument 227
8.6 Using MsgBox Function 230
8.6.1 Syntax 230
8.6.2 Parameter Description 230
8.6.3 Return Values 232
8.6.4 Example 232
8.7 Using String Function 234
8.7.1 Declaration and Initialization of [Link] 234
8.7.2 Working with [Link] String Functions 234
8.8 Printing to printer using Print Method 238
8.8.1 Printing with the semicolon (;) separator 239
Summary 246
Knowledge Check 248
Review Questions 249
References 251

xi
Chapter 9 Object-Oriented Programming 253
Introduction 253
9.1 Classes and Objects 254
9.1.1 Class members 263
9.1.2 Properties and Fields 263
9.1.3 Methods 264
9.1.4 Constructors 265
9.1.5 Destructors 265
9.1.6 Events 265
9.1.7 Nested classes 266
9.1.8 Access modifiers and access levels 266
9.1.9 Instantiating classes 267
9.1.10 Shared Classes and Members 267
9.1.11 Anonymous Types 268
9.2 Inheritance 274
9.2.1 Visual Basic Inheritance Syntax 274
9.2.2 Visual Basic Inheritance Example 275
9.2.3 Visual Basic Multi-Level Inheritance 277
9.2.4 Visual Basic Multiple Inheritance 280
9.2.5 Advantages of Inheritance in [Link] 280
9.3 Interfaces 281
9.3.1 Multiple inheritance 285
9.4 Generics 288
9.4.1 Visual Basic Generics Declaration 288
9.4.2 Visual Basic Generic Class Example 289
9.4.3 Visual Basic Generic Class as Base / Derived Class 290
9.4.4 Visual Basic Generic Delegates 293
9.5 Delegates 294
9.5.1 Delegates and Events 294
9.5.2 Declaring Events that Use an Existing Delegate Type 295
9.5.3 Delegate Variables and Parameters 295
9.5.4 AddressOf and Lambda Expressions 295
Summary 301
Knowledge Check 302
Review Questions 303
References 305

Index 307
PREFACE
Visual Basic (VB) is an event-driven programming language and environment
from Microsoft that provides a graphical user interface (GUI) which allows
programmers to modify code by simply dragging and dropping objects
and defining their behavior and appearance. VB is derived from the BASIC
programming language and is considered to be event-driven and object-
oriented. Businesses and organizations can use Visual Basic for applications
(VBA) to customize Excel for their unique purposes, such as pulling certain
statistics or information from a spreadsheet. Businesses and organizations
can also use VBA externally, or in non-Microsoft applications, by applying
a technology called a component object model (COM) interface that enables
commands to communicate across computer boundaries. This allows VBA
to be used on an enterprise-specific application.

Organization of the Book


This edition is comprised of nine chapters. New chapters are added in
this edition. 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.
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 8 aims to focus on List, Loops and Printing. A loop is series of one
or more statements that executes more than one time. Loop statement repeats
until a certain predefined condition is true.
Chapter 9 intends to cover on Object-Oriented Programming. It highlights on
classes and objects. It also explain inheritance and interfaces.

xiv
1
CHAPTER

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:
1. Overview of meaning of
visual basic
2. Discuss the visual basic
environment
3. Describe the building
VB applications

INTRODUCTION
Visual Basic (VB) is an event-driven programming
language and environment from Microsoft that provides
2 Basic Computer Coding: Visual Basic

a graphical user interface (GUI) which allows programmers


to modify code by simply dragging and dropping objects and
defining their behavior and appearance. VB is derived from
the BASIC programming language and is considered to be
event-driven and object-oriented.
VB is intended to be easy to learn and fast to write
code with; as a result, it is sometimes called a rapid
application development (RAD) system and is used
to prototype an application that will later be written in a
more difficult but efficient language.

The last version of VB, Visual Basic 6, was released in


1998, but has since been replaced by VB .NET, Visual Basic for
applications (VBA) and Visual Stuido .NET. VBA and Visual
Studio are the two frameworks most commonly used today.
Keyword
The
graphical 1.1 MEANING OF VISUAL BASIC
user interface
(GUI), is a type
Visual Basic is a programming language and development
of user interface environment created by Microsoft. It is an extension of the
that allows users BASIC programming language that combines BASIC functions
to interact with and commands with visual controls. Visual Basic provides a
electronic devices graphical user interface GUI that allows the developer to
through graphical
icons and visual drag and drop objects into the program as well as manually
indicators such write program code.
as secondary Visual Basic, also referred to as “VB,” is designed to
notation, instead
of text-based user make software development easy and efficient, while still
interfaces, typed being powerful enough to create advanced programs. For
command labels or example, the Visual Basic language is designed to be “human
text navigation. readable,” which means the source code can be understood
without requiring lots of comments. The Visual Basic program
also includes features like “IntelliSense” and “Code Snippets,”
which automatically generate code for visual objects added by

3G E-LEARNING
Introduction to Visual Basic 3

the programmer. Another feature, called “AutoCorrect,” can


debug the code while the program is running.
Programs created with Visual Basic can be designed to
run on Windows, on the Web, within Office applications, or
on mobile devices. Visual Studio, the most comprehensive Remember
VB development environment, or IDE, can be used to create
programs for all these mediums. Visual Studio .NET provides Visual
Basic
development tools to create programs based on the .NET is available as
framework, such as [Link] applications, which are often a streamlined
deployed on the Web. application that
is used primarily
by beginning
1.1.1 History of Visual Basic developers and
for educational
The first version of visual basic, VB 1.0, was announced in the purposes.
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 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

3G E-LEARNING
4 Basic Computer Coding: Visual Basic

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

3G E-LEARNING
Introduction to Visual Basic 5

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

Disadvantages
■■ Visual basic is a proprietary programming language written by Microsoft,
so programs written in Visual basic cannot, easily, be transferred to other
operating systems.

3G E-LEARNING
6 Basic Computer Coding: Visual Basic

■■ There are some, fairly minor disadvantages compared


with C. C has better declaration of arrays – its possible
to initialize an array of structures in C at declaration
time; this is impossible in VB.

1.2 VISUAL BASIC ENVIRONMENT


Did You On start up, Visual Basic 6.0 will display the following dialog
Know? box as shown in figure 1. You can choose to start a new
Visual
project, open an existing project or select a list of recently
Basic 1.0 for DOS opened programs. A project is a collection of files that make
was released in up your application. There are various types of applications
September 1992. we could create, however, we shall concentrate on creating
The language Standard EXE programs (EXE means executable program).
itself was not
quite compatible
Now, click on the Standard EXE icon to go into the actual
with Visual Basic VB programming environment.
for Windows, as
it was actually
the next version
of Microsoft’s
DOS-based
BASIC compilers,
Microsoft
QuickBASIC
compiler and
the BASIC
Professional
Development
System 7.1. The
interface was
barely graphical,
using extended Figure 1: The Visual Basic Start-up Dialog Box.
ASCII characters
to simulate the In figure 2, the Visual Basic Environment consists of the
appearance of a ■■ The Blank Form window which you can design your
GUI.
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

3G E-LEARNING
Introduction to Visual Basic 7

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.

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.

3G E-LEARNING
8 Basic Computer Coding: Visual Basic

Figure 3: The VB6 Source Code Window.


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.

3G E-LEARNING
Introduction to Visual Basic 9

Figure 5: List of Procedures.


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

3G E-LEARNING
10 Basic Computer Coding: Visual Basic

Print 20 - 10
Print 20 * 10
Print 20 / 10

End Sub

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:

3G E-LEARNING
Introduction to Visual Basic 11

Option Explicit
Dim Count As Integer
Private Sub Form_Load()
Count = 0
[Link] = 1000 ‘ units of milliseconds
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

3G E-LEARNING
12 Basic Computer Coding: Visual Basic

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.
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)
Keyword End Sub
The user Private Sub Cmd_fgColor_Click()
interface Dim r, g, b As Integer
in the industrial
design field r = Int(Rnd() * 256)
of human– g = Int(Rnd() * 256)
computer
interaction, is
b = Int(Rnd() * 256)
the space where Lbl_Msg.ForeColor = RGB(r, g, b)
interactions End Sub
between humans
and machines When you run the program, each time you press on the
occur. ‘Change Background Color’ button, you will see different
background color. Similarly, each time you press on the
‘Change Foreground Color’, you will see the message on the
Label changes color. The output is shown in Figure 7.

3G E-LEARNING
Introduction to Visual Basic 13

Figure 7:

1.3.3 Structure of a Visual Basic Application


Application (Project) is made up of:
■■ Forms - Windows that you create for user interface
■■ Controls - Graphical features drawn on forms to allow user interaction (text
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.
■■ 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

3G E-LEARNING
14 Basic Computer Coding: Visual Basic

■■ Break mode - application halted and debugger is


available
■■ Six windows appear when you start Visual Basic.
Keyword
A menu
■■ The Main Window consists of the title bar, menu bar,
bar is a and toolbar. The title bar indicates the project name,
graphical control the current Visual Basic operating mode, and the
element which current form. The menu bar has drop-down menus
contains drop-
from which you control the operation of the Visual
down menus.
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.

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

3G E-LEARNING
Introduction to Visual Basic 15

■■ 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:

3G E-LEARNING
16 Basic Computer Coding: 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.

3G E-LEARNING
Introduction to Visual Basic 17

Keyword
A toolbar
is a
1.3.5 Saving Projects graphical control
element on which
on-screen buttons,
Even the simplest Visual Basic project comprises multiple files icons, menus, or
which must each be saved on your system to store the project. other input or
:Follow these steps to save the current New Project to disk output elements
are placed.
■■ Click the Save All button on the Tool Bar, or click File,
Save All on the Menu Bar, or press the Ctr+Shift+S
keys, to open the Save Project dialog

■■ 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

3G E-LEARNING
18 Basic Computer Coding: Visual Basic

■■ 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

3G E-LEARNING
Introduction to Visual Basic 19

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 and scenarios,

3G E-LEARNING
20 Basic Computer Coding: Visual Basic

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.

3G E-LEARNING
Introduction to Visual Basic 21

SUMMARY
■■ Visual Basic is a programming language and development environment created
by Microsoft.
■■ 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.
■■ 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.
■■ Visual Basic is regarded as the third generation event-driven programming
language.
■■ Visual basic programming language allows programmers to create software
interface and codes in an easy to use graphical environment.
■■ 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.
■■ 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.
■■ 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', you will see the message on
the Label changes color.
■■ Even the simplest Visual Basic project comprises multiple files which must
each be saved on your system to store the project.

3G E-LEARNING
22 Basic Computer Coding: Visual Basic

KNOWLEDGE CHECK
1. The Visual Basic Code Editor will automatically detect certain types of errors
as you are entering code.
a. True
b. False
2. Keywords are also referred to as reserved words.
a. True
b. False
3. The divide-and-conquer-method of problem solving breaks a problem into large,
general pieces first, then refines each piece until the problem is manageable.
a. True
b. False
4. 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
5. When the user clicks a button, _________ is triggered.
a. an event
b. a method
c. a setting
d. a property
6. What property of controls tells the order they receive the focus when the tab
key is pressed during run time?
a. Focus order
b. Focus number
c. Tab index
d. Control order
7. Sizing Handles make it very easy to resize virtually any control when developing
applications with Visual Basic. When working in the Form Designer, how are
these sizing handles displayed?
a. A rectangle with 4 arrows, one in each corner, around your control.
b. A 3-D outline around your control.

3G E-LEARNING
Introduction to Visual Basic 23

c. A rectangle with small squares around your control.


d. None of the above.
8. The Properties window plays an important role in the development of Visual
Basic applications. It is mainly used
a. to change how objects look and feel.
b. when opening programs stored on a hard drive.
c. to allow the developer to graphically design program components.
d. to set program related options like Program Name, Program Location, etc.
9. Pseudocode is
a. data that have been encoded for security.
b. the incorrect results of a computer program.
c. a program that doesn’t work.
d. the obscure language computer personnel use when speaking.
e. a description of an algorithm similar to a computer language.
10. Which of the properties in a control’s list of properties is used to give the
control a meaningful name?
a. Text
b. ContextMenu
c. ControlName
d. Name

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. (a) 2. (a) 3. (a) 4. (b) 5. (a)
6. (c) 7. (c) 8. (a) 9. (e) 10. (d)

3G E-LEARNING
24 Basic Computer Coding: Visual Basic

REFERENCES
1. 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).
2. 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.
3. Ryder, Barbara, Mary Lou Soffa and Margaret Burnett, The Impact of Software
Engineering Research on Modern Programming Languages. In ACM Transactions
on Software Engineering and Methodology, October, 2005. Pages 431 to 477.
4. Störrle, Harald, VMQL: A Generic Visual Model Query Language. In IEEE
Symposium on Visual Languages/Human Centric Computing, Corvallis, Oregon,
September 2009.
5. Zhang, Kang, Visual Languages and Applications. In Research Manuscript,
Springer, 2007.

3G E-LEARNING
2
CHAPTER

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:
1. Learn about the data
types
2. Explain the useful
variable in visual basic
3. Know about the
constants in visual basic

INTRODUCTION
The data type of a programming element refers to what
kind of data it can hold and how it stores that data. Data
26 Basic Computer Coding: Visual Basic

types apply to all values that can be stored in computer memory or participate in the
evaluation of an expression. Every variable, literal, constant, enumeration, property,
procedure parameter, procedure argument, and procedure return value has a data type.
Visual Basic is a Strongly Typed programming language so before we perform any
operation on a variable, it’s mandatory to define a variable with a required data type
to indicate what type of data the variable can hold in our application.
A variable is a location in memory where a value can be stored during the
execution of a Visual Basic application. Visual Basic variables are assigned names by
the programmer when they are declared so that they can easily be referenced in other
places in the application code.
These values may either be declared as variable (in that once the value has been
assigned it can be changed later in the Visual Basic code) or as constant (in that once
the value has been assigned, it cannot be changed elsewhere in the code).
Both constants and variables provide a way to reserve memory locations for the
storage of values of various types (such as numbers, characters and strings). These
memory locations are assigned names which can be used in Visual Basic code to
reference these memory locations. For example, you might want to store the interest
rate for a banking application. To do so you would declare a variable with a name of
your choice (such as interestRate) and specify the variable as an Integer type (since it
will be storing a number). Having declared the variable you can assign a value to it
and read that value anywhere in your application code.
The difference between variables and constants is that the value stored in a variable
can be changed at any time after it has been created. The value assigned to a constant,
as the name suggests, cannot be changed once it has been declared an initialized.

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.

3G E-LEARNING
Data Types, Constants And Variables 27

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)

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)

3G E-LEARNING
28 Basic Computer Coding: Visual Basic

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)


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.

3G E-LEARNING
Data Types, Constants And Variables 29

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.
■■ 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 Keyword
and you need to control the storage layout of its Boolean
members, you can apply the StructLayoutAttribute data type is
attribute to the class or structure. a data type that has
one of two possible
values (usually
2.1.3 Boolean Data Type denoted true and
false), intended to
Holds values that can be only True or False. The keywords True represent the two
truth values of
and False correspond to the two states of Boolean variables. logic and Boolean
Use the Boolean Data Type (Visual Basic) to contain two- algebra.
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, and the stored
values are not intended to be equivalent to numbers. You
should never write code that relies on equivalent numeric
values for True and False. Whenever possible, you should
restrict usage of Boolean variables to 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 not always produce the same results as the Visual

3G E-LEARNING
30 Basic Computer Coding: Visual Basic

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

3G E-LEARNING
Data Types, Constants And Variables 31

■■ 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.
[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.

3G E-LEARNING
32 Basic Computer Coding: Visual Basic

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

3G E-LEARNING
Data Types, Constants And Variables 33

If you pass an 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.
Remember
■■ Type Characters. Appending the literal type character
C to a single-character string literal forces it to the The
Decimal
Char data type. Char has no identifier type character. data type
■■ Framework Type. The corresponding type in the .NET provides the
Framework is the [Link] structure. greatest number
of significant
digits for a
2.1.6 Decimal Data Type number. It
supports up to 29
Holds signed 128-bit (16-byte) values representing 96- significant digits
and can represent
bit (12-byte) integer numbers scaled by a variable power
values in excess
of 10. The scaling factor specifies the number of digits to of 7.9228 x 10^28.
the right of the decimal point; it ranges from 0 through 28. It is particularly
With a scale of 0 (no decimal places), the largest possible suitable for
value is +/-79,228,162,514,264,337,593,543,950,335 (+/- calculations,
such as financial,
7.9228162514264337593543950335E+28). With 28 decimal places,
that require a
the largest value is +/-7.9228162514264337593543950335, and the large number of
smallest nonzero value is +/-0.0000000000000000000000000001 digits but cannot
(+/-1E-28). tolerate rounding
errors. The
■■ Precision. Decimal is not a floating-point data type. default value of
The Decimal structure holds a binary integer value, Decimal is 0.
together with a sign bit and an integer scaling factor
that specifies what portion of the value is a decimal
fraction. Because of this, Decimal numbers have a
more 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 System.
OverflowException error.
■■ Trailing Zeros. Visual Basic does not store trailing

3G E-LEARNING
34 Basic Computer Coding: Visual Basic

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

3G E-LEARNING
Data Types, Constants And Variables 35

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.
Keyword
Floating-
Programming Tips point data
types are stored in
■■ Precision. When you work with floating-point the IEEE SINGLE
numbers, remember that they do not always have a and DOUBLE
precise representation in memory. This could lead to precision formats.
unexpected results from certain operations, such as Both formats have
a sign bit field, an
value comparison and the Mod operator. For more exponent field, and
information, see Troubleshooting Data Types. a fraction field.
■■ Trailing Zeros. The floating-point data types do
not have any internal representation of trailing zero
characters. For example, they do not distinguish
between 4.2000 and 4.2. Consequently, trailing zero
characters do not appear when you display or print
floating-point values.
■■ Type Characters. Appending the literal 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

3G E-LEARNING
36 Basic Computer Coding: Visual Basic

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.
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
k = 4.5
The following statement sets k to 6
Note, Visual Basic uses banker’s rounding (toward nearest even number)
k = 5.5

3G E-LEARNING
Data Types, Constants And Variables 37

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.

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

3G E-LEARNING
38 Basic Computer Coding: Visual Basic

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
Keyword variable.
Visual
Studio 2.2.2 Comparing Implicit and Explicit Variable
Code is a source
code editor Performance
developed by
Microsoft for The default data type for Visual Basic variables is the variant.
Windows, Linux This means that, unless you specify otherwise, every variable
and macOS. It in your application will be a variant. The data type is not
includes support
for debugging,
very efficient. Its data storage requirements are greater than
embedded Git the equivalent simple data type. The computer spends more
control, syntax time keeping track of the data type contained in a variant
highlighting, than for other data types.
intelligent code
completion, An explicit declaration statically types the variable it
snippets, and code declares. In a language that requires explicit declaration, you
refactoring. 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
value.
Given the rise of very smart editors like Visual Studio
Code, implicit declaration need not be the menace it was,
at least for languages that support the notion of optional
declaration, for example Visual Basic. Smart editors can
highlight references to undeclared variables and list them in
warnings. Great for rapid prototyping, especially if the editor
provides an alphabetical list of symbol names - which would
make typos obvious.

3G E-LEARNING
Data Types, Constants And Variables 39

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

3G E-LEARNING
40 Basic Computer Coding: Visual Basic

ClassLevelCount += 10 ‘ This method can 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.
Now we need a Main() method that calls these methods so we can analyze the results.
Here we go:
Module Module1
Sub Main()

3G E-LEARNING
Data Types, Constants And Variables 41

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

3G E-LEARNING
42 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.

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 boxes, command buttons, option
groups, and other controls. Keeping track of the variables, procedures, forms, and
controls in even a moderately complicated Visual Basic application is a daunting task.

3G E-LEARNING
Data Types, Constants And Variables 43

One way to ease the burden of managing the 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. Keyword
Using a naming convention is not difficult. In most case, Naming
when the use of the variable is obvious a one-character prefix convention
is a set of rules
is used to keep code examples short and simple. In longer
for choosing the
procedures, three-character prefixes are used on most variables. character sequence
to be used for
identifiers which
2.2.7 Understanding Variable Scope and denote variables,
Lifetime types, functions,
and other entities
A variable is more than just a simple data repository. Every in source code and
variable is a dynamic part of the application and can be used at documentation.
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 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.
There are many analogies for public and private scope.
Variables declared within a procedure are local to that procedure
and cannot be used or referenced outside that procedure.
In each case, the Dim keyword was used to define the
variable.
Dim is shorthand for dimension and is a rather archaic
expression that instructs Visual Basic to allocate enough
memory to contain the variable that follows the Dim keyword.
Therefore, Dim i As Integer allocates less memory (2 bytes)
than Dim s As Double (8 bytes). There is no way to make a
variable declared within a procedure visible outside of that
procedure.

3G E-LEARNING
44 Basic Computer Coding: Visual Basic

The public keyword is used to make a variable visible


throughout an application. Public can be used only at the
module level and cannot be used within a procedure. Usually,
the Public keyword is used only in standard modules that are
not part of a form. Every variable declared 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.
Remember
Variables
are 2.3 CONSTANTS IN VISUAL BASIC
often used in
all programs A constant is a meaningful name that takes the place of a
and they help number or string that does not change. Constants store values
you store values that, as the name implies, remain constant throughout the
temporarily execution of an application. You can use constants that are
while the
program is
defined by the controls or components you work with, or
executing. you can create your own. Constants you create yourself are
You can have described as user-defined.
long-term
You can greatly improve the readability of your code and
variables(global)
which are make it easier to maintain by using constants. Use them in
used while the code that contains values that reappear or that depends on
program is been certain numbers that are difficult to remember or have no
used or you can obvious meaning.
have private
variables which How to Create and Use Constants: Visual Basic contains
are used only a number of predefined constants, mainly using for printing
on one form of and displaying. You can also create your own constants with
the program the Const statement, using the same guidelines you would
and even local
variables which for creating a variable name. If Option Strict is On, you must
are only used explicitly declare the constant type.
on a specific A constant’s scope, which is the set of all code that can
procedure inside
a form.
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.

3G E-LEARNING
Data Types, Constants And Variables 45

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

3G E-LEARNING
46 Basic Computer Coding: Visual Basic

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

3G E-LEARNING
Data Types, Constants And Variables 47

To declare a constant
Write a declaration that includes an access specifier, the Const
keyword, and an expression, as in the following examples: Keyword
String
Public Const DaysInYear = 365
constants
Private Const WorkDays = 250 are a special
type of constants
When Option Infer is Off and Option Strict is On, you which store fixed
must declare a constant explicitly by specifying a data type sequences of
(Boolean, Byte, Char, DateTime, Decimal, Double, Integer, characters.
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”
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

3G E-LEARNING
48 Basic Computer Coding: Visual Basic

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.

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.
You can coerce a literal to a particular data type in two ways: by appending a
type character to it, or by placing it within enclosing characters. A type character
or enclosing characters must immediately precede and/or follow the literal, with no
intervening space or characters of any kind.
To make the previous example work, you can append the D type character to the
:literal, which causes it to be represented as a Decimal
Dim MyDecimal As Decimal = 100000000000000000000D
The following example demonstrates correct usage of type characters and enclosing
characters:
Default to Integer.
Public Const DefaultInteger As Integer = 100
Default to Double.
Public Const DefaultDouble As Double = 54.3345612

3G E-LEARNING
Data Types, Constants And Variables 49

Force constant to be type Char.


Public Const MyCharacter As Char = “a”c Did You
DateTime constants. Know?
All
Public Const MyDate As DateTime = #1/15/2001# versions of the
Public Const MyTime As DateTime = #1:15:59 AM# Visual Basic
development
Force data type to be Long. environment
Public Const MyLong As Long = 45L from 1.0 to 6.0
were retired
Force data type to be Single. by Microsoft
Public Const MySingle As Single = 45.55! by 2008, and
are therefore
The following table shows the enclosing characters and no longer
type characters available in Visual Basic. supported.
The associated
runtime
Data type Enclosing character Appended type character environments
are also
Boolean (none) (none) unsupported,
Byte (none) (none) except for the
Visual Basic 6
Char “ C core runtime
Date # (none) environment,
which Microsoft
Decimal (none) D or @ officially
Double (none) R or # supports for
the lifetime of
Integer (none) I or % Windows 8 and
Windows 10.
Long (none) L or &
Short (none) S
Single (none) F or !
String “ (none)

3G E-LEARNING
50 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 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

3G E-LEARNING
Data Types, Constants And Variables 51

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

3G E-LEARNING
52 Basic Computer Coding: Visual Basic

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

3G E-LEARNING
Data Types, Constants And Variables 53

SUMMARY
■■ 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.
■■ 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.
■■ The same considerations apply to each member of a composite data type,
such as a structure or an array.
■■ Holds values that can be only True or False. The keywords True and False
correspond to the two states of Boolean variables.
■■ 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.
■■ 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.
■■ 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.
■■ Visual Basic provides extremely liberal rules for naming variables.
■■ 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 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.

3G E-LEARNING
54 Basic Computer Coding: Visual Basic

KNOWLEDGE CHECK
1. __________ is a variable that remains in memory, and retains its value even
after the procedure declaring it ends.
a. Procedure-level variable
b. Class-level variable
c. Static variable
d. Dynamic variable
2. Static variable can only be used in the __________ in which it is declared.
a. Class
b. Any procedures in the form
c. Any form
d. Only the Procedure it is declared in
3. A __________ cannot change its value while the application is running.
a. Constant variable
b. Class variable
c. Named constant
d. Static constant
4. Named constants are used because __________
a. Because they take up less space in memory
b. Because they make documentation and code modification easier
c. Because they can be easily accessed by procedures
d. Because they are easily declared
5. What is wrong with the expression “const dblPi As Double = 3.141593”?
a. Double is written
b. Name should be DBLPi
c. “const” starts with a “C”
d. Value is too large

3G E-LEARNING
Data Types, Constants And Variables 55

6. What is wrong with the expression “static dblPi AsDouble ”?


a. Double is written
b. Nothing is wrong
c. “Static” starts with a “S”
d. Value is not given

7. What happens when a procedure containing the following statements ends?


a. Dim decSales As Decimal=12.2
b. Static decTotal As Decimal=13.5
c. Both values lose their values
d. Dim variable loses its value
e. Static variable loses its value
f. Both variables retain their values
8. Using a named constant is advantageous because to change a value in future,
change __________
a. The value in the Const statement
b. The value of the variable wherever it appears in the program
c. The value of the variable anywhere in the program
d. The value of the variable in one of the procedures in the program
9. Unintentional errors in application by declaring variables can be reduced by
__________
a. Giving them Small names
b. Declaring them with a small sized data type
c. Giving them minimum scope possible
d. Making them class variables
10. To declare a class-level named constant you declare it as __________
a. Public
b. Dynamic
c. Private
d. Static

3G E-LEARNING
56 Basic Computer Coding: Visual Basic

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. (d) 3. (c) 4. (b) 5. (c)
6. (c) 7. (b) 8. (a) 9. (c) 10. (c)

3G E-LEARNING
Data Types, Constants And Variables 57

REFERENCES
1. Abraham, Robin, Martin Erwig, Header and Unit Inference for Spreadsheets
Through Spatial Analyses. In IEEE Symposium on Visual Languages and
Human-Centric Computing , Rome, Italy, September 2004.
2. Abraham, Robin, FoXQ - XQuery by Forms. In 2003 IEEE Symposia on
Human Centric Computing Languages and Environments, Auckland, New
Zealand, October 2003.
3. Banyasad, Omid, Philip. T. Cox, An Automatic Layout Algorithm for
Lograph. In 2004 IEEE Symposium on Visual Languages and Human Centric
Computing, Rome, Italy, Sept 2004.
4. Bardohl, Roswitha, Ribeiro Leila, Towards a Compositional Approach
to Define Graphical Animation of Software Applications. In 2001 IEEE
Symposium on Visual Languages and Formal Methods, Stresa, Italy,
September 2001.
5. Bergin, Joe, K. Brodlie, M. Goldweber, R. Jimenez-Peris, S. Khuri, M.
Patino-Martinez, M. McNally, T. Naps, S. Rodger, J. Wilson, An overview
of visualization: its use and design. In 1996 ACM ITiCSE, Barcelona, Spain,
June 1996. Pages 192 to 200.

3G E-LEARNING
3
CHAPTER

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:
1. Describe the statement
2. Learn about decision
making structures
3. Understand the visual
basic control
4. Discuss about visual
basic control tools

INTRODUCTION
In [Link], the control statements are the statements that
controls the execution of the program on the basis of the
60 Basic Computer Coding: Visual Basic

specified condition. It is useful for determining whether a


condition is true or not. If the condition is true, a single or
block of statement is executed. In the control statement, we
will use if- Then, if Then Else, if Then ElseIf and the Select
case statement.
We can define more than one condition to be evaluated by the
program with statements. If the defined condition is true, the
statement or block executes according to the condition, and if
the condition is false, another statement is executed.

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 −
Keyword ■■ Declaration statements − these are the statements
where you name a variable, constant, or procedure,
Assignment and can also specify a data type.
statement sets
and/or re-sets the ■■ Executable statements − these are the statements,
value stored in the which initiate actions. These statements can call a
storage location(s) method or function, loop or branch through blocks of
denoted by a code or assign values or expression to a variable or
variable name; in
constant. In the last case, it is called an Assignment
other words, it
copies a value into statement.
the variable.
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.
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.

3G E-LEARNING
Control Statements and Tools 61

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

3G E-LEARNING
62 Basic Computer Coding: Visual Basic

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

3G E-LEARNING
Control Statements and Tools 63

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


14 Delegate Statement Delegate Function Expression
MathOperator( is a
Used to declare a delegate. combination of one
ByVal x As Double, or more constants,
variables,
ByVal y As Double operators, and
functions that the
) As Double programming
language interprets
and computes to
3.1.2 Executable Statements produce another
value.
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.

Example
The following example demonstrates a decision making
statement −
Module decisions
Sub Main()

3G E-LEARNING
64 Basic Computer Coding: Visual Basic

‘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 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 −

3G E-LEARNING
Control Statements and Tools 65

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

3.2.1 If...Then Statement


It is the simplest form of control statement, frequently used in Keyword
decision making and changing the control flow of the program Execution
execution. Syntax for if-then statement is – is the
process by which a
If condition Then
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.

3G E-LEARNING
66 Basic Computer Coding: Visual Basic

Flow Diagram

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

3G E-LEARNING
Control Statements and Tools 67

3.2.2 If...Then...Else Statement


An If statement can be followed by an optional Else statement,
which executes when the Boolean expression is false. Keyword
Boolean
expression
Syntax is an expression
in a programming
The syntax of an If...Then... Else statement in [Link] is as language that
follows − produces a Boolean
value when
If(boolean_expression)Then evaluated, i.e. one
‘statement(s) will execute if the Boolean expression is true of true or false.

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

3G E-LEARNING
68 Basic Computer Coding: Visual Basic

‘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
Remember
[Link](“a is less than 20”)
When
using Else
If... Else If... Else ‘ if condition is false then print the following
statements, there
are few points to [Link](“a is not less than 20”)
keep in mind.
End If
• An If can have [Link](“value of a is : {0}”, a)
zero or one Else’s
and it must come [Link]()
after an Else If’s. End Sub
• An If can have End Module
zero to many When the above code is compiled and executed, it produces
Else If’s and they
the following result −
must come before
the Else. a is not less than 20
• Once an Else if value of a is : 100
succeeds, none
of the remaining 3.2.3 The If...Else If...Else Statement
Else If’s or Else’s
will be tested.
An If statement can be followed by an optional Else if...Else
statement, which is very useful to test various conditions
using single If...Else If statement.

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

3G E-LEARNING
Control Statements and Tools 69

Else
‘ executes when the none of the above 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

3G E-LEARNING
70 Basic Computer Coding: Visual Basic

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)
[Link](“Exact value of b is : {0}”, b)
[Link]()
End Sub

3G E-LEARNING
Control Statements and Tools 71

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
Keyword
3.2.5 Select Case Statement
Value is
A Select Case statement allows a variable to be tested for the representation
of some entity that
equality against a list of values. Each value is called a case, and can be manipulated
the variable being switched on is checked for each select case. by a 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, 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.

3G E-LEARNING
72 Basic Computer Coding: Visual Basic

Flow Diagram

Example
Module decisions
Sub Main()
‘local variable definition
Dim grade As Char
grade = “B”
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

3G E-LEARNING
Control Statements and Tools 73

[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
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

3G E-LEARNING
74 Basic Computer Coding: Visual Basic

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
Did You
Know?
The 3.3 VISUAL BASIC CONTROL
origins of
Visual Basic An object is a type of user interface element you create on a
are found in a Visual Basic form by using a toolbox control. In fact, in Visual
programming Basic, the form itself is an object. Every Visual Basic control
language created consists of three important elements −
in 1964 by
John Kemeny ■■ Properties which describe the object,
and Thomas ■■ Methods cause an object to do something and
Kurtz. BASIC
(Beginners ■■ Events are what happens when an object does
All-purpose something.
Symbolic
Instruction Code)
was originally 3.3.1 Control Properties
an interpreted
language that All the Visual Basic Objects can be moved, resized or
was designed customized by setting their properties. A property is a value
to simplify the or characteristic held by a Visual Basic object, such as Caption
programming
process or Fore Color.
and make Properties can be set at design time by using the Properties
programming window or at run time by using statements in the program
more accessible
to the world at
code.
large. Object. Property = Value
Where
■■ Object is the name of the object you’re customizing.
■■ Property is the characteristic you want to change.
■■ Value is the new property setting.

For example,
[Link] = “Hello”
You can set any of the form properties using Properties Window.

3G E-LEARNING
Control Statements and Tools 75

Most of the properties can be set or read during application


execution. You can refer to Microsoft documentation for a
complete list of properties associated with different controls
and restrictions applied to them.

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 −
■■ 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 [Link], 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 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.

3G E-LEARNING
76 Basic Computer Coding: Visual Basic

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 −
Keyword Private Sub Form1_Load(sender As Object, e As EventArgs)
Subroutine Handles [Link]
is
a sequence ‘event handler code goes here
of program End Sub
instructions that
performs a specific Here, Handles [Link] indicates that Form1_Load()
task, packaged as subroutine handles Load event. Similar way, you can check
a unit. 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

3G E-LEARNING
Control Statements and Tools 77

■■ Image control
■■ Label
■■ Line
■■ List box
■■ Ole container
■■ 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 [Link] 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.

3G E-LEARNING
78 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.

Early Life and Education


In 1951, Kurtz’ first experience with computing came at the
Summer Session of the Institute for Numerical Analysis at

3G E-LEARNING
Control Statements and Tools 79

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

3G E-LEARNING
80 Basic Computer Coding: Visual Basic

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

3G E-LEARNING
Control Statements and Tools 81

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.

3G E-LEARNING
82 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.
■■ 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.
■■ It is the simplest form of control statement, frequently used in decision making
and changing the control flow of the program execution.
■■ An If statement can be followed by an optional Else statement, which executes
when the Boolean expression is false.
■■ An If statement can be followed by an optional Else if...Else statement, which
is very useful to test various conditions using single If...Else If statement.
■■ 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).
■■ A Select Case statement allows a variable to be tested for equality against a
list of values. Each value is called a case, and the variable being switched on
is checked for each select case.
■■ 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.
■■ An object is a type of user interface element you create on a Visual Basic
form by using a toolbox control.
■■ All the Visual Basic Objects can be moved, resized or customized by setting
their properties. A property is a value or characteristic held by a Visual Basic
object, such as Caption or Fore Color.
■■ 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.

3G E-LEARNING
Control Statements and Tools 83

■■ 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.
■■ Visual Basic toolbox contains the controls which are used in the form design.
The controls are used by users to interact with the applications.

3G E-LEARNING
84 Basic Computer Coding: Visual Basic

KNOWLEDGE CHECK
1. Visual Basic is developed by:
a. IBM
b. Microsoft
c. Microsystem
d. Oracle
2. Visual Basic is a tool that allows you to develop application in ______.
a. Real Time
b. Graphical User Interface
c. Character User Interface
d. None of these
3. ______ is used for finding out about objects, properties and methods.
a. Form Layout Window
b. Code Editor Window
c. Object Browser
d. None of the above
4. IDE stands for ______
a. Internet Development Environment
b. Integrated Dual Environment
c. Integrated Development Environment
d. Integrated Desktop Environment
5. Which window 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
6. Which of the following window is the central to the development of Visual
Basic applications.
a. Project window
b. Form window
c. Properties window
d. All of the above

3G E-LEARNING
Control Statements and Tools 85

7. In ______ window we can write code.


a. Immediate window
b. Local window
c. Code editor window
d. None of these
8. ______ shows the value of any variables within the scope of the current procedure.
a. Immediate window
b. Locals window
c. watches window
d. None of these
9. ______ shows the property type as well as a short description of the property.
a. Object box
b. Decription pane
c. Form layout window
d. Code editor
10. Which window shows information that results from debugging statements in
our code.
a. Watch window
b. Variables window
c. Locals window
d. Immediate window

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. (b) 2. (b) 3. (c) 4. (c) 5. (a)
6. (b) 7. (c) 8. (b) 9. (b) 10. (d)

3G E-LEARNING
86 Basic Computer Coding: Visual Basic

REFERENCES
1. Abraham, Robin, Identifying Structure in Spreadsheets. In IEEE Symposium on
Visual Languages and Human-Centric Computing, Rome, Italy, September 2004.
2. Banyasad, Omid, Philip T. Cox, Design and Implementation of an Interpreter
Engine for a Visual Logic Programming Language. In Proceedings of the Second
CologNet Workshop on Implementation Technology for Computational Logic
Systems, Pisa, Italy, 2003. Pages 39 to 50.
3. Bimonte, Sandro, Filomena Ferrucci, Robert Laurini, Giuseppe Polese, Prototype
of a Visual Language for Spatial Data Mining. In 2003 Symposium on Visual/
Multimedia, HCC’03 , Auckland, New Zealand, October 2003.
4. Bottoni, Paolo, Juan de Lara, Esther Guerra, Action Patterns for the Specification
of the Execution Semantics of Visual Languages. In 2007 IEEE Symposium on
Visual Languages and Human Centric Computing, Cour d’Alene, Oregon / USA,
September 2007. Pages 163 to 170.
5. Burmester, Sven, Holger Giese, Visual Integration of UML 2.0 and Block Diagrams
for Flexible Reconfiguration in Mechatronic UML. In 2005 IEEE Symposium on
Visual Languages and Human-Centric Computation (VL/HCC’05), Dallas, Texas/
USA, September 2005.

3G E-LEARNING
4
CHAPTER

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:
1. Understanding the menu
bar
2. Explain the dialog boxes

INTRODUCTION
Menus, which are located on the menu bar of a form,
contain a list of related commands. When you click a menu
88 Basic Computer Coding: Visual Basic

title in a Windows-based program, a list of menu commands should always appear


in a well-organized list.
Most menu commands run immediately after they are clicked. For example, when
the user clicks the Edit menu Copy command, Windows immediately copies information
to the Clipboard. However, if ellipsis points (…) follow the menu command, Visual
Basic displays a dialog box that requests more information before the command is
carried out.
There are many built-in dialog boxes to be used in Windows forms for various
tasks like opening and saving files, printing a page, providing choices for colors, fonts,
page setup, etc., to the user of an application. These built-in dialog boxes reduce the
developer’s time and workload.
All of these dialog box control classes inherit from the CommonDialog class and
override the RunDialog() function of the base class to create the specific dialog box.

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:

3G E-LEARNING
Menu Bar and Dialog Boxes 89

Figure 1: New Project Window


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.

3G E-LEARNING
90 Basic Computer Coding: Visual Basic

Figure 3
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

3G E-LEARNING
Menu Bar and Dialog Boxes 91

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

3G E-LEARNING
92 Basic Computer Coding: Visual Basic

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”
Keyword .CancelError = False
File ‘Set the flags and attributes of the common dialog control
menu is a
graphical control .Filter = “Bitmaps(*.BMP)|*.BMP|Metafiles(*.WMF)|*.
element formerly WMF|Jpeg
common to most
Files(*.jpg)|*.jpg|GIF Files(*.gif)|*.gif|Icon Files(*.ico)|*.
file-handling
computer ico|All Files(*.*)|*.*”
programs, but .ShowOpen
more recently
often replaced by a [Link] = LoadPicture(.FileName)
toolbar or ribbon. If Len(.FileName) = 0 Then
Exit Sub
End If
sFile = .FileName
End With
End Sub
When you run the program and click on the File menu
and then the submenu Open, the following Open dialog box
will be displayed, where you can look for graphic files of
various formats to load it into the image box.

3G E-LEARNING
Menu Bar and Dialog Boxes 93

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:
Clicking on the particular picture will load it into the image box, as shown in
Figure 10

3G E-LEARNING
94 Basic Computer Coding: Visual Basic

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:
You can then add in other menu items on the menu bar by following the same
procedure, as shown in Figure 12:

3G E-LEARNING
Menu Bar and Dialog Boxes 95

Figure 12:
When you click Ok, the menu items will be shown on
the menu bar of the form.

Keyword
Arrow
keys
are buttons on a
computer keyboard
that are either
programmed or
designated to move
the cursor in a
specified direction.

Figure 13
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 key, and the dotted line
will appear. This shows the second level of the menu, or the
submenu. Now key in the caption and the name. Repeat the
same procedure to add other submenu items. Here, we are
adding New, Open, Save, Save As and Exit.

3G E-LEARNING
96 Basic Computer Coding: Visual Basic

Figure 14:

Figure 15:
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:

3G E-LEARNING
Menu Bar and Dialog Boxes 97

Finally, you can enter the code by clicking on any of the


submenu items.
Keyword
Multiple
4.2 DIALOG BOXES document
interface (MDI)
An application’s object is programmatically referred to as is a graphical user
a parent when it can host, hold, or carry other objects. For interface in which
this reason, such a window is also referred to as a container. multiple windows
Although the first object that comes in mind is the form, this reside under a
single parent
is not the only window that can act as parent. This means window.
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.
As mentioned already, there are two categories of controls:
parents and children:
■■ Parent: The child controls are positioned on a parent.
To keep track of its children, a parent control has
the 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 Keyword
a parent is destroyed, it also destroys its children. A
NET.
parent control «carries», «holds», or hosts the controls Framework
positioned on it. When a parent is created, made is a software
active, or made visible, it gives existence and visibility framework
to its controls. When a parent gets hidden, it also developed by
Microsoft that
hides its controls. If a parent moves, it moves with runs primarily
its children. The controls keep their positions and on Microsoft
dimensions inside the parent. The .NET Framework .Windows
provides various parent controls.
■■ Child: A window is referred to as child when its

3G E-LEARNING
98 Basic Computer Coding: Visual Basic

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

3G E-LEARNING
Menu Bar and Dialog Boxes 99

that hosts three property pages (tab controls) and each property page hosts its own
child controls:

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

3G E-LEARNING
100 Basic Computer Coding: Visual Basic

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 is thinner than
that of a regular form). You can set this characteristic in the Properties window or
programmatically. Here is an example:

3G E-LEARNING
Menu Bar and Dialog Boxes 101

Public Sub InitializeComponent()


Text = “Domain Configuration”
Width = 320
Height = 150
Location = New Point(140, 100)
StartPosition = [Link]
FormBorderStyle = [Link].
FixedDialog Did You
End Sub Know?
Before
the computer
The Minimize and Maximize Boxes mouse was
widespread,
Besides taking care of the border, you should also set both the
arrow keys were
MinimizeBox and the MaximizeBox properties to False. This the primary
causes the window to display only the system Close button. way of moving
You can set these characteristics in the Properties window or a cursor on
programmatically. Here is an example: screen. Mouse
Public Sub InitializeComponent() keys is a feature
that allows
Text = “Domain Configuration” controlling a
Width = 320 mouse cursor
with arrow keys
Height = 150
.instead
Location = New Point(140, 100)
StartPosition = [Link]
FormBorderStyle = [Link].
FixedDialog
MinimizeBox = False
MaximizeBox = False
End Sub
This would produce:

3G E-LEARNING
102 Basic Computer Coding: Visual Basic

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
Button Cancel BtnCancel
Label Bedrooms:
TextBox TxtBedrooms
Button OK BtnOK

3G E-LEARNING
Menu Bar and Dialog Boxes 103

Label Bathrooms:
TextBox TxtBatrooms
Label Monthly Rent:
TextBox TxtMonthlyRent Did You
Know?
If the
Closing a Dialog Box user press Enter,
the dialog box
You should provide a way for the user to close the dialog should also be
box. A dialog box should have at least one button labeled OK. closed as if the
This button allows the user to acknowledge the message of OK button was
.the dialog box and close it by clicking the button clicked.

Accepting an Action
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. 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
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

3G E-LEARNING
104 Basic Computer Coding: Visual Basic

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]
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:

3G E-LEARNING
Menu Bar and Dialog Boxes 105

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.

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

3G E-LEARNING
106 Basic Computer Coding: Visual Basic

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.

Keyword Modeless Dialog Boxes


WordPad A dialog box is referred to as modeless if the user does not
is a basic
have to close it in order to continue using the application
word processor
that is included that owns the dialog box. A modeless dialog box has the
with almost following characteristics
all versions of
■■ It has a thin border
Microsoft Windows
from Windows 95 ■■ It can be neither minimized nor maximized. This
onwards. 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:
The Find (and the Replace) dialog box of WordPad (also
the Find and the Replace dialog boxes of most applications)
is an example of a modeless dialog box. If it is opened, the
user does not have to close it in order to use the application
or the document in the background.

3G E-LEARNING
Menu Bar and Dialog Boxes 107

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:

3G E-LEARNING
108 Basic Computer Coding: Visual Basic

■■ On the main menu, you can click Project -> Add New Item...
■■ On the main menu, you can click File -> Add New Item...
■■ 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.

3G E-LEARNING
Menu Bar and Dialog Boxes 109

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. This wizard allows the user to insert fully customized
standard Windows menu into his or her application.
■■ 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. For this reason, such a window is also
referred to as a container.
■■ 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.
■■ 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.
■■ 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.
■■ 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.
■■ 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.
■■ 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.
■■ 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.
■■ 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.

3G E-LEARNING
110 Basic Computer Coding: 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. IDE stands for…………..
a. Internet Development Environment
b. Integrated Dual Environment
c. Integrated Development Environment
d. Integrated Desktop Environment
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. Properties can be viewed in two ways
a. Alphabetic and Categorized
b. Alphabetic and Numeric
c. Numeric and Alphanumeric
d. None of these
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
6. Which of the following provides quick access to commonly used commands in
the programming environment
a. Toolbox
b. Object browser
c. Toolbar

3G E-LEARNING
Menu Bar and Dialog Boxes 111

d. None of these
7. In ……………… window we can write code
a. Immediate window
b. Locals window
c. Code editor window
d. None of these
8. ………… is used for finding out about objects, properties and methods.
a. Object browser
b. Property window
c. Form layout window
d. Code editor window
9. The form module has file extension….
a. .frb
b. .fra
c. .frm
d. .fru
10. A text box can hold as many as ……. Characters for a single line text.
a. 2052
b. 2048
c. 2058
d. 2047

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. (c) 3. (a) 4. (a) 5. (b)
6. (c) 7. (c) 8. (a) 9. (c) 10. (b)

3G E-LEARNING
112 Basic Computer Coding: Visual Basic

REFERENCES
1. Burnett, Margaret M, Martin Erwig, Visually Customizing Inference Rules About
Apples and Oranges. In IEEE International Symposium on Human-Centric
Computing Languages and Environments (HCC 2002), Arlington, VA, USA,
September 2002.
2. Campbell, Jeffrey D, Multi-User Collaborative Visual Program Development. In
Human Centric Computing Languages and Environments 2002, Arlington, VA,
USA, September 2002.
3. Carrara, Paola, Daniela Fogli, Giuseppe Fresta, Piero Mussio, Making Abstract
Specifications Concrete to End-Users: the Visual Workshop Hierarchy Strategy. In
2002 IEEE Symposia on Human Centric Computing Languages and Environments,
Arlington, VA, USA, September 2002.
4. Casella, Giovanni, Gennaro Costagliola, Vincenzo Deufemia, Maurizio Martelli,
Viviana Mascardi, An Agent-Based Framework for Context-Driven Interpretation
of Symbols in Diagrammatic Sketches. In 2006 IEEE Symposium on Visual
Languages and Human-Centric Computing (VL/HCC’06), Brighton, United
Kingdom, September 2006. Pages 73 to 80.
5. Castello, Rodolfo, Rym Mili, Haripriya Madabushi, Visualizing Graphical and
Textual Formalisms. In 2001 IEEE Symposia on Human-Centric Computing
Languages and Environments, Stresa, Italy, September 2001. Pages 120 to 121.
6. Chatley, Robert, Jeff Kramer, Jeff Magee, Sebastian Utchitel, Visual Methods for
Web Application Design. In The 2003 IEEE Symposium on Visual/Multimedia
Software Engineering , Auckland, New Zealand, Octoiber 2003.

3G E-LEARNING
5
CHAPTER

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:
1. Describe the error types
2. Explain the debugging
visual basic programs
3. Describe the debugging
tools
4. Understand the error
handling

INTRODUCTION
Errors, bugs, and therefore debugging are a part of life
for a programmer. As the saying goes, if you haven’t
114 Basic Computer Coding: Visual Basic

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.

3G E-LEARNING
Executing the Debugging 115

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

Did You
5.1.3 Logic Errors Know?
The
These are errors that cause the program to behave incorrectly. terms “bug” and
They generally arise through failure on the part of the “debugging”
programmer to arrive at a correct algorithm for the task. are popularly
Typical problems might be incorrect ordering of statements, attributed to
Admiral Grace
failure to initialize or reinitialize a variable, assignment to Hopper in the
an incorrect variable, use of ‘<’ instead of ‘<=’, use of ‘and’ 1940s.
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 careful testing is so important.

3G E-LEARNING
116 Basic Computer Coding: Visual Basic

5.2 DEBUGGING VISUAL BASIC PRO-


GRAMS
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.
Keyword The interface between your application and the debugging
A toolbar
tools is via three different debug windows: the Immediate
is a
graphical control Window, the Locals Window, and the Watch Window. These
element on which windows can be accessed from the View menu (the Immediate
on-screen buttons, Window can be accessed by pressing Ctrl+G). Or, they can be
icons, menus, or selected from the Debug Toolbar (accessed using the Toolbars
other input or
output elements option under the View menu):
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

3G E-LEARNING
Executing the Debugging 117

■■ Change the values of variables and properties

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

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.

3G E-LEARNING
118 Basic Computer Coding: Visual Basic

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 while an
application is running. Sometimes, this is all the debugging
you may need. A few carefully placed print statements
can sometimes clear up all logic errors, especially in small
applications.
To print to the immediate window, use the Print method:
[Link] Example:
■■ Place the following statement in the Command1_Click
procedure after the line calling the general procedure
Keyword Fcn: [Link] X; Y
A logic
error
and run the application.
is a bug in a ■■ Examine the immediate window. Note how, at each
program that iteration of the loop, the program prints the value
causes it to operate
incorrectly, but
of X and Y. You could use this information to make
not to terminate sure X is incrementing correctly and that Y values
abnormally (or look acceptable.
crash). A logic
error produces
■■ Remove the [Link] statement.
unintended or
undesired output Breakpoints:
or other behavior,
although it may In the above examples, the program ran to completion before
not immediately be we could look at the debug window. In many applications,
recognized as such.
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

3G E-LEARNING
Executing the Debugging 119

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.

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 are displayed in the watch
window. In break mode, you can use the Quick Watch button on the toolbar to add
watch expressions you need. Simply put the cursor on the variable or expression you
want to add to the watch list and click the Quick Watch button. Watch expressions
can be edited using the Edit Watch option on the Debug menu.
Watch Expression Example:
■■ Set a breakpoint at the X = X + 1 line in the example.

3G E-LEARNING
120 Basic Computer Coding: Visual Basic

■■ 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.
Keyword
A debug ■■ At some point in the debug procedure, add a quick
menu or watch on Y. Notice it is now in the watch window.
debug mode is
a user interface
■■ Clear the breakpoint. Add a watch on the expression:
implemented in a X = Y. Set Watch Type to ‘Break When Value Is True.’
computer program Run the application. Notice it goes into break mode
that allows the and displays the watch window whenever X = Y.
user to view and/ Delete this last watch expression.
or manipulate
the program’s
internal state for Call Stack:
the purpose of
debugging. 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:

3G E-LEARNING
Executing the Debugging 121

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

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 Keyword
the Fcn function, press the Step over button. Notice The debug
how the program did not single step through the window
function as it did previously. provides
information
about the state of
Function Exit (Step Out): your patch as it
is executing. By
While stepping through your program, if you wish to complete setting a break
the execution of a function you are in, without stepping watchpoint,
through it line -by-line, choose the Step Out option. The you can look at
function will be completed and you will be returned to the the suspended
execution of your
procedure accessing that function. To perform this step out, patch to learn more
press Ctrl+Shift+<f8>, choose Step Out from the Debug menu, information about
or press the Step Out button on the toolbar. its behavior.

Using the Debug Window


Sometimes debugging requires analysis of what is happening
to data. A problem may have been traced to the value of a
variable or property but you need to know where the incorrect
assignment occurred. The Debug window lets you display
the value of variables either while a program is running or
after it has been halted. The window consists of two panes:

3G E-LEARNING
122 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:

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.

3G E-LEARNING
Executing the Debugging 123

Run time Mode


At run time, although you can’t enter statements into the
Debug window, you can use it to display internal values
without printing them to the actual forms. The Debug window
is an object which has a single Print method. For example, the Remember
following line will send the name of the font used in ‘Label1’ The VB
to the debug window at run time: program
which is still
■■ [Link] [Link]
running may
Variables or constants can also be printed in the same way: obscure the
Debug window,
■■ [Link] intCurrentDay thus it is
■■ [Link] “Reached here in the code” advisable to
move it so that
the contents
5.4 ERROR HANDLING of the debug
window can be
Most or early errors occur in your code. If you are using the seen.
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 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 compilation will
be over and the executable will be ready. You can then execute
the application to see the result. If the user is not asked to
provide value(s), you are less likely to get a run-time error.
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]()

3G E-LEARNING
124 Basic Computer Coding: Visual Basic

Return 0
End Function

Keyword End Module


A
compiler is
computer software Here is an example of executing it:
that transforms
computer code Enter a number: 246.88
written in one 246.88 * 2 = 493.76
programming
language The first thing your should do is to imagine what could
into another cause a problem. If you think there is such a possibility, start
programming by creating a label that could be used to transfer code if a
language.
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

3G E-LEARNING
Executing the Debugging 125

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

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

3G E-LEARNING
126 Basic Computer Coding: Visual Basic

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

3G E-LEARNING
Executing the Debugging 127

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:

Enter a number: 24$.58

3G E-LEARNING
128 Basic Computer Coding: Visual Basic

In Main(): The operation could not be executed


When the On Error GoTo statement is used, this indicates
to the compiler that if any type of error occurs while the code
Keyword of this procedure is executed, it should transfer the compilation
GoTo is a to the label. As soon as something bad happens, the compiler
statement marks the area where the problem occurred, skips the normal
found in many code and jumps to the label indicated by the On Error GoTo
computer
programming line. The compiler returns where the error occurred. If there
languages. It is nothing to solve the problem, the compiler continues down
performs a one- but without executing the lines of code involved. In this case, it
way transfer of would encounter the Exit Subline and get out of the procedure.
control to another
line of code; in
contrast a function 5.4.2 In Case Of Error, Jump To Line #
call normally
returns control. 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

[Link](“{0} * 2 = {1}”, Number, Twice)


[Link]()

Exit Function

624:
[Link](“In Main(): The operation could
not be executed”)

3G E-LEARNING
Executing the Debugging 129

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:

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

3G E-LEARNING
130 Basic Computer Coding: Visual Basic

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

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

3G E-LEARNING
Executing the Debugging 131

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

3G E-LEARNING
132 Basic Computer Coding: Visual Basic

[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
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

3G E-LEARNING
Executing the Debugging 133

SUMMARY
■■ In writing VB software, three types of errors can occur syntax errors (Compile
errors), run-time errors and logic errors.
■■ Syntax Errors 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).
■■ Run-time Errors 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.
■■ Logic Errors 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.
■■ 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.
■■ All debugging using the debug windows is done when your application is
in break mode.
■■ 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.
■■ 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.
■■ Sometimes debugging requires analysis of what is happening to data. A
problem may have been traced to the value of a variable or property but you
need to know where the incorrect assignment occurred. The Debug window
lets you display the value of variables either while a program is running or
after it has been halted.
■■ 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.
■■ At run time, although you can’t enter statements into the Debug window, you
can use it to display internal values without printing them to the actual forms.

3G E-LEARNING
134 Basic Computer Coding: Visual Basic

■■ 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 by
paying attention to your code.
■■ 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.
■■ 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.

3G E-LEARNING
Executing the Debugging 135

KNOWLEDGE CHECK
1. Which of the following information is contained in the assembly manifest?
a. Files
b. Identity
c. Security Permissions
d. All of the above
2. Any project that compiles to an EXE or DLL files produces an assembly in .NET.
a. True
b. False
3. Which of the following is the best to retrieve Read-Only, Forward-only stream
of data from database?
a. Data Set
b. Typed Data Set
c. DataReader
4. ________ protects system resources from unauthorized calls.
a. Role-based security
b. Code-based security
c. None of the above
5. Which of the following is not a method of Debug class?
a. Assert( )
b. Flush( )
c. Open( )
6. __________ is used to step through each line of code as it executes, including
calls to other function.
a. Step Out
b. Step Over
c. Step Into
d. Run to Cursor
e. Set Next Statement
7. COMException class is a part of ________ .
a. [Link]
b. [Link]
c. System. Data

3G E-LEARNING
136 Basic Computer Coding: Visual Basic

8. The methods declared with the following modifiers are not accessible out side
the current [Link] project.
a. Public
b. Protected
c. Friend
9. Default properties are always a parameterized property.
a. True
b. False
10. How do you limit implicit type conversion in [Link]?
a. Option Strict On
b. Option Strict=1
c. Options Strict True
d. Option Strict off

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. (d) 2. (a) 3. (c) 4. (b) 5. (c)
6. (c) 7. (a) 8. (c) 9. (a) 10. (a)

3G E-LEARNING
Executing the Debugging 137

REFERENCES
1. Costabile, Maria Francesca, Daniela Fogli, Giuseppe Fresta, Piero Mussio & Antonio
Piccinno , Building Environments for End-User Development and Tailoring . In
IEEE Symposia on Human-Centric Computing Languages and Environments
(HCC) 2003, Auckland, New Zealand , October 2003.
2. Costagliola, Gennaro, Vincenzo deufemia, Filomena Ferrucci, Carmine Gravino,
The Use of the GXL Approach for Supporting Visual Language Specification and
Interchanging. In 2002 IEEE Symposia on Human Centric computing Languages
and Environments, Arlington, VA, USA, September 2002. Pages 131 to 138.
3. Cox, Philip T, Lei Dong, Obstacles to the industrial use of visual programming.
In 2004 International Workshop on Visual Languages and Computing, San
Francisco, CA, Sept 2004. Pages 304 to 311.
4. Cramer, Bastian, Uwe Kastens, Animation automatically generated from simulation
specifications. In 2009 IEEE Symposium on Visual Languages and Human-Centric
Computing, , , 9 2009.
5. Spinellis, Diomidis, Unix tools as visual programming components in a GUI-
builder environment. In Software: Practice and Experience, January, 2002. Pages
57 to 71.

3G E-LEARNING
6
CHAPTER

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:
1. Understand about the
basics of procedures
2. Define the concept of
arrays in visual basic

INTRODUCTION
A procedure is a small program that is meant to solve a
relatively small problem. In fact, sometimes it is called a
140 Basic Computer Coding: Visual Basic

sub-program. A program developer writes the procedure and a user (the user is either
you or another programmer) would only see the result. There are two categories of
procedures you will use in your programs: those that have already been created thus
made available to you, and those you will create yourself.
By definition, an array is a variable with a single name that represents many
different items. When we work with a single item, we only need to use one variable.
However, if we have a list of items which are of similar type to deal with, we need
to declare an array of variables instead of using a variable for each item. For example,
if we need to enter one hundred names, it is difficult to declare 100 different names.
Besides, if we want to process those data that involves decision making, we might have
to use hundreds of if...then statements, this is a waste of time and efforts. So, instead
of declaring one hundred different variables, we need to declare only one array. We
differentiate each item in the array by using subscript, the index value of each item,
for example, name(1), name(2), name(3) .......etc. , makes declaring variables more
streamline.

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

3G E-LEARNING
Procedures and Arrays 141

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 Keyword
structures. By default, it is Public, which means you can call A Sub
procedure
it from anywhere in your application that has access to the
can take
module, class, or structure in which you defined it. The term, arguments, such
method, describes a Sub or Function procedure that is accessed as constants,
from outside its defining module, class, or structure. variables, or
expressions, which
are passed to it by
Declaration Syntax the calling code.

The syntax for declaring a Sub procedure is as follows:


[ modifiers ] Sub subname [( parameterlist )]
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:

3G E-LEARNING
142 Basic Computer Coding: Visual Basic

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.

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

3G E-LEARNING
Procedures and Arrays 143

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


Call Assign()
End Sub

3G E-LEARNING
144 Basic Computer Coding: Visual Basic

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.
In order to add General procedure:
■■ The Code window is opened for the module to which the procedure is to
be added.
■■ The Add Procedure option is chosen from the Tools menu, which opens an
Add Procedure dialog box as shown in the figure given below.
■■ 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

3G E-LEARNING
Procedures and Arrays 145

outside the module, or Private to create a procedure


that can be invoked only from within the module.
Keyword
Programming
is the process of
taking an algorithm
and encoding it
into a notation,
a programming
language, so that it
can be executed by
a computer.

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.

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

3G E-LEARNING
146 Basic Computer Coding: Visual Basic

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

3G E-LEARNING
Procedures and Arrays 147

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 is executed. The following
Keyword
example illustrates this.
Function is
Function FunctionName [(ParameterList)] As ReturnType a block of
organized, reusable
‘ The following statement does not transfer control code that is used to
back to the calling code. perform a single,
FunctionName = Expression related action.
It provide better
‘ When control returns to the calling code, Expression modularity for
is the return value. your application
and a high degree
End Function of code reusing.
The advantage of assigning the return value to the function You have already
name is that control does not return from the procedure until seen various
functions like
it encounters an Exit Function or End Function statement. printf() and main().
This allows you to assign a preliminary value and adjust it
later if necessary.

Calling Syntax
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, all the actions of the

3G E-LEARNING
148 Basic Computer Coding: Visual Basic

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
Remember
Function hypotenuse(ByVal side1 As Single, ByVal side2
A
As Single) As Single
property
procedure is a Return [Link]((side1 ^ 2) + (side2 ^ 2))
series of Visual
Basic statements
End Function
that manipulate The following example shows a typical call to hypotenuse.
a custom
property on a Dim testLength, testHypotenuse As Single
module, class, testHypotenuse = hypotenuse(testLength, 10.7)
or structure.
Property
procedures are 6.1.5 Property Procedures
also known
as property A property procedure is used to create and manipulate custom
accessors. 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 Property Set procedure
that sets the references to an object.
Visual Basic provides for the following property procedures:
■■ 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.

3G E-LEARNING
Procedures and Arrays 149

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

3G E-LEARNING
150 Basic Computer Coding: Visual Basic

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

3G E-LEARNING
Procedures and Arrays 151

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

3G E-LEARNING
152 Basic Computer Coding: Visual Basic

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
Keyword we have to handle.
Visual
Basic (VB) Handling large numbers of grades quickly becomes
is a programming unwieldy. This in turn makes an application much more
environment from likely to have serious bugs.
Microsoft in which
a programmer uses It is difficult to maintain. Each new grade that we add
a graphical user requires that the application be modified, recompiled, and
interface (GUI) to redeployed.
choose and modify
preselected sections By using an array, you can refer to these related values
of code written by the same name, and use a number that’s called an index
in the BASIC or subscript to identify an individual element based on its
programming position in the array. The indexes of an array range from 0
language.
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, 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)

3G E-LEARNING
Procedures and Arrays 153

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}}

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.

3G E-LEARNING
154 Basic Computer Coding: Visual Basic

The general syntax to declare a one dimensional array is as follow:


Dim arrayName(subscript) as dataType
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

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:

3G E-LEARNING
Procedures and Arrays 155

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

3G E-LEARNING
156 Basic Computer Coding: Visual Basic

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

Keyword Figure 1
Static
array is 6.2.2 Dynamic Array
a composite
data type in
UnrealScript that
So far we have learned how to define the number of elements
groups multiple in an array during design time. This type of array is known
values of the same as static array. However, the problem is sometimes we might
type not know how many data items we need 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

3G E-LEARNING
Procedures and Arrays 157

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

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

Figure 2

3G E-LEARNING
158 Basic Computer Coding: Visual Basic

Building Skills
Another problem related to ReDim is each time you ReDim
an array, the values currently stored in the array are lost. In
order to preserve the stored values, we can use the keywords
ReDim Preserve, as follows
Did You ReDim Preserve MyArray(n)
Know? where n is the new upper bound of the array
In a 1999
paper, Brodnik The new Charlotte Church CD came out but your rack
et al. describe a only has three slots. You don’t want to throw away any of
tiered dynamic your CDs to make room for the new one so you decide to
array data use your ultimate building skills to attach another slot. You
structure, which
wastes only start building:
n1/2 space for n Dim strCDRack() As String
elements at any
point in time,
and they prove
a lower bound ReDim strCDRack(0 to 2) As String
showing that any
dynamic array
must waste this strCDRack(0) = “Deftones”
much space if strCDRack(1) = “Tool”
the operations
are to remain strCDRack(2) = “Disturbed”
amortized What have you done? Nothing wrong, you’ve just
constant time.
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

3G E-LEARNING
Procedures and Arrays 159

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

3G E-LEARNING
160 Basic Computer Coding: Visual Basic

strFriends(0) = “Bianca”
strFriends(1) = “Jeana”
strFriends(2) = “Sam”
strFriends(3) = “Jenna”
strFriends(4) = “Erin”
strFriends(5) = “Carolyn”
strFriends(6) = “Kate”

For lngPosition = LBound(strFriends) To UBound(strFriends)

Keyword MsgBox strFriends(lngPosition)


Snippet
is a
Next lngPositionlngPositionlngPosition
programming
term for a small There are two new functions in that snippet of code.
region of re-usable LBound and UBound are used to determine the lower and
source code, upper bounds of an array. Because strFriends has a lower bound
machine code, or of 0 and an upper bound of 6. These functions allow you to
text. Ordinarily,
these are formally
to iterate through an array with a dynamic size and they keep
defined operative you from having to keep track of the array›s size yourself.
units to incorporate With each iteration of that loop, lngPosition will count up from
into larger 0 to 6. By accessing the array as strFriends(lngPosition) you
programming
are greatly reducing the amount of code you have to write.
modules.

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

3G E-LEARNING
Procedures and Arrays 161

‘ 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:
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”

3G E-LEARNING
162 Basic Computer Coding: Visual Basic

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”

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

3G E-LEARNING
Procedures and Arrays 163

SUMMARY
■■ Visual Basic offers different types of procedures to execute small sections of
coding in applications.
■■ Procedures used in one program can act as building blocks for other programs
with slight modifications.
■■ 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.
■■ 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.
■■ You invoke a Sub procedure explicitly with a stand-alone calling statement.
You cannot call it by using its name in an expression.
■■ 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.
■■ 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.
■■ 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.
■■ By using an array, you can refer to these related values by the same name,
and use a number that’s called an index or subscript to identify an individual
element based on its position in the 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.

3G E-LEARNING
164 Basic Computer Coding: Visual Basic

■■ Multidimensional arrays can be thought of as arrays-of-arrays. For example,


to visualize a two dimensional array we could picture a row of CD racks.
■■ 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.

3G E-LEARNING
Procedures and Arrays 165

KNOWLEDGE CHECK
1. What is the value of the index for the first element in a [Link] array?
a. 0
b. 1
c. 2
d. 3
e. Depends on what the assigned value is.
2. Which method will return the number of elements in an array?
a. Dimension
b. Length
c. Number
d. Size
e. UpperBound
3. In the statement, Dim Days(7) as String, what part of the array does the number
7 refer to?
a. Array name
b. Datatype
c. Lowerbound
d. Upperbound
e. Size
4. What is required to reference an element in an array?
a. Array name
b. Index value of the element
c. Element value
d. Both a and b.
e. All of the above.
5. Which method will arrange the elements of an array in alphabetical order?
a. Arrange
b. Assemble
c. Order
d. Rank
e. Sort

3G E-LEARNING
166 Basic Computer Coding: Visual Basic

6. The number of variables allowed in a structured is:


a. 0
b. 1
c. 2
d. 3
e. Any number of variables can be declared in an array.
7. The variable inside a structure is called a(n):
a. associate.
b. constituent.
c. element.
d. member.
e. part.
8. Which datatype can an array not hold?
a. TextBoxes
b. Labels
c. Structures
d. Controls
e. An array can hold all of the above.
9. An array of controls can be populated by:
a. assigning existing controls to the array.
b. creating controls and assigning them to the array.
c. borrowing controls that will automatically assign them to the array.
d. Both a and b.
e. All of the above.
10. The Tag property can:
a. only hold string values.
b. only hold integer values.
c. only hold Boolean values.
d. only hold controls.
e. hold any data defined by the programmer.

3G E-LEARNING
Procedures and Arrays 167

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. (a) 2. (b) 3. (d) 4. (d) 5. (e)
6. (e) 7. (d) 8. (e) 9. (d) 10. (a)

3G E-LEARNING
168 Basic Computer Coding: Visual Basic

REFERENCES
1. Homer, Alex, Dave Sussman, and Mark Fussell. A First Look at Costagliola,
Gennaro, Vincenzo Deufemia, Michele Risi, A Multi-layer Parsing Strategy for
On-line Recognition of Hand-drawn Diagrams. In 2006 IEEE Symposium on
Visual Languages and Human-Centric Computing (VL/HCC’06), Brighton, United
Kingdom, September 2006. Pages 103 to 110.
2. Dong, Jing, Sheng Yang, Visualizing Design Patterns With A UML Profile. In
The 2003 IEEE Symposium on Visual/Multimedia Languages , Auckland, New
Zealand, October 2003.
3. Gauvin, Simon, Trevor Smedley, Reduction of Cognitive Load Through the
Addition of High-Level Semantics to ReactoGraph. In VL/HCC 2004, Rome,
Italy, Sept 2004.
4. Gestwicki, Paul, Bharat Jayaraman, Interactive Visualization of Java Programs. In
IEEE Symposium on Human-Centric Computing, Languages, and Environments,
Arlington, VA/USA, September 2002.
5. Gordon, Donald, Robert Biddle, James Noble, Ewan Tempero, A Technology For
Lightweight Web-Based Visual Applications. In 2003 IEEE Symposium on Visual/
Multimedia Software Engineering, Auckland, New Zealand, October 2003.
6. Grigoreanu, Valentina, Roland Fernandez, Kori Inkpen, George Robertson,
What Designers Want: Needs of Interactive Application Designers. In 2009 IEEE
Symposium on Visual Languages and Human-Centric Computing, Corvallis, OR,
September 2009.

3G E-LEARNING
7
CHAPTER

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:
1. Understand the ADO.
Net object model
2. Connect to a database
3. Create table, columns
and rows
4. Select the data source

INTRODUCTION
Over the years, Visual Basic has become an application
development tool used for developing Client/Server
170 Basic Computer Coding: Visual Basic

applications. This is an area of Visual Basic that seems to be


getting better and better with every new version. For instance,
Visual Basic 6.0 has introduced a new way of accessing data
through ADO & OLEDB. And Microsoft says you stick to
ADO because that is the future. Old methods like DAO and
RDO are already obsolete.
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.
Keyword
Object
model is 7.1 [Link] OBJECT MODEL
a logical interface,
software or system [Link] object model is nothing but the structured process
that is modeled flow through various components. The object model can be
through the use
pictorially described as –
of object-oriented
techniques.

3G E-LEARNING
Data Access 171

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.
3 DataReader

Data reader is used to retrieve data from a data source in a


read-only and forward-only mode.

3G E-LEARNING
172 Basic Computer Coding: Visual Basic

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.
Keyword ■■ The .Net Framework data provider for ODBC -
Dataset is provides access to data sources exposed by ODBC.
a collection ■■ The .Net Framework data provider for Oracle -
of related, discrete provides access to Oracle data source.
items of related
data that may ■■ The EntityClient provider - enables accessing data
be accessed through Entity Data Model (EDM) applications.
individually or
in combination
or managed as a 7.1.2 DataSet
whole entity.
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.
The following diagram shows the dataset object model −

3G E-LEARNING
Data Access 173

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.


7 DataView

It represents a fixed customized view of a DataTable for


sorting, filtering, searching, editing and navigation.

3G E-LEARNING
174 Basic Computer Coding: Visual Basic

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.

Keyword
Server
7.2 CONNECTING TO A DATABASE
Explorer Begin by launching Visual Studio and creating a new Windows
is the server
management
Application project called “VBdatabase”. Once the new project
console for Visual has been created the first task is to connect to the Northwind
Studio. Use this database. Click on the View menu and select Server Explorer.
window to open The Server Explorer panel will appear on the left hand side
data connections
of the main Visual Studio area:
and to log on to
servers and explore
their databases and
system services.

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

3G E-LEARNING
Data Access 175

Did You
Know?
Visual
Basic 3.0 was
released in the
summer of 1993
and came in
Change the Data source field to Microsoft Access Database if Standard and
Professional
necessary. Click on the Browse button and locate the Northwind. versions.
mdb database. Once you have selected the Northwind database VB3 included
click on the Test Connection button to verify the database is version 1.1 of
accessible. Assuming the connection is successful, click on the the Microsoft Jet
OK button to apply the connection. Database Engine
that could read
The database is now connected to the application and it and write Jet
is time to select a data source. (or Access) 1.x
databases.
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.

Example
We have a table stored in Microsoft SQL Server, named
Customers, in a database named testDB. Please consult ‘SQL
Server’ tutorial for creating databases and database tables in
SQL Server.
Let us connect to this database. Take the following steps −
■■ Select TOOLS → Connect to Database

3G E-LEARNING
176 Basic Computer Coding: Visual Basic

Remember
Login and
logout
events will not
be raised on the
server when a
connection is
fetched from ■■ Select a server name and the database name in the
or returned to Add Connection dialog box.
the connection
pool, because
the connection
is not actually
closed when it is
returned to the
connection pool.

■■ Click on the Test Connection button to check if the


connection succeeded.

3G E-LEARNING
Data Access 177

■■ Add a DataGridView on the form.

■■ Click on the Choose Data Source combo box.


■■ Click on the Add Project Data Source link.

■■ This opens the Data Source Configuration Wizard.


■■ Select Database as the data source type

3G E-LEARNING
178 Basic Computer Coding: Visual Basic

■■ Choose DataSet as the database model.

■■ Choose the connection already set up.

■■ Save the connection string.

3G E-LEARNING
Data Access 179

■■ Choose the database object, Customers table in our example, and click the
Finish button.

Select the Preview Data link to see the data in the Results grid −

3G E-LEARNING
180 Basic Computer Coding: Visual Basic

When the application is run using Start button available at the Microsoft Visual
Studio tool bar, it will show the following window −

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 ‘[Link]’
table.
You can move, or remove it, as needed.

[Link]([Link])
‘ Set the caption bar text of the form.
[Link] = “[Link]”
End Sub

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


Click

3G E-LEARNING
Data Access 181

Dim connection As SqlConnection = New sqlconnection()


[Link] = “Data Source=KABIR-
DESKTOP; _
Initial Catalog=testDB;Integrated Security=True”
[Link]()
Dim adp As SqlDataAdapter = New SqlDataAdapter _ Keyword
(“select * from Customers”, connection) Data
grid is a
Dim ds As DataSet = New DataSet() system composed
[Link](ds) of multiple
servers that work
[Link] = [Link](0) together to manage
End Sub information
and related
End Class operations - such
as computations
■■ When the above code is executed and run using Start - in a distributed
button available at the Microsoft Visual Studio tool environment.
bar, it will show the following window −

■■ Clicking the Fill button displays the table on the data


grid view control –

3G E-LEARNING
182 Basic Computer Coding: Visual Basic

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

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

3G E-LEARNING
Data Access 183

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
End Function

Private Sub AddNewColumn(ByRef table As DataTable, _


ByVal columnType As String, ByVal columnName As String)
Dim column As DataColumn = _
[Link](columnName, [Link](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 Button1.


Click
Dim ds As New DataSet
ds = CreateDataSet()
[Link] = [Link](“Student”)
End Sub

3G E-LEARNING
184 Basic Computer Coding: Visual Basic

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:

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

3G E-LEARNING
Data Access 185

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. Keyword
Data
7.4.1 Linking Data Sources to an Application source is
the location where
data that is being
The next step in our tutorial is to add some data fields to our used come from.
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 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:

3G E-LEARNING
186 Basic Computer Coding: Visual Basic

Once the data fields are added you will notice that Visual
Basic adds a toolbar to the top of the form to provide navigation
Keyword and the ability to add and remove records from the database.
TextBox Press F5 to build and run the application. When the application
is a starts the fields will be populated with data from the database.
composite control Use the toolbar to move through the records:
that is composed
of several
encapsulated
components.

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.

3G E-LEARNING
Data Access 187

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:

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:

3G E-LEARNING
188 Basic Computer Coding: Visual Basic

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-replication in cellular automata, extending on work

3G E-LEARNING
Data Access 189

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

3G E-LEARNING
190 Basic Computer Coding: Visual Basic

SUMMARY
■■ [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.
■■ DataSet components like DataTable, DataColumn and DataRow allow us to
create tables, columns and rows, respectively.
■■ 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.
■■ 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).

3G E-LEARNING
Data Access 191

KNOWLEDGE CHECK
1. A collection of data designed to be used by different people is called 1.
_____________ works as a bridge between data source and data set.
a. Data Reader
b. Data Provider
c. Data Adapter
d. Data Relation
2. What is the full form of XML?
a. Extension Mark Language
b. Extension Model Language
c. Extensible Markup Language
d. Extensible Mark Language
3. How many methods are used in database programming with [Link]?
a. 1
b. 4
c. 2
d. 3
4. What is the shortcut key to open Server Explorer?
a. Shift+S
b. Ctrl+Alt+S
c. Shift+Alt+S
d. Ctrl+S
5. When was ADO introduce by Microsoft?
a. 1990
b. 1991
c. 1995
d. 1996
6. Which one is Data Adapter Object?
a. OleDb
b. Sql
c. Odbc
d. All

3G E-LEARNING
192 Basic Computer Coding: Visual Basic

7. Through __________Controls we can access information in the databases.


a. Data Bound Control
b. Data Control
c. Wizard
d. Report
8. Which does the solution explorer not display?
a. Form Properties
b. Reference Folder
c. Form File
d. Assemble File
9. How many properties in SQL Command?
a. 2
b. 1
c. 3
d. 4
10. What is ODBC in [Link]?
a. Open Database Connectivity
b. Open Data Connection
c. Open Database Connection
d. Open Data Connectivity

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. (c) 2. (c) 3. (d) 4. (b) 5. (d)
6. (d) 7. (a) 8. (a) 9. (d) 10. (a)

3G E-LEARNING
Data Access 193

REFERENCES
1. Grundy, John, John G Hosking, High-level Static and Dynamic Visualisation
of Software Architectures. In IEEE Symposium on Visual Languages, Seattle,
Washington, September 2000.
2. Hirakawa, Masahito, Yuki Kojima, Atsuo Yoshitaka, Transparent Interface: A
Seamless Media Space Integrating the Real and Virtual Worlds. In 2003 IEEE
Symposium on Human-Centric Computing Languages and Environments,
Auckland, New Zealand, October 2003.
3. Hundhausen, Christopher, Jonathan Lee Brown, What You See Is What You
Code: A Radically Dynamic Algorithm Visualization Development Model for
Novice Learners. In 2005 IEEE Symposium on Visual Languages, Dallas, TX,
September 2005.
4. Jamroendararasame, Kornkamol, Tetsuya Suzuki and Takehiro Tokuda, A Visual
Approach to Development of Web Services Providers/Requestors. In 2003 IEEE
Symposium on Visual/Multimedia Software Engineering, Auckland, New Zealand,
October 2003.
5. Jonsson, Torsten A, Andreas Hamfelt, Uppsala University, DAViLa - A Domain
Adaptable Visual Language. In The 2003 IEEE Symposium on Visual / Multimedia
Languages, VL03, Auckland, New Zealand, October 2003.
6. Kim, Chul H, John Hosking and John Grundy, A Suite of Visual Languages for
Statistical Survey Specification. In 2005 IEEE Symposium on Visual Languages
and Human-Centric Computing, Dallas, Texas, September 2005.

3G E-LEARNING
8
CHAPTER

LIST, LOOPS
AND PRINTING

“Multitasking creates a dopamine-addiction feedback loop, effectively rewarding the brain for losing
focus and for constantly searching for external stimulation.”

–Daniel Levitin

LEARNING
OBJECTIVES
After studying this chapter, you
will be able to:
1. Explain list boxes & combo
boxes
2. Know how to filling the list
using property window
3. Understand clear method
4. Discuss about Do/Loops
5. Focus on For/Next Loops
6. Describe using MsgBox
function
7. Analyse using String
function INTRODUCTION
8. Perform printing to printer
using print method A loop is series of one or more statements that executes
more than one time. Loop statement repeats until a certain
196 Basic Computer Coding: Visual Basic

predefined condition is true. Two types of loop structures are available in VB. The
do loop and for-next loop. The do loop constructs offers many variations and is used
typically. If we do not know how many iterations will be performed.
We can use several methods to fill a listbox & combobox. If we know the list
contents at design time and list never changes , we define list item in properties
window. The list property holds the list of items for a listbox or combobox. To define
the List property at design time, select the control and scroll the properties window
to the List property.
Click on the down arrow to drop down the empty list and type our first item. Then
press Ctrl + Enter to move to the next list item. Continue typing items and pressing
Ctrl + Enter until we r finishe. On the last list item , do not press Ctrl + Enter or we
will have an extra (blank item) on the list.
For adding items to the list during program execution , we will use the AddItem
method in an event procedure. Syntax is as follows :
[Link] value (index)
Ex. [Link] “VB”
[Link] [Link]
A function that controls horizontal spacing on the line is the spc(space). The space
function differs from the tab function. In that we specify the number of spaces on the
line that we want to advance from the last item printed.

Syntax is as follows :
Spc(number of characters)
Ex.

[Link] Tab(20); “Name”; spc(5); “Phone”; Spc(5); “Address”


So far, any printed output has been done with the PrintForm method. When we
print using PrintForm , all output is produced as a graphic, which does not produce
attractive text.
In addition to printing forms, we will need to create reports or print small bits
of information on the printer. We can use VB?s Print method to print text on a form,
on the Printer object, or in the Debug window.
We can set up an output for the printer using [Link] ([Link]). Visual
Basic establishes a printer object in memory for our output. Each time we issue a
[Link] method, our output is added to the printer object.

3G E-LEARNING
List, Loops and Printing 197

8.1 LIST BOXES & COMBO BOXES


ListBox and ComboBox controls present a set of choices that are
displayed vertically in a column. If the number of items exceed
the value that be displayed, scroll bars will automatically
appear on the control. These scroll bars can be scrolled up
and down or left to right through the list.
Keyword
Scroll bars
8.1.1 List Box is a bar
that appears on the
The function of the List Box in visual basic 2017 is to display side or bottom of a
window to control
a list of items. The user can click and select the items from
which part of a
the list. Items can be added at design time or at runtime. The list or document
items can also be removed at design time and also at runtime. is currently in the
window ‘s frame.
Adding Items to a List Box
To demonstrate how to add items at design time, start a
new project and insert a list box on the form. Right-click on
the list box to access the properties window. Next, click on
collection of the Item property, you will be presented with
String Collection Editor whereby you can enter the items one
by one by typing the text and press the Enter key, as shown
in Figure 1

Figure 1
After clicking on the OK button, the items will be displayed
in the list box, as shown in Figure 2

3G E-LEARNING
198 Basic Computer Coding: Visual Basic

Figure 2
In Visual Basic 2017, Items can also be added at runtime using the Add( ) method.
Visual Basic 2017 is an object-oriented programming language, therefore, it comprises
objects. All objects have methods and properties, and they can are differentiated and
connected by the hierarchy. For a list box, Item is an object subordinated to the object
ListBox. Item comprises a method called Add() that is used to add items to the list
box. To add an item to a list box, you can use the following syntax:

[Link](“Text”)
For example, if you wish to add a new item to ListBox1 above, you can key-in the
following statement
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles [Link]
[Link](“Microsoft Visual Studio 2017”)
End Sub
The item “Visual Studio 2017” will be added to the end of the list, as shown in
Figure 3

3G E-LEARNING
List, Loops and Printing 199

Figure 3
You can also allow the user to add their own items using the InputBox function.
To add this capability, insert a button at design time and change its text to Add Item.
Click on the button and enter the following statements in the code window:
Private Sub BtnAdd_Click(sender As Object, e As EventArgs) Handles [Link]
Dim myitem
myitem = InputBox(“Enter your Item”)
[Link](myitem)
End Sub
* The keyword Dim is to declare the variable myitem.
Run the program and click on the Add item button will bring up an input box
where the user can key in the item he or she wants to add to the list, as shown in
Figure 4

Figure 4

3G E-LEARNING
200 Basic Computer Coding: Visual Basic

Deleting Items from a List Box


To delete items at design time, simply open the String Collection Editor and delete
the items line by line or all at once using the Delete key.
To delete an item at runtime, you can use the Remove method in the following
syntax:

[Link](“text”)
It is illustrated in the following example:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles [Link]
[Link](“Visual Basic 6”)
End Sub
The item “Visual Basic 6” will be removed after running the program. You can
also let the user choose which item to delete.
You can also allow the user to delete their own items using the InputBox function.
To add this capability, insert a button at design time and change its text to Delete
Item. Click on the button and enter the following statements in the code window:
Private Sub BtnDelete_Click(sender As Object, e As EventArgs) Handles Button1.
Click
Dim myitem
myitem = InputBox(“Enter your Item for Deletion”)
[Link](myitem)
End Sub
To clear all the items at once, use the clear method, as illustrated in the following
example. In this example, add a button and label it “Clear Items”
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles [Link]
[Link]()
End Sub

8.1.2 Combo Box


In Visual Basic 2017, the function of the Combo Box is also to present a list of items
where the user can click and select the items from the list. However, the user needs to
click on the handle(small arrowhead) on the right of the combo box to see the items
which are presented in a drop-down list.

3G E-LEARNING
List, Loops and Printing 201

Properties of the ComboBox Control


The following are some of the commonly used properties of the ComboBox control −

[Link]. Property & Description


1 AllowSelection

Gets a value indicating whether the list enables selection of list items.
2 AutoCompleteCustomSource

Gets or sets a custom [Link] .[Link] to use


when the AutoCompleteSourceproperty is set to CustomSource.
3 AutoCompleteMode

Gets or sets an option that controls how automatic completion works for the
ComboBox.
4 AutoCompleteSource

Gets or sets a value specifying the source of complete strings used for automatic
completion.
5 DataBindings

Gets the data bindings for the control.


6 DataManager

Gets the CurrencyManager associated with this control.


7 DataSource

Gets or sets the data source for this ComboBox.


8 DropDownHeight

Gets or sets the height in pixels of the drop-down portion of the ComboBox.
9 DropDownStyle

Gets or sets a value specifying the style of the combo box.


10 DropDownWidth

Gets or sets the width of the of the drop-down portion of a combo box.
11 DroppedDown

Gets or sets a value indicating whether the combo box is displaying its drop-
down portion.
12 FlatStyle

Gets or sets the appearance of the ComboBox.

3G E-LEARNING
202 Basic Computer Coding: Visual Basic

13 ItemHeight

Gets or sets the height of an item in the combo box.


14 Items

Gets an object representing the collection of the items contained in this ComboBox.
15 MaxDropDownItems

Gets or sets the maximum number of items to be displayed in the drop-down


part of the combo box.
16 MaxLength

Gets or sets the maximum number of characters a user can enter in the editable
area of the combo box.
17 SelectedIndex

Gets or sets the index specifying the currently selected item.


18 SelectedItem

Gets or sets currently selected item in the ComboBox.


19 SelectedText

Gets or sets the text that is selected in the editable portion of a ComboBox.
20 SelectedValue

Gets or sets the value of the member property specified by the ValueMember
property.
21 SelectionLength

Gets or sets the number of characters selected in the editable portion of the combo
box.
22 SelectionStart

Gets or sets the starting index of text selected in the combo box.
23 Sorted

Gets or sets a value indicating whether the items in the combo box are sorted.
24 Text

Gets or sets the text associated with this control.

3G E-LEARNING
List, Loops and Printing 203

Methods of the ComboBox Control


The following are some of the commonly used methods of the ComboBox control −

[Link]. Method Name & Description


1 BeginUpdate

Prevents the control from drawing until the EndUpdate method is called,
while items are added to the combo box one at a time.
2 EndUpdate

Resumes drawing of a combo box, after it was turned off by the


BeginUpdate method.
3 FindString

Finds the first item in the combo box that starts with the string specified
as an argument.
4 FindStringExact

Finds the first item in the combo box that exactly matches the specified
string.
5 SelectAll

Selects all the text in the editable area of the combo box.

Events of the ComboBox Control


The following are some of the commonly used events of the ComboBox control −

[Link]. Event & Description


1 DropDown

Occurs when the drop-down portion of a combo box is


displayed.
2 DropDownClosed

Occurs when the drop-down portion of a combo box is no


longer visible.
3 DropDownStyleChanged

Occurs when the DropDownStyle property of the


ComboBox has changed.

3G E-LEARNING
204 Basic Computer Coding: Visual Basic

4 SelectedIndexChanged

Occurs when the SelectedIndex property of a ComboBox


control has changed.
5 SelectionChangeCommitted

Occurs when the selected item has changed and the change
appears in the combo box.
Keyword
Runtime Adding Items to a Combo Box
is when
a program is In order to add items to the list at design time, you can also
running (or being
use the String Collection Editor. You will have to type an item
executable). That
is, when you start under the text property in order to display the default item
a program running at runtime. The following is the runtime interface:
in a computer, it
is runtime for that
program.

Figure 5
After clicking the handle of the right side of the combo
box, the user will be able to view all the items, as shown in
Figure 6

Figure 6

3G E-LEARNING
List, Loops and Printing 205

Besides, you may add items using the Add() method. For example, if you wish
to add an item to Combo box 1, you can key in the following statement
Private Sub BtnAdd_Click(sender As Object, e As EventArgs) Handles [Link]
[Link](“Visual Studio 2017”)
End Sub

You can also allow the user to add their own items using the InputBox function,
as follows:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles [Link]
Dim myitem
myitem = InputBox(“Enter your Item”)
[Link](myitem)
End Sub

Removing Items from a Combo Box


To delete items at design time, simply open the String Collection Editor and delete
the items at line by line or all at once using the Delete key.
To delete the items at runtime, you can use the Remove method, as illustrated in the
following example. In this example, add a second button and label it “Remove Items”.
Click on this button and enter the following code:

Private Sub Delete_Click(sender As Object, e As EventArgs) Handles [Link]


[Link](“Visual Basic 6”)
End Sub
The item “Visual Basic 6” will be removed after running the program. You can
also let the user choose which item to delete.
To clear all the items at once, use the clear method, as illustrated in the following
example. In this example, add a button and label it “Clear Items”
Private Sub Btn_Clr_Click(sender As Object, e As EventArgs) Handles [Link]
[Link]()
End Sub

Example
In this example, let us fill a combo box with various items, get the selected items in
the combo box and show them in a list box and sort the items.

3G E-LEARNING
206 Basic Computer Coding: Visual Basic

Drag and drop a combo box to store the items, a list box to display the selected
items, four button controls to add to the list box with selected items, to fill the combo
box, to sort the items and to clear the combo box list, respectively.
Add a label control that would display the selected item.

Add the following code in the code editor window −


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

‘sends the selected items to the list box


Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.
Click
If [Link] > -1 Then
Dim sindex As Integer
sindex = [Link]
Dim sitem As Object
sitem = [Link]
[Link](sitem)

3G E-LEARNING
List, Loops and Printing 207

End If
End Sub

‘populates the list


Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.
Click
[Link]()
[Link](“Safety”)
[Link](“Security”)
[Link](“Governance”)
[Link](“Good Music”)
[Link](“Good Movies”)
[Link](“Good Books”)
[Link](“Education”)
[Link](“Roads”)
[Link](“Health”)
[Link](“Food for all”)
[Link](“Shelter for all”)
[Link](“Industrialisation”)
[Link](“Peace”)
[Link](“Liberty”)
[Link](“Freedom of Speech”)
[Link] = “Select from...”
End Sub
‘sorting the list

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


[Link] = True
End Sub
‘clears the list

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


[Link]()

3G E-LEARNING
208 Basic Computer Coding: Visual Basic

End Sub
‘displaying the selected item on the label

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


_
Handles [Link]
[Link] = [Link]()
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 −

Click on various buttons to check the actions performed by each −

3G E-LEARNING
List, Loops and Printing 209

8.2 FILLING THE LIST USING PROPERTY


WINDOW
The ListBox represents a Windows control to display a list
of items to a user. A user can select an item from the list. It
allows the programmer to add items at design time by using Keyword
the properties window or at the runtime. ToolboX
is an
Let’s create a list box by dragging a ListBox control from integrated
the Toolbox and dropping it on the form. development
environment
designed to
introduce
computer
programming in
academic subjects
with originally no
competences in this
matter.

You can populate the list box items either from the
properties window or at runtime. To add items to a ListBox,
select the ListBox control and get to the properties window,
for the properties of this control. Click the ellipses (...) button
next to the Items property. This opens the String Collection
Editor dialog box, where you can enter the values one at a line.

8.2.1 Properties of the ListBox Control


The following are some of the commonly used properties of
the ListBox control −

[Link]. Property & Description


1 AllowSelection

Gets a value indicating whether the ListBox currently


enables selection of list items.

3G E-LEARNING
210 Basic Computer Coding: Visual Basic

2 BorderStyle

Gets or sets the type of border drawn around the list


box.
3 ColumnWidth

Gets of sets the width of columns in a multicolumn


list box.
4 HorizontalExtent

Gets or sets the horizontal scrolling area of a list box.


5 HorizontalScrollBar

Gets or sets the value indicating whether a horizontal


scrollbar is displayed in the list box.
6 ItemHeight

Gets or sets the height of an item in the list box.


7 Items

Gets the items of the list box.


8 MultiColumn

Gets or sets a value indicating whether the list box


supports multiple columns.
9 ScrollAlwaysVisible

Gets or sets a value indicating whether the vertical


scroll bar is shown at all times.
10 SelectedIndex

Gets or sets the zero-based index of the currently


selected item in a list box.
11 SelectedIndices

Gets a collection that contains the zero-based indexes


of all currently selected items in the list box.
12 SelectedItem

Gets or sets the currently selected item in the list box.


13 SelectedItems

Gets a collection containing the currently selected


items in the list box.

3G E-LEARNING
List, Loops and Printing 211

14 SelectedValue

Gets or sets the value of the member property


specified by the ValueMember property.
15 SelectionMode

Gets or sets the method in which items are selected in


the list box. This property has values −

• None

• One

• MultiSimple

• MultiExtended
16 Sorted

Gets or sets a value indicating whether the items in


the list box are sorted alphabetically.
17 Text

Gets or searches for the text of the currently selected


item in the list box.
18 TopIndex

Gets or sets the index of the first visible item of a list


box.

8.2.2 Methods of the ListBox Control


The following are some of the commonly used methods of the ListBox control −

[Link]. Method Name & Description


1 BeginUpdate

Prevents the control from drawing until the EndUpdate method is called, while
items are added to the ListBox one at a time.
2 ClearSelected

Unselects all items in the ListBox.


3 EndUpdate

Resumes drawing of a list box after it was turned off by the BeginUpdate method.

3G E-LEARNING
212 Basic Computer Coding: Visual Basic

4 FindString

Finds the first item in the ListBox that starts with the string specified as an
argument.
5 FindStringExact

Finds the first item in the ListBox that exactly matches the specified string.
6 GetSelected

Returns a value indicating whether the specified item is selected.


7 SetSelected

Selects or clears the selection for the specified item in a ListBox.


8 OnSelectedIndexChanged

Raises the SelectedIndexChanged event.


8 OnSelectedValueChanged

Raises the SelectedValueChanged event.

8.2.3 Events of the ListBox Control


The following are some of the commonly used events of the ListBox control −

[Link]. Event & Description


1 Click

Occurs when a list box is selected.


2 SelectedIndexChanged

Occurs when the SelectedIndex property of a list box is changed.

Consult Microsoft documentation for detailed list of properties, methods and


events of the ListBox control.

Example
In the following example, let us add a list box at design time and add items on it at
runtime.
Take the following steps −
■■ Drag and drop two labels, a button and a ListBox control on the form.

3G E-LEARNING
List, Loops and Printing 213

■■ Set the Text property of the first label to provide the caption “Choose your
favourite destination for higher studies”.
■■ Set the Text property of the second label to provide the caption “Destination”.
The text on this label will change at runtime when the user selects an item
on the list.
■■ Click the listbox and the button controls to add the following codes 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]”
[Link](“Canada”)
[Link](“USA”)
[Link](“UK”)
[Link](“Japan”)
[Link](“Russia”)
[Link](“China”)
[Link](“India”)
End Sub

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


Click
MsgBox(“You have selected “ + [Link]())
End Sub

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


Handles [Link]
[Link] = [Link]()
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 −

3G E-LEARNING
214 Basic Computer Coding: Visual Basic

When the user chooses a destination, the text in the second label changes −

Clicking the Select button displays a message box with the user’s choice −

3G E-LEARNING
List, Loops and Printing 215

Example
In this example, we will fill up a list box with items, retrieve the total number of
items in the list box, sort the list box, remove some items and clear the entire list box.
Design the Form −

Add the following code in the code editor window −


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]”
‘ creating multi-column and multiselect list box
[Link] = True
[Link] = [Link]
End Sub

‘populates the list


Private Sub Button1_Click_1(sender As Object, e As EventArgs) _
Handles [Link]
[Link](“Safety”)
[Link](“Security”)
[Link](“Governance”)
[Link](“Good Music”)
[Link](“Good Movies”)

3G E-LEARNING
216 Basic Computer Coding: Visual Basic

[Link](“Good Books”)
[Link](“Education”)
[Link](“Roads”)
[Link](“Health”)
[Link](“Food for all”)
[Link](“Shelter for all”)
[Link](“Industrialisation”)
[Link](“Peace”)
[Link](“Liberty”)
[Link](“Freedom of Speech”)
End Sub
‘sorting the list
Private Sub Button2_Click(sender As Object, e As EventArgs) _
Handles [Link]
[Link] = True
End Sub

‘clears the list


Private Sub Button3_Click(sender As Object, e As EventArgs) _
Handles [Link]
[Link]()
End Sub

‘removing the selected item


Private Sub Button4_Click(sender As Object, e As EventArgs) _
Handles [Link]
[Link]([Link])
End Sub

‘counting the numer of items


Private Sub Button5_Click(sender As Object, e As EventArgs) _
Handles [Link]
[Link] = [Link]

3G E-LEARNING
List, Loops and Printing 217

End Sub

‘displaying the selected item on the third label


Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) _
Handles [Link]
[Link] = [Link]()
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 −

Fill the list and check workings of other buttons −

8.3 CLEAR METHOD


Clears all property settings of the Err object.

3G E-LEARNING
218 Basic Computer Coding: Visual Basic

8.3.1 Syntax
[Link]
The object is always the Err object.

8.3.2 Remarks
Use Clear to explicitly clear the Err object after an error has
Keyword been handled, for example, when you use deferred error
Code is a handling with On Error Resume Next. The Clear method is
term used called automatically whenever any of the following statements
to describe text that
is written using
is executed:
the protocol of a ■■ Any type of Resume statement
particular language
by a computer ■■ Exit Sub, Exit Function, Exit Property
programmer. ■■ Any On Error statement
Note: The On Error Resume Next construct may be
preferable to On Error GoTo when handling errors generated
during access to other objects. Checking Err after each
interaction with an object removes ambiguity about which
object was accessed by the code. You can be sure which object
placed the error code in [Link], as well as which object
originally generated the error (the object specified in Err.
Source).

8.3.3 Example
This example uses the Err object’s Clear method to reset the
numeric properties of the Err object to zero and its string
properties to zero-length strings. If Clear were omitted from
the following code, the error message dialog box would be
displayed on every iteration of the loop (after an error occurs)
whether or not a successive calculation generated an error. You
can single-step through the code to see the effect.
VBCopy
Dim Result(10) As Integer ‘ Declare array whose elements
‘ will overflow easily.
Dim indx
On Error Resume Next ‘ Defer error trapping.
Do Until indx = 10

3G E-LEARNING
List, Loops and Printing 219

‘ Generate an occasional error or store result if no error.


Result(indx) = Rnd * indx * 20000
If [Link] <> 0 Then
MsgBox Err, , “Error Generated: “, [Link], [Link]
[Link] ‘ Clear Err object properties.
End If
indx = indx + 1
Loop

8.4 DO/LOOPS
There are two Do Loops in Visual Basic: the Do While and Do Until. The Do While
loops something which is true, and the Do Until loops until a certain condition is met.
Create a new VB Console Application and name it Do Loops.

8.4.1 Do Until
Dim myNumber As Integer = 0

Do Until myNumber = 5
[Link](“Pick a number between 1 and 6”)
myNumber = [Link]()

If myNumber = 5 Then
[Link](“Yes 5, it is!”)
Else
[Link](“Oops that’s not the lucky number!”)
End If
Loop
[Link]()

Code Explained
■■ First we make a integer and call it myNumber, and set its default value to 0
■■ Then we have a Do Until Statement which loops until myNumber = 5

3G E-LEARNING
220 Basic Computer Coding: Visual Basic

■■ Next we ask the user to pick a number between 1 and 6


■■ We read the user’s value and store it in myNumber
■■ If the number is not 5 then they get the text “Oops that’s not the lucky number”
■■ If they do not pick 5 then the question will be asked again. (It is an infinite
loop, so it will keep looping until myNumber is 5)
■■ If they pick 5 then they will get the message “Yes 5, it is!” The program will
close after this.

8.4.2 Do While
The Do While is similar to the Do Until but it evaluates something which is true.

Example
Dim mySecondNumber As Integer

Do While mySecondNumber < 50


mySecondNumber += 1
[Link](mySecondNumber)
Loop
[Link]()

Code Explained
■■ First we make a integer called mysecondNumber
■■ We use the Do While loop and see if mysecondNumber is less than 50 (which
is true)
■■ We then increment it by 1 until it reaches 50 (then the Do While will become
false)

8.4.3 Operators
You can use the following operators with Do Until and Do While:

Operator Description
< Less than
> Greater than

3G E-LEARNING
List, Loops and Printing 221

<= Less than or equal to


>= Greater than or equal to
<> Not equal to
= Equal to

8.4.4 Loop While and Loop Until


It is possible to place the While and Until after the loop so it appears as:
Dim myNumber As Integer = 0

Do
myNumber += 1
[Link](myNumber)
Loop While myNumber < 10

Do
myNumber += 1
[Link](myNumber)
Loop Until myNumber = 10

[Link]()
In this example, the Until and While are after the loop, and the code will
always execute at least once. Now if you run this code, it will crash and give an
overflowException: the first Loop While will execute and it will keep going until
myNumber is 10, and then it will exit. The Do Until loop will then execute, and this
will keep looping (infinitely) because myNumber is no longer equal to 10. The Do
Loop executed once and myNumber += 1 changed its value to 11, and therefore this
loop will execute until it reaches 10, but it won’t!
It is best to use Do While and Do Until instead of putting the While and Until
after the loop, because they will always keep executing. The Do While/Until will not
execute if its condition is false. Issues like the above example cause bugs in your
application since the variable changed.

Example
Dim myNumber As Integer = 0

3G E-LEARNING
222 Basic Computer Coding: Visual Basic

Do
myNumber += 1
[Link](myNumber)
Loop While myNumber < 10

Do Until myNumber = 10
myNumber += 1
[Link](myNumber)
Loop

[Link]()
This is similar to the above example, however this time when the first loop executes
and reaches 10, the second loop will not execute because myNumber is already 10.
This section covered the different types of Do Loops and also the operators. In
addition you learned about Loop Until and Loop While.

8.5 FOR/NEXT LOOPS


Repeats a group of statements a specified number of times.

8.5.1 Syntax
VBCopy
For counter [ As datatype ] = start To end [ Step step ]
[ statements ]
[ Continue For ]
[ statements ]
[ Exit For ]
[ statements ]
Next [ counter ]

3G E-LEARNING
List, Loops and Printing 223

8.5.2 Parts

Part Description
counter Required in the For statement. Numeric
variable. The control variable for the loop.
datatype Optional. Data type of counter.
start Required. Numeric expression. The initial
value of counter.
end Required. Numeric expression. The final
value of counter.
step Optional. Numeric expression. The amount
by which counter is incremented each time
through the loop.
statements Optional. One or more statements between Remember
For and Next that run the specified number The To
of times. keyword
Continue For Optional. Transfers control to the next loop is used in this
iteration. statement to
specify the range
Exit For Optional. Transfers control out of the For
for the counter.
loop.
You can also use
Next Required. Terminates the definition of the this keyword
For loop. in the Select...
Case Statement
and in array
8.5.3 Simple Examples declarations.

You use a For...Next structure when you want to repeat a set


of statements a set number of times.
In the following example, the index variable starts with a
value of 1 and is incremented with each iteration of the loop,
ending after the value of index reaches 5.
VBCopy
For index As Integer = 1 To 5
[Link]([Link] & “ “)
Next
[Link](“”)
‘ Output: 1 2 3 4 5
In the following example, the number variable starts at 2
and is reduced by 0.25 on each iteration of the loop, ending

3G E-LEARNING
224 Basic Computer Coding: Visual Basic

after the value of number reaches 0. The Step argument of -.25 reduces the value by
0.25 on each iteration of the loop.
VBCopy
For number As Double = 2 To 0 Step -0.25
[Link]([Link] & “ “)
Next
[Link](“”)
‘ Output: 2 1.75 1.5 1.25 1 0.75 0.5 0.25 0
Tip: A While...End While Statement or Do...Loop Statement works well when you
don’t know in advance how many times to run the statements in the loop. However,
when you expect to run the loop a specific number of times, a For...Next loop is a
better choice. You determine the number of iterations when you first enter the loop.

8.5.4 Nesting Loops


You can nest For loops by putting one loop within another. The following example
demonstrates nested For...Next structures that have different step values. The outer
loop creates a string for every iteration of the loop. The inner loop decrements a loop
counter variable for every iteration of the loop.
VBCopy
For indexA = 1 To 3
‘ Create a new StringBuilder, which is used
‘ to efficiently build strings.
Dim sb As New [Link]()

‘ Append to the StringBuilder every third number


‘ from 20 to 1 descending.
For indexB = 20 To 1 Step -3
[Link]([Link])
[Link](“ “)
Next indexB

‘ Display the line.


[Link]([Link])
Next indexA

3G E-LEARNING
List, Loops and Printing 225

‘ Output:
‘ 20 17 14 11 8 5 2
‘ 20 17 14 11 8 5 2
‘ 20 17 14 11 8 5 2
When nesting loops, each loop must have a unique
counter variable.
You can also nest different kinds control structures within
each other.

Keyword
8.5.5 Exit For and Continue For
A nested
loop join is
The Exit For statement immediately exits the For…Next loop a naive algorithm
and transfers control to the statement that follows the Next that joins two
statement. sets by using two
nested loops.
The Continue For statement transfers control immediately
to the next iteration of the loop.
The following example illustrates the use of the Continue
For and Exit For statements.
VBCopy
For i4ndex As Integer = 1 To 100000

‘ If index is between 5 and 7, continue


‘ with the next iteration.
If index >= 5 AndAlso index <= 8 Then
Continue For
End If

‘ Display the index.


[Link]([Link] & “ “)

‘ If index is 10, exit the loop.


If index = 10 Then
Exit For
End If
Next
[Link](“”)

3G E-LEARNING
226 Basic Computer Coding: Visual Basic

‘ Output: 1 2 3 4 9 10

You can put any number of Exit For statements in a For…Next loop. When used
within nested For…Next loops, Exit For exits the innermost loop and transfers control
to the next higher level of nesting.
Exit For is often used after you evaluate some condition (for example, in an If...
Then...Else structure). You might want to use Exit For for the following conditions:
■■ Continuing to iterate is unnecessary or impossible. An erroneous value or a
termination request might create this condition.
■■ A Try...Catch...Finally statement catches an exception. You might use Exit For
at the end of the Finally block.
■■ You have an endless loop, which is a loop that could run a large or even
infinite number of times. If you detect such a condition, you can use Exit For
to escape the loop.

8.5.6 Technical Implementation


When a For...Next loop starts, Visual Basic evaluates start, end, and step. Visual Basic
evaluates these values only at this time and then assigns start to counter. Before the
statement block runs, Visual Basic compares counter to end. If counter is already larger
than the end value (or smaller if step is negative), the For loop ends and control passes
to the statement that follows the Next statement. Otherwise, the statement block runs.
Each time Visual Basic encounters the Next statement, it increments counter by
step and returns to the For statement. Again it compares counter to end, and again it
either runs the block or exits the loop, depending on the result. This process continues
until counter passes end or an Exit For statement is encountered.
The loop doesn’t stop until counter has passed end. If counter is equal to end, the
loop continues. The comparison that determines whether to run the block is counter
<= end if step is positive and counter >= end if step is negative.
If you change the value of counter while inside a loop, your code might be more
difficult to read and debug. Changing the value of start, end, or step doesn’t affect
the iteration values that were determined when the loop was first entered. If you nest
loops, the compiler signals an error if it encounters the Next statement of an outer
nesting level before the Next statement of an inner level. However, the compiler can
detect this overlapping error only if you specify counter in every Next statement.

8.5.7 Step Argument


The value of step can be either positive or negative. This parameter determines loop
processing according to the following table:

3G E-LEARNING
List, Loops and Printing 227

STEP ARGUMENT
Step value Loop executes if
Positive or zero counter <= end
Negative counter >= end
Keyword
The default value of step is 1. A data
type is a
classification of
8.5.8 Counter Argument data which tells
the compiler or
The following table indicates whether counter defines a new interpreter how
the programmer
local variable that’s scoped to the entire For…Next loop. This intends to use the
determination depends on whether datatype is present and data.
whether counter is already defined.
COUNTER ARGUMENT
Is datatype Is counter Result (whether counter defines a new local variable that’s
present? already scoped to the entire For...Next loop)
defined?
No Yes No, because counter is already defined. If the scope of counter isn’t
local to the procedure, a compile-time warning occurs.
No No Yes. The data type is inferred from the start, end, and step
expressions.

Yes Yes Yes, but only if the existing counter variable is defined outside
the procedure. That variable remains separate. If the scope of the
existing counter variable is local to the procedure, a compile-time
error occurs.
Yes No Yes.
The data type of counter determines the type of the iteration,
which must be one of the following types:
■■ A Byte, SByte, UShort, Short, UInteger, Integer, ULong,
Long, Decimal, Single, or Double.
■■ An enumeration that you declare by using an Enum
Statement.
■■ An Object.
■■ A type T that has the following operators, where B
is a type that can be used in a Boolean expression.
Public Shared Operator >= (op1 As T, op2 As T) As B
Public Shared Operator <= (op1 As T, op2 As T) As B
Public Shared Operator - (op1 As T, op2 As T) As T

3G E-LEARNING
228 Basic Computer Coding: Visual Basic

Public Shared Operator + (op1 As T, op2 As T) As T


You can optionally specify the counter variable in the
Next statement. This syntax improves the readability of your
Remember
program, especially if you have nested For loops.
You must
specify The start, end, and step expressions can evaluate to any
the variable that data type that widens to the type of counter. If you use a
appears in the user-defined type for counter, you might have to define the
corresponding CType conversion operator to convert the types of start, end,
For statement. or step to the type of counter.

Example
The following example removes all elements from a generic
list. Instead of a For Each...Next Statement, the example shows
a For...Next statement that iterates in descending order. The
example uses this technique because the removeAt method
causes elements after the removed element to have a lower
index value.
VBCopy
Dim lst As New List(Of Integer) From {10, 20, 30, 40}

For index As Integer = [Link] - 1 To 0 Step -1


[Link](index)
Next

[Link]([Link])
‘ Output: 0

Example
The following example iterates through an enumeration that’s
declared by using an Enum Statement.
VBCopy
Public Enum Mammals
Buffalo
Gazelle
Mongoose
Rhinoceros

3G E-LEARNING
List, Loops and Printing 229

Whale
End Enum

Public Sub ListSomeMammals()


For mammal As Mammals = [Link] To [Link]
[Link]([Link] & “ “)
Next
[Link](“”)
‘ Output: Gazelle Mongoose Rhinoceros
End Sub

Example
In the following example, the statement parameters use a class that has operator
overloads for the +, -, >=, and <= operators.
VBCopy
Private Class Distance
Public Property Number() As Double

Public Sub New(ByVal number As Double)


[Link] = number
End Sub

‘ Define operator overloads to support For...Next statements.


Public Shared Operator +(ByVal op1 As Distance, ByVal op2 As Distance) As Distance
Return New Distance([Link] + [Link])
End Operator

Public Shared Operator -(ByVal op1 As Distance, ByVal op2 As Distance) As Distance
Return New Distance([Link] - [Link])
End Operator

Public Shared Operator >=(ByVal op1 As Distance, ByVal op2 As Distance) As Boolean

3G E-LEARNING
230 Basic Computer Coding: Visual Basic

Return ([Link] >= [Link])


End Operator

Public Shared Operator <=(ByVal op1 As Distance, ByVal op2 As Distance) As Boolean
Return ([Link] <= [Link])
End Operator
End Class

Public Sub ListDistances()


Dim distFrom As New Distance(10)
Dim distTo As New Distance(25)
Dim distStep As New Distance(4)

For dist As Distance = distFrom To distTo Step distStep


[Link]([Link] & “ “)
Next
[Link](“”)

‘ Output: 10 14 18 22
End Sub

8.6 USING MSGBOX FUNCTION


The MsgBox function displays a message box and waits for the user to click a button
and then an action is performed based on the button clicked by the user.

8.6.1 Syntax
MsgBox(prompt[,buttons][,title][,helpfile,context])

8.6.2 Parameter Description


■■ Prompt − A Required Parameter. A String that is displayed as a message
in the dialog box. The maximum length of prompt is approximately 1024
characters. If the message extends to more than a line, then the lines can be

3G E-LEARNING
List, Loops and Printing 231

separated using a carriage return character (Chr(13)) or a linefeed character


(Chr(10)) between each line.
■■ Buttons − An Optional Parameter. A Numeric expression that specifies the
type of buttons to display, the icon style to use, the identity of the default
button, and the modality of the message box. If left blank, the default value
for buttons is 0.
■■ Title − An Optional Parameter. A String expression displayed in the title bar
of the dialog box. If the title is left blank, the application name is placed in
the title bar.
■■ Helpfile − An Optional Parameter. A String expression that identifies the Help
file to use for providing context-sensitive help for the dialog box.
■■ Context − An Optional Parameter. A Numeric expression that identifies the
Help context number assigned by the Help author to the appropriate Help
topic. If context is provided, helpfile must also be provided.
The Buttons parameter can take any of the following values −
■■ 0 vbOKOnly - Displays OK button only.
■■ 1 vbOKCancel - Displays OK and Cancel buttons.
■■ 2 vbAbortRetryIgnore - Displays Abort, Retry, and Ignore buttons.
■■ 3 vbYesNoCancel - Displays Yes, No, and Cancel buttons.
■■ 4 vbYesNo - Displays Yes and No buttons.
■■ 5 vbRetryCancel - Displays Retry and Cancel buttons.
■■ 16 vbCritical - Displays Critical Message icon.
■■ 32 vbQuestion - Displays Warning Query icon.
■■ 48 vbExclamation - Displays Warning Message icon.
■■ 64 vbInformation - Displays Information Message icon.
■■ 0 vbDefaultButton1 - First button is default.
■■ 256 vbDefaultButton2 - Second button is default.
■■ 512 vbDefaultButton3 - Third button is default.
■■ 768 vbDefaultButton4 - Fourth button is default.
■■ 0 vbApplicationModal Application modal - The current application will not
work until the user responds to the message box.
■■ 4096 vbSystemModal System modal - All applications will not work until the
user responds to the message box.
The above values are logically divided into four groups: The first group (0 to 5)
indicates the buttons to be displayed in the message box. The second group (16, 32,
48, 64) describes the style of the icon to be displayed, the third group (0, 256, 512, 768)

3G E-LEARNING
232 Basic Computer Coding: Visual Basic

indicates which button must be the default, and the fourth


group (0, 4096) determines the modality of the message box.

8.6.3 Return Values


The MsgBox function can return one of the following values
which can be used to identify the button the user has clicked
in the message box.
■■ 1 - vbOK - OK was clicked
■■ 2 - vbCancel - Cancel was clicked
■■ 3 - vbAbort - Abort was clicked
■■ 4 - vbRetry - Retry was clicked
■■ 5 - vbIgnore - Ignore was clicked
■■ 6 - vbYes - Yes was clicked
■■ 7 - vbNo - No was clicked

Keyword 8.6.4 Example


A
screenshot, Function MessageBox_Demo()
also known as ‘Message Box with just prompt message
screen capture, or
screen grab, is a MsgBox(“Welcome”)
digital image that
shows the contents
of a computer ‘Message Box with title, yes no and cancel Butttons
display.
int a = MsgBox(“Do you like blue color?”,3,”Choose
options”)
‘ Assume that you press No Button
msgbox (“The Value of a is “ & a)
End Function

Output
Step 1 − The above Function can be executed either by clicking
the “Run” button on VBA Window or by calling the function
from Excel Worksheet as shown in the following screenshot.

3G E-LEARNING
List, Loops and Printing 233

Step 2 − A Simple Message box is displayed with a message “Welcome” and an


“OK” Button

Step 3 − After Clicking OK, yet another dialog box is displayed with a message
along with “yes, no, and cancel” buttons.

Step 4 − After clicking the ‘No’ button, the value of that button (7) is stored as
an integer and displayed as a message box to the user as shown in the following
screenshot. Using this value, it can be understood which button the user has clicked.

3G E-LEARNING
234 Basic Computer Coding: Visual Basic

8.7 USING STRING FUNCTION


A string is nothing but a collection of characters. In very simple terms, String may
be defined as the array of characters. When it comes to an understanding variable,
Integer is the very first thing we learn about. An integer is the data type that stores
the integer value, in the same way, char is the data type that stores single character
and similarly, a string is the data type that allows the storage of the set of characters
in a single variable.
We can also store the string in a char array but the simple way to store any string
is by making the use of string data type. We can perform several functions on the
strings that we will see later. The ability to process string values helps a lot to create
complex applications. Now in the next section, we will learn how to implement string.

8.7.1 Declaration and Initialization of [Link]


To bring string in actual use, we will first need to declare the string. Once it is declared
we can use it numerous of times as required. Below is the syntax to declare a string
in VB .net.
Dim Str as String
■■ Dim: It is the keyword used while declaring any variable.
■■ Str: It is the name of the variable that will hold the string value.
■■ String: It is the keyword that is used to state that the value that Str will hold
should be a string.
Now, once the name of the variable is declared we have to put some value in it
so that it could be used in the program. We can assign the value to the variable either
by taking input from a user in run time or we can assign the value manually. Here
we will see how we can assign the value manually.
Str=“Latin”
Here the value has been assigned to the variable str. While assigning the string
value to the variable we have to make sure that the values have to be written in
double quotes. Once the values are assigned, we can use it anywhere in the program.

8.7.2 Working with [Link] String Functions


In this section, we will see how string could be used with several functions in order
to process the value and generate the desired output. Below are the string functions
that are used to work with String.
Popular Course in this category

3G E-LEARNING
List, Loops and Printing 235

Asc function
This string function in [Link] is used in order to get the integer value of the first
letter of the string. Its integer value is actually the integer value of that character.

Example
Input:
Dim Str as String
Str=“Latin”
Asc(Str)
Output: 76

Format function
This function is used to arrange the string in a particular format. Here we will consider
an example that will change the data representation.

Example
Input:
Dim ChangedTime As Date = #03/23/2019 4:10:43 PM#
Dim ChangedTime as the string
ChangedTime = Format(TestDateTime, “h:m:s”)
Output: 04:10:43 PM

Join function
This [Link] String function is used to join two substrings. Here in this example, we
will create an array of string and then add the value in the array with a comma(,).
Example
Input:
Dim ItemList() As String = {“Apple”, “Banana”, “Guava”}
Dim JoinItemList as string = Join(ItemList, “, “)
Output: Apple, Banana, Guava

3G E-LEARNING
236 Basic Computer Coding: Visual Basic

LCase Function
This function will convert all the characters of the string into a lowercase character. If
the character is already in lowercase that it will ignore the character else will convert
that into lowercase.

Example
Input:
Dim Uppercase as String = “HELLO WORLD”
Dim Lowercase as String = LCase(Uppercase)
Output: hello world

Left function
This function will return the specific characters from left as requested by mentioning
any number. If we will use this function to get the first four characters from the string
from the left end than we have to mention the number 4.

Example
Input:
Dim CheckStr as string = “Hey Jim”
Dim ResultStr as string = Left(CheckStr, 3)
Output: Hey

Len function
This String function in [Link] will return the numbers of characters in a string. The
value returned will be an integer value so it has to be stored in the integer variable.
Example
Input:
Dim StrWords as String = “You are a hero!”
Dim WordCount as Integer = Len(StrWords)
Output: 15

3G E-LEARNING
List, Loops and Printing 237

Right Function
This function will return the specified number of characters
from a string from the right side. The way the Left function
has worked, it will work similarly. The only difference will
be that it will select the characters from the right.

Example
Input:
Dim CheckStr as string = “Hey Jim” Keyword
Dim ResultStr as string = Right(CheckStr, 3) A delimiter
is a
Output: Jim sequence of one or
more characters
for specifying
Split function
the boundary
between separate,
This String function in [Link] is used to split the string.
independent
Though there is various delimiter that could be used with regions in plain
function and here we will just separate it with space. text, mathematical
expressions or
Example
other data streams.
Input:
Dim CheckStr as String = “How are you?”
Dim OutputStr as String = Split(CheckStr)
Output: {“How”, “are”, “you?”}, it is the array of string actually.

StrReverse function
This function will be used to reverse the value of the string.
It sounds the same as swapping the characters to revert the
string. Let’s see an example

Example
Input:
Dim CorrectStr as String = “Apple”
Dim ReverseString as String = StrReverse(CorrectStr)
Output: elppA

3G E-LEARNING
238 Basic Computer Coding: Visual Basic

UCase function
This [Link] String function will turn all the lowercase characters of the string into
uppercase. It works exactly the reverse as the Lcase function does.

Example
Input:
Dim LowercaseStr as String = “Hello Jim”
Dim UppercaseStr as String = UCase(LowercaseStr)
Output:
HELLO JIM
The string is a very useful data type in any programming language. Almost all of
us are unaware that it plays a very vital role in securing the user ID and password.
There are several complex algorithms called hashing algorithms that only manipulates
the string to add an edge in the security of data. To work with String all its need is
to understand the possibility that string functions posses.

8.8 PRINTING TO PRINTER USING PRINT METHOD


Print is a fundamental BASIC statement that dates back to the first days of the language
in the mid-1960s. Print is used to display lines of data on a form, picture box, printer,
and the immediate (Debug) window; it can also be used to write records of data to a
file. In VB, Print is implemented as a method of the following objects:
■■ Form: You can print lines of data directly to the background of a form. This
is done in the examples in the section, although it is not typically done in
regular VB applications. Statements that print to a form begin in any of the
following ways:
[Link] . . .
[Link] . . .
Print . . .
■■ Picture Box: You can print lines of data or graphics to a PictureBox control,
with syntax beginning like the following:
[Link] . . .
■■ Debug object:You can print lines of data to the VB Immediate Window, using
syntax beginning like the following:
[Link] . . .

3G E-LEARNING
List, Loops and Printing 239

■■ Printer:You can print lines of data to the Windows


default printer, using syntax beginning like the
following:

[Link] . . .
To write data to a file, the Print # statement is used, using
syntax beginning like the following:

Print #1, . . .

Printing to files is a common way to write data to a


sequential file; this will be covered in detail in a later section. Did You
Know?
The general format for the Print method is: The
Microsoft .NET
framework
[object.]Print [expressionlist] that powers
Visual Basic
consists of class
where object refers to one of the objects mentioned above libraries called
(Form, PictureBox, Debug window, Printer) and expressionlist namespaces.
refers to a list of one or more numeric or string expressions
to print.

Items in the expression list may be separated with


semicolons (;) or commas (,). A semicolon or comma in the
expression list determines where the next output begins:
; (semicolon) means print immediately after the last value.
, (comma) means print at the start of the next “print zone”.

8.8.1 Printing with the semicolon (;) separator


As noted above, items in the expression list of a Print statement
that are separated by semicolons print immediately after one
another. In the statement

Print “Hello,”; strName; “How are you today?”

3G E-LEARNING
240 Basic Computer Coding: Visual Basic

If strName contained “HARRY”, the Print statement would generate the following
output:
Hello,HARRYHow are you today?

As you can see, there is a slight problem which is easily fixed. But first, make
sure you understand that the Print statement above contains three distinct items in its
expression list: the string constant “Hello,”, the string variable strName (whose contents
will be printed when the Print statement is executed), and the string constant “How
are you today?”. Note that each item was printed immediately one after the other.
The problem is fixed by adding a blank space to the end of the first string constant
(within the quotes) and adding a period and a blank space to the beginning of the
last string constant (within the quotes):

Print “Hello, “; strName; “. How are you today?”

This fixed Print statement would generate better looking output:

Hello, HARRY. How are you today?

Now consider another program segment:

intSum = intFirstNum + intSecondNum


Print “The sum of”; intFirstNum; “and”; intSecondNum; “is”; intSum

Assuming all the variables involved were numeric, and that intFirstNum contained
3 and intSecondNum contained 2, the Print statement would generate:

The sum of 3 and 2 is 5


Note that there are six distinct items in the Print statement’s expression list:
the string constant “The sum of”, the content of the variable intFirstNum, the string
constant “and”, the content of the variable intSecondNum, the string constant “is”,
and the content of the variable intSum.
Note that it was not necessary to place extra spaces in the string constants of the
Print statement this time. That is because, by default, VB always outputs numeric
items with a leading sign and a trailing space. (If the sign of the number is positive,
a blank space will print; if negative, a “-” will print.)

3G E-LEARNING
List, Loops and Printing 241

If a Print statement ends with a semicolon, any item printed by a subsequent


Print statement will be printed on the same line, immediately following the last item
that was printed. In effect, a semicolon at the end of a Print statement suppresses
the carriage return/line feed to the next line.
Examples:

Print Statements Output


Print “Hello”;

Print “There” HelloThere


For intX = 1 To 10

Print intX;

Next 1 2 3 4 5 6 7 8 9 10
For intX = 1 To 10

Print “*”;

Next **********

3G E-LEARNING
242 Basic Computer Coding: Visual Basic

CASE STUDY
VISUAL BASIC 6.0 TO VB .NET TECHNOLOGY MIGRATION

Business Requirements
Application migration projects are undertaken by enterprises in order to gain better
control of business processes, to improve business efficiency, and to increase their
competitive advantage. Organizations typically embark on application migration projects
as part of new application implementation, or to phase out existing legacy applications.
This case study present show ODA proactively assisted a US Insurance company
with global presence, with Visual Basic 6 (VB6) to VB .NET migration. In 2006, ODA
approached the client to discuss the fact that Microsoft was taking away all support
for VB6 by the end of 2008. To mitigate that exposure, the client asked ODA to assess
risk on an application by application basis, make recommendations, and implement
those recommendations.

Scope
The client wanted ODA to do “vanilla” migration of its VB 6.0 applications to VB
.NET. The client wanted its applications to be migrated, but also wanted that the
business logic and the architecture of the applications should remain the same, so
that neither should there be any logical and major behavioral change for the users
of the applications nor should there be any need for providing training to the users.
The client wanted their applications to be converted from VB6 to VB .NET, providing
them with fully functional, ready-to-deploy applications quickly and cost-effectively.
Transforming existing Visual Basic applications to the more efficient and multiplatform
.NET framework not only provides better security but also lets leverage the many
new capabilities of .NET. Moreover, it would help them keep pace with Microsoft as
they had officially announced its plans to withdraw support for VB 6.0. Here is the
information about some important projects and components.

3G E-LEARNING
List, Loops and Printing 243

ODA Approach/Methodology
ODA did a sophisticated analysis to prepare for the migration. This included performing
inventory analysis, determining the degree of impact for each application, and performing
a gap assessment for each application. ODA then proposed a strategic migration
path for the affected applications. The client had hoped that the VB6 code could be
automatically converted to [Link]. Our experience, however, confirmed that most
applications required some manual coding effort. Also, some applications had valid
reasons to go to C# or J2EE environments.

3G E-LEARNING
244 Basic Computer Coding: Visual Basic

ODA’s team was led by a Migration Practice Partner with extensive platform
migration experience. Other resources used for this project were onshore migration
analysts, offshore lead developer and analyst, offshore developers and analysts, offshore
technical writer and tester. A team of two Onshore and eighteen offshore resources had
completed this migration in a period of 12 months. Technology used for the project
included, VB .NET, MS Access 95, .NET MS Framework 2.0, CVS (opensource) and
MS Visual Studio 2005 (IDE).
Each application’s migration path was considered individually. ODA after analysis
came to the conclusion that it would be best to divide the entire migration process
into four projects, which were as follows:
■■ Migration of Calc & Complex suite of applications from Visual Basic 6.0
thick-client to Visual Basic .NET 2005 thick-client. Some major components
of this project were replacing DAO and DAO data bindings with [Link],
converting printing features of the application to .NET etc.
■■ Migration of ETS Security Sub-System and PruServ Lite systems for Pruco
Command from Visual Basic 6.0 thick-client to Visual Basic .NET 2005 thick-
client. Some major components of this project were; Migration of PruServ Lite
- Business tier from Visual Basic 6.0 ActiveX EXE / DLLs to .NET Assemblies
and Migration of PruServ Lite –Presentation tier from ASP to [Link] web
pages.
■■ Migration of PWS Reporting - Data fetch component in SEC Reporting
Application from Visual Basic 6.0 to Java. Migration efforts included rewriting
the ‘Visual Basic 6.0 component’ in Java for fetching results from SQL Server
and populating it in MS Access. This required migrating all the modules/
methods, which were used for these database activities.
■■ ISP is Illustration System for Prudential, it has some agent centric applications
like AMP and Case Navigator, which are used by most of the agents and
third party brokers. Migration of AMP and Case Navigator applications from
Visual Basic 6.0 thick-client to Visual Basic .NET 2005 thick-client was the
scope of this project.

3G E-LEARNING
List, Loops and Printing 245

ODA Value Added


The project produced its own set of challenges from time to time. Firstly, the data
access was not centralized and data access calls were scattered through-out the code.
Secondly, the applications used DAO for data access which is not supported on .NET
platform. DAO and DAO data bindings had to be replaced with [Link] during
migration. Thirdly, applications extensively used Printing features available in VB 6.0,
whereas .NET does not support Printer object. To handle the printing feature, ODA
used Microsoft printing library in projects. Fourthly, a new .NET control PRUMASK
was created to fulfill the requirement of VB mask edit control. All above challenges
had been smartly handle by ODA team.

Moving Ahead
ODA was able to complete the project on time and within budget. The client was
pleased that each application’s migration path was considered individually, with special
attention paid to each application’s environment. Also, there was minimal impact to
the user experience.
Success of this project has paved way for a long-term association between the client
and ODA. As a result of on-time and successful delivery of the project, the client has
awarded ODA with other migration projects.

3G E-LEARNING
246 Basic Computer Coding: Visual Basic

SUMMARY
■■ ListBox and ComboBox controls present a set of choices that are displayed
vertically in a column.
■■ The function of the List Box in visual basic 2017 is to display a list of items.
The user can click and select the items from the list.
■■ In Visual Basic 2017, the function of the Combo Box is also to present a list
of items where the user can click and select the items from the list. However,
the user needs to click on the handle(small arrowhead) on the right of the
combo box to see the items which are presented in a drop-down list.
■■ The ListBox represents a Windows control to display a list of items to a user.
A user can select an item from the list. It allows the programmer to add items
at design time by using the properties window or at the runtime.
■■ Use Clear to explicitly clear the Err object after an error has been handled, for
example, when you use deferred error handling with On Error Resume Next.
■■ There are two Do Loops in Visual Basic: the Do While and Do Until. The Do
While loops something which is true, and the Do Until loops until a certain
condition is met.
■■ The Do While is similar to the Do Until but it evaluates something which is
true.
■■ You use a For...Next structure when you want to repeat a set of statements
a set number of times.
■■ You can nest For loops by putting one loop within another. The following
example demonstrates nested For...Next structures that have different step
values.
■■ The Exit For statement immediately exits the For…Next loop and transfers
control to the statement that follows the Next statement.
■■ When a For...Next loop starts, Visual Basic evaluates start, end, and step.
Visual Basic evaluates these values only at this time and then assigns start
to counter.
■■ The MsgBox function displays a message box and waits for the user to click
a button and then an action is performed based on the button clicked by the
user.
■■ A string is nothing but a collection of characters. In very simple terms, String
may be defined as the array of characters.
■■ To bring string in actual use, we will first need to declare the string. Once it
is declared we can use it numerous of times as required.

3G E-LEARNING
List, Loops and Printing 247

■■ Print is a fundamental BASIC statement that dates back to the first days of
the language in the mid-1960s. Print is used to display lines of data on a
form, picture box, printer, and the immediate (Debug) window; it can also
be used to write records of data to a file.

3G E-LEARNING
248 Basic Computer Coding: Visual Basic

KNOWLEDGE CHECK
1. _________this control is use to display the images
a. image
b. combo
c. shape
d. text
2. To change the control’s Shape using the ______ property
a. image
b. combo
c. shape
d. text
3. The ____box is the standard control for accepting input from the user as well
as to display the output.......
a. image
b. combo
c. shape
d. text
4. text box can handle string (text. and numeric data but not images or pictures
a. True
b. False
c. Both
d. none of these.
5. The ________ is a very useful control for Visual Basic, as it is not only used
to provide instructions and guides to the users, it can also be used to display
outputs.
a. image
b. combo
c. Label
d. text
6. One of its most important properties of lable is ________
a. background
b. caption

3G E-LEARNING
List, Loops and Printing 249

c. Label
d. text
7. One of its most important properties of text box is ______.
a. background
b. caption
c. Label
d. text
8. The _______ is one of the most important controls as it is used to execute
commands.
a. command button
b. radio
c. Label
d. text
9. The most common event associated with the command button is the _____ event,
a. click
b. change
c. double click
d. text
10. The ______ is one of the controls that is used to handle graphics
a. picture box
b. combo
c. Label
d. text

REVIEW QUESTIONS
1. How do you control the horizontal spacing of printer output?
2. Explain how do the Left , Right and len function operate?
3. Discuss how and when the values of the loop index change throughout the process-
ing of the loop.
4. What are the steps in processing a FOR-NEXT Loop?
5. Explain differences between Do/Loop and For-Next Loop.
6. Explain difference between a pretest and a posttest in a Do/Loop.

3G E-LEARNING
250 Basic Computer Coding: Visual Basic

7. In what situation would a loop be used in a procedure?


8. When and how the information is placed inside the listbox or combobox?
9. Explain the purpose of ListCount and ListIndex Property.
10. How can we make scroll bars appear on a listbox or combobox?
11. Describe the three styles of ComboBox.

Check Your Result


1. (a) 2. (c) 3. (d) 4. (a) 5. (c)
6. (b) 7. (d) 8. (a) 9. (a) 10. (a)

3G E-LEARNING
List, Loops and Printing 251

REFERENCES
1. Dollard, Kathleen (November 13, 2018). “Visual Basic in .NET Core 3.0”. blogs.
[Link].
2. Krill, Paul (February 27, 2009). “Microsoft converging programming languages |
Developer World”. InfoWorld. Archived from the original on January 26, 2013.
Retrieved August 18, 2013.
3. Mackenzie, Duncan (2006). “Navigate The .NET Framework And Your Projects
With The My Namespace”. MSDN Magazine Visual Studio 2005 Guided Tour
2006. Microsoft.
4. reshmim. “Visual Studio 2017 Release Notes”. [Link].
5. reshmim. “What’s new for Visual Basic 16.0”. [Link].
6. Roslyn, .NET Foundation, April 13, 2019, retrieved April 14, 2019
7. Sherriff, Lucy (February 22, 2005). “Real Software slams MS IsNot patent
application”. The Register. Retrieved April 6, 2009.
8. Taft, Darryl K. (February 21, 2005). “Real Software Slams Microsofts Patent
Effort”. eWeek. Retrieved April 6, 2009.
9. Vick, Paul A. Jr.; Barsan, Costica Corneliu; Silver, Amanda K. (May 14, 2003).
“United States Patent Application: 20040230959”. Patent Application Full Text
and Image Database. US Patent & Trademark Office. Retrieved April 6, 2009.
10. Whitney, Tyler (November 2005). “[Link]: Examining the Visual Basic My
Feature”. MSDN. Microsoft.

3G E-LEARNING
9
CHAPTER

OBJECT-ORIENTED
PROGRAMMING

“The object-oriented model makes it easy to build up programs by accretion. What this often means,
in practice, is that it provides a structured way to write spaghetti code.”

–Paul Graham

LEARNING
OBJECTIVES
After studying this chapter, you
will be able to:
1. Understand classes and
objects
2. Explain inheritance
3. Describe interfaces
4. Focus on generics
5. Discuss about delegates

INTRODUCTION
Visual Basic provides full support for object-oriented
programming including encapsulation, inheritance, and
polymorphism.
254 Basic Computer Coding: Visual Basic

■■ Encapsulation means that a group of related properties,


methods, and other members are treated as a single
unit or object.
■■ Inheritance describes the ability to create new classes
based on an existing class.
■■ Polymorphism means that you can have multiple classes
that can be used interchangeably, even though each
class implements the same properties or methods in
different ways.

9.1 CLASSES AND OBJECTS


The terms class and object are sometimes used interchangeably,
but in fact, classes describe the type of objects, while objects are
usable instances of classes. So, the act of creating an object is
called instantiation. Using the blueprint analogy, a class is a
blueprint, and an object is a building made from that blueprint.
Keyword
Instantiation is To define a class:
the creation of VBCopy
a real instance
or particular Class SampleClass
realization of an
abstraction or
End Class
template such as a Visual Basic also provides a light version of classes called
class of objects or a structures that are useful when you need to create large array of
computer process.
objects and do not want to consume too much memory for that.
To define a structure:
VBCopy
Structure SampleStructure
End Structure

Class Statement
Declares the name of a class and introduces the definition of
the variables, properties, events, and procedures that the class
comprises.

Syntax
VBCopy

3G E-LEARNING
Object-Oriented Programming 255

[ <attributelist> ] [ accessmodifier ] [ Shadows ] [ MustInherit | NotInheritable ] [


Partial ] _
Class name [ ( Of typelist ) ]
[ Inherits classname ]
[ Implements interfacenames ]
[ statements ]
End Class

Parts

PARTS
Term Definition
attributelist Optional.
accessmodifier Optional. Can be one of the following:

- Public

- Protected

- Friend

- Private

- Protected Friend

- Private Protected

Shadows Optional.
MustInherit Optional.
NotInheritable Optional.
Partial Optional. Indicates a partial definition of the class.
name Required. Name of this class.
Of Optional. Specifies that this is a generic class.
typelist Required if you use the Of keyword. List of type parameters for this
class.
Inherits Optional. Indicates that this class inherits the members of another
class.

3G E-LEARNING
256 Basic Computer Coding: Visual Basic

classname Required if you use the Inherits statement. The name of the class from
which this class derives.
Implements Optional. Indicates that this class implements the members of one or
more interfaces.
interfacenames Required if you use the Implements statement. The names of the
interfaces this class implements.
statements Optional. Statements which define the members of this class.
End Class Required. Terminates the Class definition.

Remarks
A Class statement defines a new data type. A class is a fundamental building block of
object-oriented programming (OOP
You can use Class only at namespace or module level. This means the declaration
context for a class must be a source file, namespace, class, structure, module, or interface,
and cannot be a procedure or block.
Each instance of a class has a lifetime independent of all other instances. This
lifetime begins when it is created by a New Operator clause or by a function such
as CreateObject. It ends when all variables pointing to the instance have been set to
Nothing or to instances of other classes.
Classes default to Friend access. You can adjust their access levels with the access
modifiers.

Rules
■■ Nesting. You can define one class within another. The outer class is called
the containing class, and the inner class is called a nested class.
■■ Inheritance. If the class uses the Inherits Statement, you can specify only one
base class or interface. A class cannot inherit from more than one element.
A class cannot inherit from another class with a more restrictive access level. For
example, a Public class cannot inherit from a Friend class.
A class cannot inherit from a class nested within it.
■■ Implementation. If the class uses the Implements Statement, you must implement
every member defined by every interface you specify in interfacenames. An
exception to this is reimplementation of a base class member.
■■ Default Property. A class can specify at most one property as its default
property.

3G E-LEARNING
Object-Oriented Programming 257

Behavior
■■ Access Level. Within a class, you can declare each
member with its own access level. Class members Keyword
default to Public access, except variables and constants, A default
which default to Private access. When a class has more property is
restricted access than one of its members, the class a class or structure
property that your
access level takes precedence.
code can access
■■ Scope. A class is in scope throughout its containing without specifying
namespace, class, structure, or module. it.

The scope of every class member is the entire class.


Lifetime. Visual Basic does not support static classes. The
functional equivalent of a static class is provided by a module.
Class members have lifetimes depending on how and
where they are declared.
■■ Qualification. Code outside a class must qualify a
member’s name with the name of that class.
If code inside a nested class makes an unqualified reference
to a programming element, Visual Basic searches for the
element first in the nested class, then in its containing class,
and so on out to the outermost containing element.

Classes and Modules


These elements have many similarities, but there are some
important differences as well.
■■ Terminology. Previous versions of Visual Basic
recognize two types of modules: class modules (.cls
files) and standard modules (.bas files). The current
version calls these classes and modules, respectively.
■■ Shared Members. You can control whether a member
of a class is a shared or instance member.
■■ Object Orientation. Classes are object-oriented, but
modules are not. You can create one or more instances
of a class.

Example
The following example uses a Class statement to define a class
and several members.

3G E-LEARNING
258 Basic Computer Coding: Visual Basic

VBCopy
Class BankAccount
Shared interestRate As Decimal
Private accountNumber As String
Private accountBalance As Decimal
Public holdOnAccount As Boolean = False

Public ReadOnly Property Balance() As Decimal


Did You Get
Know? Return accountBalance
Terminology End Get
invoking End Property
“objects” and
“oriented” in the
modern sense of Public Sub PostInterest()
object-oriented
programming accountBalance = accountBalance * (1 + interestRate)
made its first End Sub
appearance at
MIT in the late
1950s and early Public Sub PostDeposit(ByVal amountIn As Decimal)
1960s.
accountBalance = accountBalance + amountIn
End Sub

Public Sub PostWithdrawal(ByVal amountOut As Decimal)


accountBalance = accountBalance - amountOut
End Sub
End Class

Structure Statement
Declares the name of a structure and introduces the definition
of the variables, properties, events, and procedures that the
structure comprises.

Syntax
VBCopy

3G E-LEARNING
Object-Oriented Programming 259

[ <attributelist> ] [ accessmodifier ] [ Shadows ] [ Partial ] _


Structure name [ ( Of typelist ) ]
[ Implements interfacenames ]
[ datamemberdeclarations ]
[ methodmemberdeclarations ]
End Structure

Parts

PARTS
Term Definition
attributelist Optional.
accessmodifier Optional. Can be one of the following:

- Public

- Protected

- Friend

- Private

- Protected Friend

- Private Protected.
Shadows Optional.
Partial Optional. Indicates a partial definition of the structure.
name Required. Name of this structure.
Of Optional. Specifies that this is a generic structure.
typelist Required if you use the Of keyword. List of type
parameters for this structure.
Implements Optional. Indicates that this structure implements the
members of one or more interfaces.
interfacenames Required if you use the Implements statement. The
names of the interfaces this structure implements.
datamemberdeclarations Required. Zero or more Const, Dim, Enum, or Event
statements declaring data members of the structure.

3G E-LEARNING
260 Basic Computer Coding: Visual Basic

methodmemberdeclarations Optional. Zero or more declarations of Function,


Operator, Property, or Sub procedures, which serve as
method members of the structure.
End Structure Required. Terminates the Structure definition.

Remarks
The Structure statement defines a composite value type that you can customize. A
structure is a generalization of the user-defined type (UDT) of previous versions of
Visual Basic.
Structures support many of the same features as classes. For example, structures
can have properties and procedures, they can implement interfaces, and they can
have parameterized constructors. However, there are significant differences between
structures and classes in areas such as inheritance, declarations, and usage. Also, classes
are reference types and structures are value types.
You can use Structure only at namespace or module level. This means the declaration
context for a structure must be a source file, namespace, class, structure, module, or
interface, and cannot be a procedure or block.
Structures default to Friend access. You can adjust their access levels with the
access modifiers.

Rules
■■ Nesting. You can define one structure within another. The outer structure
is called the containing structure, and the inner structure is called a nested
structure. However, you cannot access a nested structure’s members through
the containing structure. Instead, you must declare a variable of the nested
structure’s data type.
■■ Member Declaration. You must declare every member of a structure. A
structure member cannot be Protected or Protected Friend because nothing
can inherit from a structure. The structure itself, however, can be Protected
or Protected Friend.
You can declare zero or more nonshared variables or nonshared, noncustom events
in a structure. You cannot have only constants, properties, and procedures, even if
some of them are nonshared.
■■ Initialization. You cannot initialize the value of any nonshared data member
of a structure as part of its declaration. You must either initialize such a data
member by means of a parameterized constructor on the structure, or assign
a value to the member after you have created an instance of the structure.

3G E-LEARNING
Object-Oriented Programming 261

■■ Inheritance. A structure cannot inherit from any type other than ValueType,
from which all structures inherit. In particular, one structure cannot inherit
from another.
You cannot use the Inherits Statement in a structure definition, even to specify
ValueType.
■■ Implementation. If the structure uses the Implements Statement, you
must implement every member defined by every interface you specify in
interfacenames.
■■ Default Property. A structure can specify at most one property as its default
property, using the Default modifier.

Behavior
■■ Access Level. Within a structure, you can declare each member with its own
access level. All structure members default to Public access. Note that if the
structure itself has a more restricted access level, this automatically restricts
access to its members, even if you adjust their access levels with the access
modifiers.
■■ Scope. A structure is in scope throughout its containing namespace, class,
structure, or module.
The scope of every structure member is the entire structure.
■■ Lifetime. A structure does not itself have a lifetime. Rather, each instance of
that structure has a lifetime independent of all other instances.
The lifetime of an instance begins when it is created by a New Operator clause.
It ends when the lifetime of the variable that holds it ends.
You cannot extend the lifetime of a structure instance. An approximation to static
structure functionality is provided by a module.
Structure members have lifetimes depending on how and where they are declared.
■■ Qualification. Code outside a structure must qualify a member’s name with
the name of that structure.
If code inside a nested structure makes an unqualified reference to a programming
element, Visual Basic searches for the element first in the nested structure, then in its
containing structure, and so on out to the outermost containing element.
■■ Memory Consumption. As with all composite data types, you cannot safely
calculate the total memory consumption of a structure by adding together the
nominal storage allocations of its members. Furthermore, you cannot safely
assume that the order of storage in memory is the same as your order of
declaration. If you need to control the storage layout of a structure, you can
apply the StructLayoutAttribute attribute to the Structure statement.

3G E-LEARNING
262 Basic Computer Coding: Visual Basic

Example
The following example uses the Structure statement to define
a set of related data for an employee. It shows the use of
Keyword Public, Friend, and Private members to reflect the sensitivity
An
of the data items. It also shows procedure, property, and
attribute
is a quality or event members.
characteristic given VBCopy
to a person, group,
or some other Public Structure employee
thing. ‘ Public members, accessible from throughout declaration
region.
Public firstName As String
Public middleName As String
Public lastName As String
‘ Friend members, accessible from anywhere within the
same assembly.
Friend employeeNumber As Integer
Friend workPhone As Long
‘ Private members, accessible only from within the structure
itself.
Private homePhone As Long
Private level As Integer
Private salary As Double
Private bonus As Double
‘ Procedure member, which can access structure’s private
members.
Friend Sub CalculateBonus(ByVal rate As Single)
bonus = salary * CDbl(rate)
End Sub
‘ Property member to return employee’s eligibility.
Friend ReadOnly Property Eligible() As Boolean
Get
Return level >= 25
End Get
End Property

3G E-LEARNING
Object-Oriented Programming 263

‘ Event member, raised when business phone number has changed.


Public Event ChangedWorkPhone(ByVal newPhone As Long)
End Structure

9.1.1 Class members


Each class can have different class members that include properties that describe class
data, methods that define class behavior, and events that provide communication
between different classes and objects.

9.1.2 Properties and Fields


Fields and properties represent information that an object contains. Fields are like
variables because they can be read or set directly.
To define a field:
VBCopy
Class SampleClass
Public SampleField As String
End Class
Properties have get and set procedures, which provide more control on how values
are set or returned.
Visual Basic allows you either to create a private field for storing the property value
or use so-called auto-implemented properties that create this field automatically behind
the scenes and provide the basic logic for the property procedures.
To define an auto-implemented property:
VBCopy
Class SampleClass
Public Property SampleProperty as String
End Class
If you need to perform some additional operations for reading and writing the property
value, define a field for storing the property value and provide the basic logic for
storing and retrieving it:
VBCopy
Class SampleClass
Private m_Sample As String
Public Property Sample() As String

3G E-LEARNING
264 Basic Computer Coding: Visual Basic

Get
‘ Return the value stored in the field.
Return m_Sample
End Get
Set(ByVal Value As String)
‘ Store the value in the field.
m_Sample = Value
End Set
End Property
End Class
Most properties have methods or procedures to both set and get the property value.
However, you can create read-only or write-only properties to restrict them from being
modified or read. In Visual Basic you can use ReadOnly and WriteOnly keywords.
However, auto-implemented properties cannot be read-only or write-only.

9.1.3 Methods
A method is an action that an object can perform.
Note: In Visual Basic, there are two ways to create a method: the Sub statement is
used if the method does not return a value; the Function statement is used if a method
returns a value.
To define a method of a class:
VBCopy
Class SampleClass
Public Function SampleFunc(ByVal SampleParam As String)
‘ Add code here
End Function
End Class
A class can have several implementations, or overloads, of the same method that differ
in the number of parameters or parameter types.
To overload a method:
VBCopy
Overloads Sub Display(ByVal theChar As Char)
‘ Add code that displays Char data.
End Sub

3G E-LEARNING
Object-Oriented Programming 265

Overloads Sub Display(ByVal theInteger As Integer)


‘ Add code that displays Integer data.
End Sub
In most cases you declare a method within a class definition. However, Visual Basic
also supports extension methods that allow you to add methods to an existing class
outside the actual definition of the class.

9.1.4 Constructors
Constructors are class methods that are executed automatically when an object of a
given type is created. Constructors usually initialize the data members of the new
object. A constructor can run only once when a class is created. Furthermore, the
code in the constructor always runs before any other code in a class. However, you
can create multiple constructor overloads in the same way as for any other method.
To define a constructor for a class:
VBCopy
Class SampleClass
Sub New(ByVal s As String)
// Add code here.
End Sub
End Class

9.1.5 Destructors
Destructors are used to destruct instances of classes. In the .NET Framework, the
garbage collector automatically manages the allocation and release of memory for
the managed objects in your application. However, you may still need destructors to
clean up any unmanaged resources that your application creates. There can be only
one destructor for a class.

9.1.6 Events
Events enable a class or object to notify other classes or objects when something of
interest occurs. The class that sends (or raises) the event is called the publisher and
the classes that receive (or handle) the event are called subscribers.
■■ To declare events, use the Event Statement.
■■ To raise events, use the RaiseEvent Statement.

3G E-LEARNING
266 Basic Computer Coding: Visual Basic

■■ To specify event handlers using a declarative way, use the WithEvents statement
and the Handles clause.
■■ To be able to dynamically add, remove, and change the event handler associated
with an event, use the AddHandler Statement and RemoveHandler Statement
together with the AddressOf Operator.

9.1.7 Nested classes


A class defined within another class is called nested. By default, the nested class is
private.
VBCopy
Class Container
Class Nested
‘ Add code here.
End Class
End Class
To create an instance of the nested class, use the name of the container class followed
by the dot and then followed by the name of the nested class:
VBCopy
Dim nestedInstance As [Link] = New [Link]()

9.1.8 Access modifiers and access levels


All classes and class members can specify what access level they provide to other
classes by using access modifiers.
The following access modifiers are available:
ACCESS MODIFIERS AND ACCESS LEVELS
Visual Basic Definition
Modifier
Public The type or member can be accessed by any other code in the same
assembly or another assembly that references it.
Private The type or member can only be accessed by code in the same class.
Protected The type or member can only be accessed by code in the same class or in
a derived class.
Friend The type or member can be accessed by any code in the same assembly,
but not from another assembly.
Protected Friend The type or member can be accessed by any code in the same assembly, or
by any derived class in another assembly.

3G E-LEARNING
Object-Oriented Programming 267

9.1.9 Instantiating classes


To create an object, you need to instantiate a class, or create a class instance.
VBCopy
Dim sampleObject as New SampleClass()
After instantiating a class, you can assign values to the instance’s properties and fields
and invoke class methods.
VBCopy
‘ Set a property value.
[Link] = “Sample String”
‘ Call a method.
[Link]()
To assign values to properties during the class instantiation process, use object initializers:
VBCopy
Dim sampleObject = New SampleClass With
{.FirstProperty = “A”, .SecondProperty = “B”}

9.1.10 Shared Classes and Members


A shared member of the class is a property, procedure, or field that is shared by all
instances of a class.
To define a shared member:
VBCopy
Class SampleClass
Public Shared SampleString As String = “Sample String”
End Class
To access the shared member, use the name of the class without creating an object of
this class:
VBCopy
MsgBox([Link])
Shared modules in Visual Basic have shared members only and cannot be instantiated.
Shared members also cannot access non-shared properties, fields or methods.

3G E-LEARNING
268 Basic Computer Coding: Visual Basic

9.1.11 Anonymous Types


Visual Basic supports anonymous types, which enable you to
create objects without writing a class definition for the data
Keyword
type. Instead, the compiler generates a class for you. The class
Shared
has no usable name, inherits directly from Object, and contains
modules
the properties you specify in declaring the object. Because the
export their
functionality name of the data type is not specified, it is referred to as an
(processes, anonymous type.
shared resources, The following example declares and creates variable
and schema product as an instance of an anonymous type that has two
namespaces) properties, Name and Price.
to application
modules or to VBCopy
other shared ‘ Variable product is an instance of a simple anonymous
modules. type.
Dim product = New With {Key .Name = “paperclips”,
.Price = 1.29}
A query expression uses anonymous types to combine
columns of data selected by a query. You cannot define the
type of the result in advance, because you cannot predict the
columns a particular query might select. Anonymous types
enable you to write a query that selects any number of columns,
in any order. The compiler creates a data type that matches
the specified properties and the specified order.
In the following examples, products is a list of product
objects, each of which has many properties. Variable
namePriceQuery holds the definition of a query that, when it
is executed, returns a collection of instances of an anonymous
type that has two properties, Name and Price.
VBCopy
Dim namePriceQuery = From prod In products
Select [Link], [Link]
Variable nameQuantityQuery holds the definition of a
query that, when it is executed, returns a collection of instances
of an anonymous type that has two properties, Name and
OnHand.
VBCopy
Dim nameQuantityQuery = From prod In products
Select [Link], [Link]

3G E-LEARNING
Object-Oriented Programming 269

Declaring an Anonymous Type


The declaration of an instance of an anonymous type uses an
initializer list to specify the properties of the type. You can
specify only properties when you declare an anonymous type,
not other class elements such as methods or events. In the
following example, product1 is an instance of an anonymous
type that has two properties: Name and Price.
VBCopy
‘ Variable product1 is an instance of a simple anonymous type.
Remember
Dim product1 = New With {.Name = “paperclips”, .Price = 1.29} The
‘ -or- name of
the anonymous
‘ product2 is an instance of an anonymous type with key type is compiler
properties. generated and
Dim product2 = New With {Key .Name = “paperclips”, Key may vary from
compilation to
.Price = 1.29} compilation.
If you designate properties as key properties, you can use Your code should
them to compare two anonymous type instances for equality. not use or rely on
However, the values of key properties cannot be changed. the name of an
anonymous type
Notice that declaring an instance of an anonymous type is because the name
like declaring an instance of a named type by using an object might change
initializer: when a project is
recompiled.
VBCopy
‘ Variable product3 is an instance of a class named Product.
Dim product3 = New Product With {.Name = “paperclips”,
.Price = 1.29}

Key Properties
Key properties differ from non-key properties in several
fundamental ways:
■■ Only the values of key properties are compared in
order to determine whether two instances are equal.
■■ The values of key properties are read-only and cannot
be changed.
■■ Only key property values are included in the compiler-
generated hash code algorithm for an anonymous
type.

3G E-LEARNING
270 Basic Computer Coding: Visual Basic

Equality
Instances of anonymous types can be equal only if they are instances of the same
anonymous type. The compiler treats two instances as instances of the same type if
they meet the following conditions:
■■ They are declared in the same assembly.
■■ Their properties have the same names, the same inferred types, and are
declared in the same order. Name comparisons are not case-sensitive.
■■ The same properties in each are marked as key properties.
■■ At least one property in each declaration is a key property.
An instance of an anonymous types that has no key properties is equal only to
itself.
VBCopy
‘ prod1 and prod2 have no key values.
Dim prod1 = New With {.Name = “paperclips”, .Price = 1.29}
Dim prod2 = New With {.Name = “paperclips”, .Price = 1.29}
‘ The following line displays False, because prod1 and prod2 have no
‘ key properties.
[Link]([Link](prod2))
‘ The following statement displays True because prod1 is equal to itself.
[Link]([Link](prod1))
Two instances of the same anonymous type are equal if the values of their key properties
are equal. The following examples illustrate how equality is tested.
VBCopy
Dim prod3 = New With {Key .Name = “paperclips”, Key .Price = 1.29}
Dim prod4 = New With {Key .Name = “paperclips”, Key .Price = 1.29}
‘ The following line displays True, because prod3 and prod4 are
‘ instances of the same anonymous type, and the values of their
‘ key properties are equal.
[Link]([Link](prod4))

Dim prod5 = New With {Key .Name = “paperclips”, Key .Price = 1.29}
Dim prod6 = New With {Key .Name = “paperclips”, Key .Price = 1.29,
.OnHand = 423}
‘ The following line displays False, because prod5 and prod6 do not

3G E-LEARNING
Object-Oriented Programming 271

‘ have the same properties.


[Link]([Link](prod6))

Dim prod7 = New With {Key .Name = “paperclips”, Key .Price = 1.29,
.OnHand = 24}
Dim prod8 = New With {Key .Name = “paperclips”, Key .Price = 1.29,
.OnHand = 423}
‘ The following line displays True, because prod7 and prod8 are
‘ instances of the same anonymous type, and the values of their
‘ key properties are equal. The equality check does not compare the
‘ values of the non-key field.
[Link]([Link](prod8))

Read-Only Values
The values of key properties cannot be changed. For example, in prod8 in the previous
example, the Name and Price fields are read-only, but OnHand can be changed.
VBCopy
‘ The following statement will not compile, because Name is a key
‘ property and its value cannot be changed.
‘ [Link] = “clamps”

‘ OnHand is not a Key property. Its value can be changed.


[Link] = 22

Anonymous Types from Query Expressions


Query expressions do not always require the creation of anonymous types. When
possible, they use an existing type to hold the column data. This occurs when the
query returns either whole records from the data source, or only one field from
each record. In the following code examples, customers is a collection of objects of a
Customer class. The class has many properties, and you can include one or more of
them in the query result, in any order. In the first two examples, no anonymous types
are required because the queries select elements of named types:
■■ custs1 contains a collection of strings, because [Link] is a string.
VBCopy
Dim custs1 = From cust In customers

3G E-LEARNING
272 Basic Computer Coding: Visual Basic

Select [Link]

■■ custs2 contains a collection of Customer objects, because each element of


customers is a Customer object, and the whole element is selected by the query.
VBCopy

Dim custs2 = From cust In customers


Select cust

However, appropriate named types are not always available. You might want
to select customer names and addresses for one purpose, customer ID numbers and
locations for another, and customer names, addresses, and order histories for a third.
Anonymous types enable you to select any combination of properties, in any order,
without first declaring a new named type to hold the result. Instead, the compiler
creates an anonymous type for each compilation of properties. The following query
selects only the customer’s name and ID number from each Customer object in
customers. Therefore, the compiler creates an anonymous type that contains only
those two properties.
VBCopy
Dim custs3 = From cust In customers
Select [Link], [Link]
Both the names and the data types of the properties in the anonymous type are
taken from the arguments to Select, [Link] and [Link]. The properties in an
anonymous type that is created by a query are always key properties. When custs3 is
executed in the following For Each loop, the result is a collection of instances of an
anonymous type with two key properties, Name and ID.
VBCopy
For Each selectedCust In custs3
[Link]([Link] & “: “ & [Link])
Next
The elements in the collection represented by custs3 are strongly typed, and you can
use IntelliSense to navigate through the available properties and to verify their types.

Deciding Whether to Use Anonymous Types


Before you create an object as an instance of an anonymous class, consider whether
that is the best option. For example, if you want to create a temporary object to contain
related data, and you have no need for other fields and methods that a complete
class might contain, an anonymous type is a good solution. Anonymous types are
also convenient if you want a different selection of properties for each declaration, or

3G E-LEARNING
Object-Oriented Programming 273

if you want to change the order of the properties. However, if your project includes
several objects that have the same properties, in a fixed order, you can declare them
more easily by using a named type with a class constructor. For example, with an
appropriate constructor, it is easier to declare several instances of a Product class than
it is to declare several instances of an anonymous type.
VBCopy
‘ Declaring instances of a named type.
Dim firstProd1 As New Product(“paperclips”, 1.29)
Dim secondProd1 As New Product(“desklamp”, 28.99)
Dim thirdProd1 As New Product(“stapler”, 5.09)

‘ Declaring instances of an anonymous type.


Dim firstProd2 = New With {Key .Name = “paperclips”, Key .Price = 1.29}
Dim secondProd2 = New With {Key .Name = “desklamp”, Key .Price = 28.99}
Dim thirdProd2 = New With {Key .Name = “stapler”, Key .Price = 5.09}
Another advantage of named types is that the compiler can catch an accidental
mistyping of a property name. In the previous examples, firstProd2, secondProd2,
and thirdProd2 are intended to be instances of the same anonymous type. However,
if you were to accidentally declare thirdProd2 in one of the following ways, its type
would be different from that of firstProd2 and secondProd2.
VBCopy
‘ Dim thirdProd2 = New With {Key .Name = “stapler”, Key .Price = 5.09}
‘ Dim thirdProd2 = New With {Key .Name = “stapler”, Key .Price = “5.09”}
‘ Dim thirdProd2 = New With {Key .Name = “stapler”, .Price = 5.09}
More importantly, there are limitations on the use of anonymous types that do not apply
to instances of named types. firstProd2, secondProd2, and thirdProd2 are instances of
the same anonymous type. However, the name for the shared anonymous type is not
available and cannot appear where a type name is expected in your code. For example,
an anonymous type cannot be used to define a method signature, to declare another
variable or field, or in any type declaration. As a result, anonymous types are not
appropriate when you have to share information across methods.

An Anonymous Type Definition


In response to the declaration of an instance of an anonymous type, the compiler creates
a new class definition that contains the specified properties. If the anonymous type
contains at least one key property, the definition overrides three members inherited
from Object: Equals, GetHashCode, and ToString. The code produced for testing equality

3G E-LEARNING
274 Basic Computer Coding: Visual Basic

and determining the hash code value considers only the key
properties. If the anonymous type contains no key properties,
only ToString is overridden. Explicitly named properties of an
anonymous type cannot conflict with these generated methods.
That is, you cannot use .Equals, .GetHashCode, or .ToString
to name a property.
Anonymous type definitions that have at least one key
property also implement the [Link]<T> interface,
where T is the type of the anonymous type.

9.2 INHERITANCE
In visual basic, Inheritance is one of the primary concepts of
object-oriented programming (OOP) and it is useful to inherit
the properties from one class (base) to another (child) class.
The inheritance will enable us to create a new class by
inheriting the properties from other classes to reuse, extend
and modify the behavior of other class members based on
our requirements.
In visual basic inheritance, the class whose members are
inherited is called a base (parent) class and the class that
inherits the members of base (parent) class is called a derived
Keyword
(child) class.
A
programming 9.2.1 Visual Basic Inheritance Syntax
language is a
formal language Following is the syntax of implementing an inheritance to
comprising a set
of strings that define derived class that inherits the properties of base class
produce various in a visual basic programming language.
kinds of machine <access_modifier> Class <base_class_name>
code output.
Programming // Base class Implementation
languages are one
kind of computer
End Class
language, and are
used in computer
programming <access_modifier> Class <derived_class_name>
to implement Inherits base_class_name
algorithms.
// Derived class implementation
End Class
If you observe the above syntax, we are inheriting the properties

3G E-LEARNING
Object-Oriented Programming 275

of base class into child class to improve the code reusability.

Following is the simple example of implementing inheritance in a visual basic


programming language.

Public Class X
Public Sub GetDetails()
‘ Method implementation
End Sub
End Class

Public Class Y
Inherits X
‘ your class implementation
End Class

Class Program
Public Shared Sub Main(ByVal args As String())
Dim y As Y = New Y()
[Link]()
End Sub
End Class
If you observe the above example, we defined a class “X” with a method called
“GetDetails” and the class “Y” is inheriting from the class “X”. After that, we are
calling a “GetDetails” method by using an instance of derived class “Y”.
In visual basic, it’s not possible to inherit the base class constructors in the derived
class and the accessibility of other members of the base class also depends on the
access modifiers which we used to define those members in the base class.

9.2.2 Visual Basic Inheritance Example


Following is the example of implementing an inheritance by defining two classes in
a visual basic programming language.

Public Class User

3G E-LEARNING
276 Basic Computer Coding: Visual Basic

Public Name As String


Private Location As String
Public Sub New()
[Link](“Base Class Constructor”)
End Sub
Public Sub GetUserInfo(ByVal loc As String)
Location = loc
[Link](“Name: {0}”, Name)
[Link](“Location: {0}”, Location)
End Sub
End Class

Public Class Details


Inherits User
Public Age As Integer
Public Sub New()
[Link](“Child Class Constructor”)
End Sub
Public Sub GetAge()
[Link](“Age: {0}”, Age)
End Sub
End Class

Class Program
Public Shared Sub Main(ByVal args As String())
Dim d As Details = New Details()
[Link] = “Suresh Dasari”
‘ Compile Time Error
‘ [Link] = “Hyderabad”;
[Link] = 32
[Link](“Hyderabad”)
[Link]()
[Link](vbLf & “Press Any Key to Exit..”)

3G E-LEARNING
Object-Oriented Programming 277

[Link]()
End Sub
End Class
If you observe the above example, we defined a base class
called “User” and inheriting all the properties of User class
into a derived class called “Details” and we are accessing all
the members of User class with an instance of Details class.

If we uncomment the commented code, we will get a compile-


time error because the Location property in User class is
defined with a private access modifier and the Private members
can be accessed only within the class.

When we execute the above visual basic program, we will get


the result as shown below.

Keyword
Single
inheritance
is one in which
the derived class
If you observe the above result, we are able to access inherits the single
all the properties of base class into child class based on our base class.
requirements.

9.2.3 Visual Basic Multi-Level Inheritance


Generally, visual basic supports only single inheritance that
means a class can only inherit from one base class. However,
in visual basic the inheritance is transitive and it allows you
to define a hierarchical inheritance for a set of types and it
is called a multi-level inheritance.
For example, suppose if class C is derived from class B,
and class B is derived from class A, then class C will inherit
the members declared in both class B and class A.
Public Class A
‘ Implementation

3G E-LEARNING
278 Basic Computer Coding: Visual Basic

End Class

Public Class B
Inherits A
‘ Implementation
End Class

Public Class C
Inherits B
‘ Implementation
End Class
If you observe the above code snippet, class C is derived from class B, and class B is
derived from class A, then class C inherits the members declared in both class B and
class A. This is how we can implement multi-level inheritance in our applications.
Visual Basic Multi-Level Inheritance Example
Following is the example of implementing multi-level inheritance in a visual basic
programming language.

Public Class A
Public Name As String
Public Sub GetName()
[Link](“Name: {0}”, Name)
End Sub
End Class

Public Class B
Inherits A
Public Location As String
Public Sub GetLocation()
[Link](“Location: {0}”, Location)
End Sub
End Class

Public Class C

3G E-LEARNING
Object-Oriented Programming 279

Inherits B
Public Age As Integer
Public Sub GetAge()
[Link](“Age: {0}”, Age)
End Sub
End Class

ClassProgram
Public Shared Sub Main(ByVal args As String())
Dim c As C = New C()
[Link] = “Suresh Dasari”
[Link] = “Hyderabad”
[Link] = 32
[Link]()
[Link]()
[Link]()
[Link](vbLf & “Press Any Key to Exit..”)
[Link]()
End Sub
End Class
If you observe the above example, we implemented three classes (A, B, C) and class
C is derived from class B, and class B is derived from class A.

By implementing multi-level inheritance, class C can inherit the members declared in


both class B and class A.
When we execute the above visual basic program, we will get the result as shown
below.

3G E-LEARNING
280 Basic Computer Coding: Visual Basic

9.2.4 Visual Basic Multiple Inheritance


As discussed, visual basic supports only single inheritance that means a class can only
inherit from one base class. In case, if we try to inherit a class from multiple base
classes, then we will get a compile-time error.
For example, if class C is trying to inherit from Class A and B at the same time,
we will get a compile-time error because multiple inheritance is not allowed in visual
basic.

Public Class A
‘ Implementation
End Class

Public Class B
‘ Implementation
End Class

Public Class C
Inherits A
Implements B
‘ Implementation
End Class
If you observe the above code snippet, class C is trying to inherit properties from
both classes A and B at the same time which will lead to compile-time error like
“Implemented type must be an interface”.

As discussed, multi-level inheritance is supported in visual basic but multiple


inheritance is not supported. In case, if you want to implement multiple inheritance
in visual basic, that we can achieve by using interfaces.

9.2.5 Advantages of Inheritance in [Link]


The feature of inheritance is very beneficial in programming. It actually helps a lot
while writing complex programs as the feature of passing the functionality mitigates
the complex looks of the code. Below are some of its common Advantages
■■ Reduces ambiguity – The code once is written could be used several times.
Hence it eliminates the duplicates and makes the code unambiguous.

3G E-LEARNING
Object-Oriented Programming 281

■■ Reusability – It follows the rule of creating once and use multiple times.
Once any function is defined, we can use that function n number of times
based on our requirement.
■■ Eliminate Coding Complexity – The code has to be written precisely in order
to follow proper documentation and make it easy for other developers to
understand the code. It could be done with the help of Inheritance.
■■ Enhances program efficiency – The program that makes the use of inheritance
are very efficient as there are a few numbers of lines as compared to the same
program which was developed without inheritance.

9.3 INTERFACES
When one refers to an object’s interface, they are referring to how an object is visible
from the outside. We already know that an object contains methods that can be set
as private or public. The object’s interface consists of its public methods, which is the
way we communicate with certain types of objects. The Warrior class we made had
the following public methods:
■■ Sub Attack(enemy As Warrior)
■■ Sub Defend(hit As Integer)
■■ Function Alive() As Boolean
■■ Sub SetMessage(message As String)
■■ Function GetLastMessage() As String
■■ Function HealthBar() As String
If we store a Warrior class instance into a variable, we are able to call the Attack()
or Defend() methods on it. Nothing new, right?
As a matter of fact, we are able to declare an interface separately, sort of like we
do with classes, and we would then be able to use it as a data type.
We’ll give it a go, but on a simpler class than the Warrior class we made. We’ll
start by creating a new project, a console application, naming it InterfaceSample, and
adding a simple class. With that all being said, let’s make a bird class! Our bird will
be able to chirp, breathe and peck. Our Bird class will look something like this:
Public Class Bird

Public Sub Chirp()


[Link](“♫ ♫ ♫”)
End Sub

3G E-LEARNING
282 Basic Computer Coding: Visual Basic

Public Sub Breathe()


[Link](“Breathing...”)
End Sub

Public Sub Peck()


[Link](“Peck, peck!”)
End Sub

End Class
Done! Now, let’s move to [Link] and create a bird instance:
Dim bird As Bird = New Bird()
Once you’ve created an instance of the bird class, write whatever you called the
instance, in this case, it is “bird”, and add a dot right after it. Visual Studio will then
display all of its class methods (you can also invoke IntelliSense by pressing Ctrl +
Space):

We now see everything that we can call on the bird instance. The 3 methods we just
now implemented are there as well as some others that all objects have from its base.
Now let’s create an interface for our bird. We’ll use the Interface keyword to do just
that. In [Link], it’s a good practice to prefix the Interface with “I” (as in Interface).
Right-click on the project, and choose Add new item -> Interface.

3G E-LEARNING
Object-Oriented Programming 283

An empty interface will be added to our project. We’ll add the headers of methods
which this interface will require. The implementation itself, method content, is added
later by the class that implements the interface.
Let’s add method headers to the IBird interface, we’ll purposely omit one of them
and only add chirping and breathing:
Public Interface IBird
Sub Chirp()
Sub Breathe()
End Interface
We don’t specify the Public modifier since an interface contains public methods
only. It wouldn’t make sense otherwise since it specifies how to work with an object
from the outside.
Let’s go back to [Link] and change the line with the bird variable so it won’t
be longer of the Bird type, but of the IBird type:
Dim bird As IBird = New Bird()
What the code above means is that in the bird variable, we expect an object that
contains the methods specified in the IBird interface. Visual Studio reports an error
since the Bird class doesn’t implement the IBird interface yet. Although it does have
the needed methods, it must first be informed that it implements this interface. Let’s
move to the Bird class and let it implement the IBird interface. We do it in the same
way as when we want a class to inherit from another, we just use the Implements
keyword for that:
Public Class Bird
Implements IBird
...

3G E-LEARNING
284 Basic Computer Coding: Visual Basic

We also have to specify which methods from the class implements which method
from the interface(s). We use the Implements keyword for it as well, this time after
the methods definitions. The Bird class will now look like this:
Public Class Bird
Implements IBird

Public Sub Chirp() Implements [Link]


[Link](“♫ ♫ ♫”)
End Sub

Public Sub Breathe() Implements [Link]


[Link](“Breathing...”)
End Sub

Public Sub Peck()


[Link](“Peck, peck!”)
End Sub

End Class
When we go back to [Link], the line with the variable of the IBird type no
longer causes an error. The Bird class correctly implements the IBird interface. Meaning
that Bird instances can now be stored in variables of this type.
Now just for completeness’ sake, let’s see what happens when we remove a
method from the class, which is required by the interface, like the Chirp() method.
Visual Studio will warn us that the implementation is not complete. Once you have
visual confirmation of the interface’s dependency on the class, put the method back
where it belongs.
Let’s write bird with a dot after it. Again, Visual Studio will offer the following
methods:

3G E-LEARNING
Object-Oriented Programming 285

We can see that now we can call only the methods provided by the interface on
the instance. That’s because the bird is now a variable of the IBird type, not the Bird
type. Meaning that we cannot call the Peck() method because we did not add it to
the interface.
Why did we leave it out in the first place, you may ask? Lots of potential reasons,
we’ve already encountered one of them. By using an interface, we simplify a complex
object and expose only the parts needed in a certain part of the program.
Also, must add that interfaces cannot be instantiated. In other words, this code
will not work:
‘ this code won’t work
Dim bird As IBird = New IBird()

9.3.1 Multiple inheritance


Visual Basic .NET, like most programming languages, doesn’t support multiple
inheritance. Meaning that we can’t inherit one class from more than one other class.
Mainly, because method naming collisions could very well occur when multiple classes
containing methods with the same name inherit their methods into another class.
Multiple inheritance is often worked around using interfaces because we are allowed
to implement as many interfaces in a class as we want. A class of the sort only allows
us to work with its instances in ways that we want to. We wouldn’t have to worry
about of what object type it actually is, or what it provides beyond the interfaces.
Now let’s add an ILizard interface to our project. Lizards will be able to breathe
and crawl:
Public Interface ILizard
Sub Crawl()
Sub Breathe()
End Interface
Next, we’ll try “multiple inheritance”, more accurately, implement multiple interfaces
by a single class. We’ll add a [Link] class to the project. It will implement
IBird and ILizard interfaces:
Public Class Pterodactyl
Implements ILizard, IBird

End Class
If we hover the mouse above each interface, i.e. click on ILizard or IBird, there
is a “light-bulb” shortcut to Implement the Interface in the context menu. It may also

3G E-LEARNING
286 Basic Computer Coding: Visual Basic

happen automatically when you write an interface name to implement. Visual Studio
will then automatically generate the necessary class methods.

After having both interfaces implemented, the code will look like this. Notice that
there are 2 Breathe() methods since the method is required both by IBird and ILizard:
Public Class Pterodactyl
Implements ILizard, IBird

Public Sub Breathe() Implements [Link]


Throw New NotImplementedException()
End Sub

Public Sub Chirp() Implements [Link]


Throw New NotImplementedException()
End Sub

Public Sub Crawl() Implements [Link]


Throw New NotImplementedException()
End Sub

Private Sub IBird_Breathe() Implements [Link]


Throw New NotImplementedException()

3G E-LEARNING
Object-Oriented Programming 287

End Sub

End Class
Since the breathing will be always the same, let’s remove the IBird_Breathe() method
and add [Link] after the Implements keyword of the first Breathe() method.
Now all we have to do is specify what we want each method to do:
Public Sub Breathe() Implements [Link], [Link]
[Link](“I’m breathing...”)
End Sub

Public Sub Crawl() Implements [Link]


[Link](“I’m crawling...”)
End Sub

public Sub Chirp() Implements [Link]


[Link](“♫ ♫♫ ♫ ♫ ♫♫”)
End Sub
That’s pretty much it! Now, let’s add an instance of the Pterodactyl class in
[Link]:
Dim pterodactyl As Pterodactyl = New Pterodactyl()
Make sure, that it has both the bird and lizard methods:

3G E-LEARNING
288 Basic Computer Coding: Visual Basic

9.4 GENERICS
In visual basic, generic is a type and it is useful to define a
class, structure, interface or method with placeholders (type
parameters) to indicate that they can store or use one or
more of the types. In visual basic, the compiler will replace
placeholders with the specified type at compile-time.
Remember In visual basic, mostly we will use generics with collections
Your and the methods that operate on them to specify a type of
computer objects to be stored in a collection. The generics are introduced
might show
in .NET Framework 2.0 with a new namespace called System.
different names
or locations [Link].
for some of the In visual basic, generics are useful to improve the code
Visual Studio reusability, type safety, and performance when compared with
user interface
elements in the non-generic types such as arraylist.
the following
instructions. The 9.4.1 Visual Basic Generics Declaration
Visual Studio
edition that you
have and the To define a class or method as generic, we need to use the
settings that you type parameter as a placeholder within the brackets.
use determine Following is the example of defining a generic class with
these elements.
type parameter (T) as a placeholder within the brackets.

Public Class GenericClass(Of T)


Public msg As T
Public Sub genericMethod(ByVal name As T, ByVal location
As T)
[Link](“{0}”, msg)
[Link](“Name: {0}”, name)
[Link](“Location: {0}”, location)
End Sub
End Class
If you observe the above class, we created a class (GenericClass)
with one parameter (msg) and method (genericMethod) using
type parameter (T) as a placeholder with brackets.

Here, (Of type) will indicate GenericClass is generic and type


parameter (T) is used to accept a requested type. The type

3G E-LEARNING
Object-Oriented Programming 289

parameter name can be anything like X or U or etc. based on our requirements.


Generally, while creating an instance of the class we need to specify an actual type,
then the compiler will replace all the type parameters such as T or U or X, etc. with
the specified actual type. In visual basic, the following is the example of creating an
instance of a generic class.

‘ Instantiate Generic Class, string is the type argument


Dim gclass As GenericClass(Of String) = New GenericClass(Of String)()
[Link] = “Welcome to Tutlane”
[Link](“Suresh Dasari”, “Hyderabad”)
If you observe the above code, we are sending the type as “String”. So, the compiler
will substitute all the type parameters (T) with the defined type “String” and our class
(GenericClass) will be like as shown below.

Public Class GenericClass


Public msg As String
Public Sub genericMethod(ByVal name As String, ByVal location As String)
[Link](“{0}”, msg)
[Link](“Name: {0}”, name)
[Link](“Location: {0}”, location)
End Sub
End Class
In visual basic, we can also create our own custom generic types and methods to
provide our own generalized solutions that are type-safe and efficient.

9.4.2 Visual Basic Generic Class Example


Following is the example of creating a generic class using type parameter (T) with
brackets (Of type) in a visual basic programming language.

Module Module1
Public Class GenericClass(Of T)
Public msg As T
Public Sub genericMethod(ByVal name As T, ByVal location As T)
[Link](“{0}”, msg)

3G E-LEARNING
290 Basic Computer Coding: Visual Basic

[Link](“Name: {0}”, name)


[Link](“Location: {0}”, location)
End Sub
End Class
Sub Main(ByVal args As String())
[Link](“****Generics Example****”)
‘ Instantiate Generic Class, string is the type argument
Dim gclass As GenericClass(Of String) = New GenericClass(Of String)()
[Link] = “Welcome to Tutlane”
[Link](“Suresh Dasari”, “Hyderabad”)
[Link]()
End Sub
End Module
When we execute the above visual basic program, we will get the result like as shown
below.

This is how we can use the generics in visual basic to create generic classes or
methods based on our requirements.

9.4.3 Visual Basic Generic Class as Base / Derived Class


In visual basic, we can use the generic class as a base class, but we need to provide
a type instead of type parameter for the base class because there is no way to send a
required type argument to instantiate a base class at run time.
Following is the example of using a generic class as a base class in a visual basic
programming language.

‘ No Error
Class DClass1
Inherits GenericClass(Of String)

3G E-LEARNING
Object-Oriented Programming 291

‘ Implementation
End Class
‘ Compile-time Error
‘Class DClass2
‘ Inherits GenericClass(Of T)
‘ Implementation
‘End Class
In case, if derived class is generic, then we don’t need to specify a type for generic
base class instead we can use type parameter (T).
Following is the example of defining a generic derived class in a visual basic programming
language.

‘ No Error
Class DClass1
Inherits GenericClass(Of String)
‘ Implementation
End Class
‘ No Error
Class DClass2(Of T)
Inherits GenericClass(Of T)
‘ Implementation
End Class
Visual Basic Generic Methods
In visual basic, if we define a method with type parameter, it is called a generic
method. Following is the example of defining a generic method with type parameter
using brackets (Of type).

Public Sub genericMethod(Of T)(ByVal a As T, ByVal b As T)

‘ Implementation

End Sub
This generic method can be called either by specifying the type of argument or without
an argument like as shown below.

3G E-LEARNING
292 Basic Computer Coding: Visual Basic

genericMethod(Of Integer)(1, 2)

Visual Basic Generic Method Example


In visual basic, we can call a generic method bypassing any type of arguments. Following
is the example of defining a generic method in visual basic programming language.

Module Module1
Public Class SampleClass
Public Sub GMethod(Of T)(ByVal a As T, ByVal b As T)
[Link](“Param1: {0}”, a)
[Link](“Param2: {0}”, b)
End Sub
End Class
Sub Main(ByVal args As String())
[Link](“****Generics Method Example****”)
Dim s As SampleClass = New SampleClass()
[Link](Of Integer)(1, 2)
[Link](“Suresh Dasari”, “Hyderabad”)
[Link]()
End Sub
End Module
If you observe the above code, we are calling our generic method (GMethod) with
or without type parameter and sending different types of arguments based on our
requirements.
When we execute the above visual basic program, we will get the result like as shown
below.

This is how we can define generic methods in a visual basic programming language
based on our requirements.

3G E-LEARNING
Object-Oriented Programming 293

9.4.4 Visual Basic Generic Delegates


In visual basic, the generic delegate is same as a normal delegate but the only difference
is the generic delegate will have a generic type with brackets (Of type).

Following is the example of defining a generic delegate in visual basic programming


language.

Module Module1
‘ Declare Generic Delegate
Public Delegate Function SampleDelegate(Of T)(ByVal a As T, ByVal b As T) As T
Class MathOperations
Public Function Add(ByVal a As Integer, ByVal b As Integer) As Integer
Return a + b
End Function
Public Function Subtract(ByVal x As Integer, ByVal y As Integer) As Integer
Return x - y
End Function
End Class
Sub Main(ByVal args As String())
[Link](“****Generic Delegate Example****”)
Dim m As MathOperations = New MathOperations()
‘ Instantiate delegate with add method
Dim dlgt As SampleDelegate(Of Integer) = New SampleDelegate(Of Integer)
(AddressOf [Link])
[Link](“Addition Result: “ & dlgt(10, 90))
‘ Instantiate delegate with subtract method
dlgt = AddressOf [Link]
[Link](“Subtraction Result: “ & dlgt(10, 90))
[Link]()
End Sub
End Module
If you observe the above code, we defined delegate (SampleDelegate) with generic
type parameter (T) using brackets (Of type) and accessing it by creating an instance
of delegate with the required argument (int).

3G E-LEARNING
294 Basic Computer Coding: Visual Basic

When we execute the above visual basic program, we will get a result like as
shown below.

This is how we can use the generics with delegates based on our requirements in
a visual basic programming language.

9.5 DELEGATES
Delegates are objects that refer to methods. They are sometimes described as type-safe
function pointers because they are similar to function pointers used in other programming
languages. But unlike function pointers, Visual Basic delegates are a reference type based
on the class [Link]. Delegates can reference both shared methods — methods
that can be called without a specific instance of a class — and instance methods.

9.5.1 Delegates and Events


Delegates are useful in situations where you need an intermediary between a calling
procedure and the procedure being called. For example, you might want an object that
raises events to be able to call different event handlers under different circumstances.
Unfortunately, the object raising the events cannot know ahead of time which event
handler is handling a specific event. Visual Basic lets you dynamically associate event
handlers with events by creating a delegate for you when you use the AddHandler
statement. At run time, the delegate forwards calls to the appropriate event handler.
Although you can create your own delegates, in most cases Visual Basic creates
the delegate and takes care of the details for you. For example, an Event statement
implicitly defines a delegate class named <EventName>EventHandler as a nested class
of the class containing the Event statement, and with the same signature as the event.
The AddressOf statement implicitly creates an instance of a delegate that refers to a
specific procedure. The following two lines of code are equivalent. In the first line, you
see the explicit creation of an instance of EventHandler, with a reference to method
Button1_Click sent as the argument. The second line is a more convenient way to do
the same thing.
VBCopy
AddHandler [Link], New EventHandler(AddressOf Button1_Click)
‘ The following line of code is shorthand for the previous line.
AddHandler [Link], AddressOf Me.Button1_Click

3G E-LEARNING
Object-Oriented Programming 295

You can use the shorthand way of creating delegates anywhere the compiler can
determine the delegate’s type by the context.

9.5.2 Declaring Events that Use an Existing Delegate Type


In some situations, you may want to declare an event to use an existing delegate type
as its underlying delegate. The following syntax demonstrates how:
VBCopy
Delegate Sub DelegateType()
Event AnEvent As DelegateType
This is useful when you want to route multiple events to the same handler.

9.5.3 Delegate Variables and Parameters


You can use delegates for other, non-event related tasks, such as free threading or with
procedures that need to call different versions of functions at run time.
For example, suppose you have a classified-ad application that includes a list box with
the names of cars. The ads are sorted by title, which is normally the make of the car.
A problem you may face occurs when some cars include the year of the car before
the make. The problem is that the built-in sort functionality of the list box sorts only
by character codes; it places all the ads starting with dates first, followed by the ads
starting with the make. To fix this, you can create a sort procedure in a class that uses
the standard alphabetic sort on most list boxes, but is able to switch at run time to
the custom sort procedure for car ads. To do this, you pass the custom sort procedure
to the sort class at run time, using delegates.

9.5.4 AddressOf and Lambda Expressions


Each delegate class defines a constructor that is passed the specification of an object
method. An argument to a delegate constructor must be a reference to a method, or
a lambda expression.
To specify a reference to a method, use the following syntax:
AddressOf [expression.]methodName
The compile-time type of the expression must be the name of a class or an interface
that contains a method of the specified name whose signature matches the signature
of the delegate class. The methodName can be either a shared method or an instance
method. The methodName is not optional, even if you create a delegate for the default
method of the class. To specify a lambda expression, use the following syntax:
Function ([parm As type, parm2 As type2, ...]) expression

3G E-LEARNING
296 Basic Computer Coding: Visual Basic

The following example shows both AddressOf and lambda expressions used to specify
the reference for a delegate.
VBCopy
Module Module1

Sub Main()
‘ Create an instance of InOrderClass and assign values to the properties.
‘ InOrderClass method ShowInOrder displays the numbers in ascending
‘ or descending order, depending on the comparison method you specify.
Dim inOrder As New InOrderClass
inOrder.Num1 = 5
inOrder.Num2 = 4

‘ Use AddressOf to send a reference to the comparison function you want


‘ to use.
[Link](AddressOf GreaterThan)
[Link](AddressOf LessThan)

‘ Use lambda expressions to do the same thing.


[Link](Function(m, n) m > n)
[Link](Function(m, n) m < n)
End Sub

Function GreaterThan(ByVal num1 As Integer, ByVal num2 As Integer) As Boolean


Return num1 > num2
End Function

Function LessThan(ByVal num1 As Integer, ByVal num2 As Integer) As Boolean


Return num1 < num2
End Function

Class InOrderClass
‘ Define the delegate function for the comparisons.

3G E-LEARNING
Object-Oriented Programming 297

Delegate Function CompareNumbers(ByVal num1 As


Integer, ByVal num2 As Integer) As Boolean
‘ Display properties in ascending or descending order.
Sub ShowInOrder(ByVal compare As CompareNumbers)
If compare(_num1, _num2) Then
[Link](_num1 & “ “ & _num2)
Else
[Link](_num2 & “ “ & _num1)
End If
End Sub

Private _num1 As Integer


Property Num1() As Integer
Get
Return _num1 Remember
End Get Event
handlers
Set(ByVal value As Integer) are nothing
_num1 = value more than
methods that are
End Set invoked through
delegates.
End Property

Private _num2 As Integer


Property Num2() As Integer
Get
Return _num2
End Get
Set(ByVal value As Integer)
_num2 = value
End Set
End Property
End Class
End Module
The signature of the function must match that of the delegate
type.

3G E-LEARNING
298 Basic Computer Coding: Visual Basic

ROLE MODEL
ALAN KAY

Alan Curtis Kay is an American computer scientist best known


for his pioneering work on object-oriented programming
and windowing graphical user interface design. While at
the ARPA project at the University of Utah in the late 1960s,
he invented dynamic object-oriented programming. Working
at Xerox PARC, his credo was, “the best way to predict the
future is to invent it.” One of his visionary concepts was the
Dynabook, a powerful and portable electronic device—the
size of a three-ring notebook with a touch-sensitive liquid
crystal screen and a keyboard for entering information.
Laptops, notebook computers, and tablets have roots in the
early concepts of the Dynabook. People needed a method for
interacting with the new computer medium. To help with this,
Kay and the members of his lab created graphical interfaces
and the Smalltalk programming language. He is considered
by some as the “father of personal computers” because he
envisioned a small computing system in the 1970’s, long before
notebook computers were available He is the founder-president
of Viewpoints Research Institute, a non-profit organization
dedicated to children and the One Laptop Per Child initiative.
An important contributor to the Squeak project, he is part of
the ongoing research called Etoys System.

Childhood & Early Life


Alan Curtis Kay was born in Springfield, Massachusetts. His
father designed arm and leg prostheses, and his mother was
a musician. He had read about 150 books before he started
school.
He attended the University of Colorado at Boulder, earning
a Bachelor’s degree in Mathematics and Molecular Biology.
Before and during this time, he worked as a professional
jazz guitarist.
In 1966, he joined graduate school at the University of
Utah College of Engineering, earning Master’s degree and

3G E-LEARNING
Object-Oriented Programming 299

a Ph.D. There, he worked with Ivan Sutherland, a pioneer in graphics programs


including Sketchpad.

Career
In 1968, Kay met Seymour Papert and learned of the Logo programming language,
a dialect of Lisp. He created Logo as a tool to improve the way children think and
solve the problems.
He studied the works of Jean Piaget, Jerome Bruner, Lev Vygotsky, and constructionist
learning that believed individual learners construct mental models to understand the
world around them.
In 1970, he joined Xerox Corporation’s Palo Alto Research Center, PARC. and was
one of the key members there to develop prototypes of networked workstations using
the programming language Smalltalk used for constructive learning
He pioneered the idea of object-oriented programming (OOP) along with some
colleagues at PARC and predecessors at the Norwegian Computing Center. C++,
Objective-C, Smalltalk, Java, C#, Perl, Python, Ruby and PHP are examples of OOP.
Closely related to his Dynabook concept, he was actively involved in the One
Laptop per Child project which aims at creating affordable educational devices for
use in the developing world.
In 1984, he became an Apple Fellow at Apple Computer’s ATG (Advanced Technology
Group), which researched in both hardware and software, and focused on such areas as
Human-Computer Interaction, Educational Technology, and Language/action perspective.
Between 1996 and 2001, he was with Walt Disney Imagineering as a Disney Fellow.
The Disney Fellow program intended to attract individual contributors of technology
applicable to creative arts, media and entertainment.
In 2001, he started the Viewpoints Research Institute (VPRI), a nonprofit organization
to improve “powerful ideas education” for the world’s children and to advance the
state of systems research and personal computing.
Kay worked with a team at Applied Minds, a company founded in 2000 by ex-
Disney Imagineers, that provides technology, design, R&D, and consulting services to
multiple firms. The company’s headquarters are in Glendale, California.
He became a Senior Fellow at Hewlett-Packard until HP disbanded the Advanced
Software Research Team in 2005, a move that was criticized outside HP and created
distrust within the company.
In 2005, at the World Summit on the Information Society, the MIT research
laboratories unveiled a new laptop computer-the $100 Laptop, the Children’s Machine,
and the XO-1 -based on his Dynabook concept.

3G E-LEARNING
300 Basic Computer Coding: Visual Basic

In 2006, his proposal titled, ‘STEPS Toward the Reinvention of Programming:


A compact and Practical Model of Personal Computing, as a Self-exploratorium, to
the United States National Science Foundation (NSF) was accepted and funds were
sanctioned.
In 2011, he taught ‘Powerful Ideas: Useful Tools to Understand the World’, at NYU’s
Interactive Telecommunications Program to devise new forms of teaching/learning
based on fundamental, powerful concepts, rather than on traditional rote learning.

Major Works
Kay conceived the Dynabook concept by 1972 which laid the foundation for laptop
and tablet computers and E-books. Thus, he is the architect of the modern overlapping
windowing graphical user interface (GUI) and mobile learning.
Kay is an important contributor to the Squeak project and is part of the ongoing
research called Etoys System, a Squeak based educational programming which is child
friendly for use in education.

Awards & Achievements


In 2003, Kay was presented the ACM Turing Award for pioneering many of the ideas
basic to contemporary object-oriented programming languages, leading the team that
developed Smalltalk, and for fundamental contributions to personal computing.
He was the recipient of the Kyoto Prize similar in intent to the Nobel Prize, in 2004
and also shared the Charles Stark Draper Prize for Alto, the first practical networked
computer.

Personal Life & Legacy


Alan Kay married Bonnie Lynn MacBird in 1983. She is an actress, playwright,
screenwriter and producer known for co-writing the science fiction film ‘Tron’ and
has two Emmys for production to her credit.

3G E-LEARNING
Object-Oriented Programming 301

SUMMARY
■■ The terms class and object are sometimes used interchangeably, but in fact,
classes describe the type of objects, while objects are usable instances of classes.
■■ Visual Basic also provides a light version of classes called structures that are
useful when you need to create large array of objects and do not want to
consume too much memory for that.
■■ Each class can have different class members that include properties that describe
class data, methods that define class behavior, and events that provide
communication between different classes and objects.
■■ Fields and properties represent information that an object contains. Fields are
like variables because they can be read or set directly.
■■ A method is an action that an object can perform.
■■ Constructors are class methods that are executed automatically when an object
of a given type is created.
■■ Destructors are used to destruct instances of classes. In the .NET Framework,
the garbage collector automatically manages the allocation and release of
memory for the managed objects in your application.
■■ Events enable a class or object to notify other classes or objects when something
of interest occurs.
■■ A class defined within another class is called nested. By default, the nested
class is private.
■■ All classes and class members can specify what access level they provide to
other classes by using access modifiers.
■■ To create an object, you need to instantiate a class, or create a class instance.
■■ In visual basic, Inheritance is one of the primary concepts of object-oriented
programming (OOP) and it is useful to inherit the properties from one class
(base) to another (child) class.
■■ When one refers to an object’s interface, they are referring to how an object
is visible from the outside.
■■ In visual basic, generic is a type and it is useful to define a class, structure,
interface or method with placeholders (type parameters) to indicate that they
can store or use one or more of the types. In visual basic, the compiler will
replace placeholders with the specified type at compile-time.
■■ Delegates are objects that refer to methods. They are sometimes described as
type-safe function pointers because they are similar to function pointers used
in other programming languages.

3G E-LEARNING
302 Basic Computer Coding: Visual Basic

KNOWLEDGE CHECK
1. __________________ is a programming language that allows the programmer to
use objects to accomplish his goals.
a. Structured programming language
b. Object-oriented programming language
c. Top-down programming language
d. Bottom-up programming language
2. Each object used in a object oriented programming is created from _____________
a. Class
b. Object
c. Instance
d. User
3. An object is the _____________ of the class.
a. Instance
b. Class
c. Object
d. User
4. A ______________ variable is the instance of the String class.
a. Button
b. String
c. Character
d. Array
5. ________________ are the characteristics that describe the object.
a. Classes
b. Attributes
c. Objects
d. Instances

3G E-LEARNING
Object-Oriented Programming 303

6. _______________ are operations that the object is capable of performing.


a. Methods
b. Events
c. Instances
d. Attributes

7. ______________ are the actions to which an object can respond.


a. Methods
b. Events
c. Instances
d. Attributes
8. An object’s _______________ include methods and events.
a. Attribute
b. Behavior
c. Instance
d. Method
9. A class ______________ all the behavior and attributes of an object.
a. Encapsulates
b. Abstracts
c. Inherits
d. Instantiate
10. Objects are ____________ from a class.
a. Instantiated
b. Evaluated
c. Printed
d. Outdated

REVIEW QUESTIONS
1. What is object-oriented programming in Visual Basic?
2. Why [Link] is an object oriented programming language?
3. Is it Visual Basic net fully object-oriented programming?
4. What is inheritance and explain its types?

3G E-LEARNING
304 Basic Computer Coding: Visual Basic

5. What is polymorphism vb net?


6. What are the various interfacing elements of Visual Basic?
7. What is generic procedure?
8. What is the purpose of delegate statement in VB net?
9. How do you define delegates?

Check Your Result


1. (b) 2. (a) 3. (a) 4. (b) 5. (b)
6. (a) 7. (b) 8. (b) 9. (a) 10. (a)

3G E-LEARNING
Object-Oriented Programming 305

REFERENCES
1. Cheesman, John and John Daniels. UML Components: A Simple Process for
Specifying Component-Based Software. Addison-Wesley, 2001.
2. Gestwicki, Paul, Bharat Jayaraman, Interactive Visualization of Java Programs. In
IEEE Symposium on Human-Centric Computing, Languages, and Environments,
Arlington, VA/USA, September 2002.
3. Lange, Sebastian, et al. .NET Framework Security. Addison-Wesley, 2002.
4. Lau, Yun-Tung, Ph.D. The Art of Objects: Object-Oriented Design and Architecture.
Addison-Wesley, 2001.
5. Meyer, Bertrand. Object-Oriented Software Construction, Second Edition. Upper
Saddle River: Prentice Hall PTR. 2000.
6. Rammer, Ingo. Advanced .NET Remoting. APress, 2002.
7. Weisfeld, Matt, and Bill McCarty. The Object-Oriented Thought Process.
Indianapolis: Sams Publishing. 2000.

3G E-LEARNING
Index

A D
access modifiers 256, 260, 261, 266, 275, 301 database 169, 171, 172, 174, 175, 176, 178,
[Link] object model 169, 170, 190 179, 184, 185, 186, 187, 188, 189, 190
assignment statement 63 Database system 3, 21
DataColumn 173, 174, 182, 183, 190
B
data provider 171, 172, 190, 192
Binary data 30 Data reader 171
Boolean Data Type 29 DataRow 173, 174, 182, 183, 190
Boolean expression 67, 82 dataset 171, 172, 173, 182, 190, 192
DataSet class 173
C data source 169, 171, 172, 173, 175, 177, 184,
Case statements 65, 71 185, 190, 192
Char data type 32 data store 171
class 254, 255, 256, 257, 260, 261, 263, 264, DataTable 173, 174, 182, 183, 190
265, 266, 267, 268, 269, 271, 272, 273, 274, Data type 28, 29, 30, 32, 33, 35, 38, 43, 47,
275, 277, 278, 279, 280, 281, 282, 283, 284, 48, 49, 53, 55
285, 286, 287, 288, 289, 290, 291, 294, 295, Debugging 113, 114, 115, 116, 117, 118, 120,
301, 302, 303 121, 133, 136
class members 263, 266, 274, 301 Debug menu 119, 120, 121
Class Statement 61 Debug toolbar 118, 133
ComboBox 197, 201, 202, 203, 204, 246, 250 Debug window 122, 123, 133
command 171 Decimal data type 33
Common language runtime 26, 28 Decision making structures 64, 82
Constructors 265, 301 declaration statements 60, 61, 82, 85
Const Statement 61 Declare Statement 62
308 Basic Computer Coding: Visual Basic

Delegates 293, 294, 301 I


Delegate Statement 63
If statement 65, 67, 68, 70, 82
Destructors 265, 301
If-Then-Else statements 70, 82
Dim Statement 61
if-then statement 65
disconnected architecture 172
Inheritance 254, 256, 261, 274, 275, 277, 278,
Do Loops 219, 222, 246
280, 281, 301
Do Until 218, 219, 220, 221, 222, 246
Insertable Objects 77
Do While 219, 220, 221, 246
instances 254, 256, 257, 261, 265, 267, 268,
Drop-down 91
269, 270, 271, 272, 273, 284, 285, 301
Dynamic array 156, 157, 158, 167
instantiation 254, 267
E interface 256, 260, 261, 274, 280, 281, 282,
283, 284, 285, 288, 295, 298, 300, 301
Else statement 65, 67, 68, 82
Interface Statement 62
EntityClient provider 172
intrinsic controls 76, 85
Entity Data Model (EDM) 172
Enum Statement 61 L
Err object 217, 218, 219, 246
ListBox 197, 198, 209, 211, 212, 246
Event procedure 144, 163
Logic errors 114, 115
Events 265, 294, 295, 301, 302, 303
Event Statement 63 M
executable statement 63, 82
Exit For statement 225, 226, 246 Memory consumption 28, 53
extension methods 265 Menu Editor 94, 95, 109
method 260, 264, 265, 267, 273, 275, 283,
F 284, 285, 286, 287, 288, 291, 292, 293, 294,
295, 296, 298, 301
Fields 263, 301
Microsoft Access 175
Floating-point data type 35
Microsoft Access Database 175
For loops 224, 228, 246
Microsoft application 7, 21
For...Next loop 224, 226, 227, 246
Microsoft SQL Server 172, 175
For...Next structure 223, 246
Module Statement 62
Function procedure 145
MsgBox function 195, 230, 232, 246
Function Statement 62
multi-level inheritance 277, 278, 279, 280
G Multiple Document Interface (MDI) 89, 97,
109
General procedure 144, 163
generic 255, 259, 288, 289, 290, 291, 292, O
293, 301, 303
object 253, 254, 256, 257, 258, 263, 264, 265,
Global variable 37
267, 268, 269, 272, 274, 281, 283, 285, 294,
Graphical user interface GUI 2

3G E-LEARNING
Index 309

295, 298, 299, 300, 301, 302, 303 SQL Query 186
object-oriented programming (OOP) 274, Statements 59, 60, 61, 63, 70, 82
299, 301 Static array 156
One-dimensional array 153, 163 Static variable 39, 40, 41, 42
On Error Resume Next 218, 246 string 203, 212, 218, 224, 234, 235, 236, 237,
Operator Statement 63 238, 239, 240, 246, 248
overloads 264, 265 structures 254, 260, 261, 301
Structure Statement 61
P
subscribers 265
Print 196, 238, 239, 240, 241, 247 Sub Statement 62
Private statement 37 Syntax errors 114
Procedure-level variable 37, 39
V
Procedure parameter 141, 163
programming elements 60 VBdatabase 174
Property procedure 148, 149, 150, 163 Visual Basic 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 14,
Property Statement 63 17, 19, 21, 26, 27, 29, 30, 32, 33, 35, 36, 37, 38,
39, 42, 43, 44, 46, 49, 50, 53, 60, 74, 76, 77, 82,
R
83, 88, 94, 109, 140, 141, 143, 145, 148, 152,
Resume keyword 129 159, 161, 163, 164, 175, 186
retrieve data 171 Visual Basic application 186
retrieving data 171, 173, 190 Visual Basic control 74
Ruby Programming Language 3 Visual Basic Objects 74, 82
Run-time errors 114 Visual Studio Code 38

S W
Select Case statement 65, 71, 82 Windows Application project 174
Server Explorer 174
Single Document Interface (SDI) 89, 97, 109

3G E-LEARNING

You might also like