Sanet - St-Basic Computer Coding - Visual Basic 2e
Sanet - St-Basic Computer Coding - Visual Basic 2e
VISUAL BASIC
2nd Edition
[Link]
BASIC COMPUTER CODING: VISUAL BASIC
2ND EDITION
[Link]
email: info@[Link]
Notice: Registered trademark of products or corporate names are used only for
explanation and identification without intent of infringement.
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.
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.
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
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
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
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
3G E-LEARNING
ROLE MODEL
Introduction to Visual Basic 19 50 Basic Computer Coding: Visual Basic
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.
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
REVIEW QUESTIONS
a. True
b. False
4. Visual Basic responds to events using which of the following? 3G E-LEARNING
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.
3G E-LEARNING
vi
3G E-LEARNING
TABLE OF
CONTENTS
Preface xiii
viii
3.4.3 Insertable Objects 77
Summary 82
Knowledge Check 84
Review Questions 85
References 86
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
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.
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
3G E-LEARNING
Introduction to Visual Basic 3
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.
3G E-LEARNING
Introduction to Visual Basic 5
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
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.
3G E-LEARNING
8 Basic Computer Coding: Visual Basic
3G E-LEARNING
Introduction to Visual Basic 9
Example 1
Private Sub Form_Load ( )
[Link]
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
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
3G E-LEARNING
12 Basic Computer Coding: Visual Basic
3G E-LEARNING
Introduction to Visual Basic 13
Figure 7:
3G E-LEARNING
14 Basic Computer Coding: Visual Basic
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
3G E-LEARNING
18 Basic Computer Coding: Visual Basic
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
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.
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.
3G E-LEARNING
Data Types, Constants And Variables 27
3G E-LEARNING
28 Basic Computer Coding: Visual Basic
†
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.
3G E-LEARNING
Data Types, Constants And Variables 29
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
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)
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
3G E-LEARNING
34 Basic Computer Coding: Visual Basic
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.
3G E-LEARNING
Data Types, Constants And Variables 35
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)
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
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
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.
3G E-LEARNING
40 Basic Computer Coding: Visual Basic
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
Need a super private variable just for one method? Consider declaring it as Static:
the VB Static variable. Happy coding!
3G E-LEARNING
Data Types, Constants And Variables 43
3G E-LEARNING
44 Basic Computer Coding: Visual Basic
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.
3G E-LEARNING
46 Basic Computer Coding: Visual Basic
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.
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
3G E-LEARNING
Data Types, Constants And Variables 49
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
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?
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
–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
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
Large
Medium
Small
End Enum
4 Class Statement Class Box
End Class
5 Structure Statement Structure Box
3G E-LEARNING
62 Basic Computer Coding: Visual Basic
End Sub
End Module
7 Interface Statement Public Interface MyInterface
End Function
9 Sub Statement Sub mySub(ByVal s As String)
3G E-LEARNING
Control Statements and Tools 63
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()
Example
The following example demonstrates a decision making
statement −
Module decisions
Sub Main()
3G E-LEARNING
64 Basic Computer Coding: Visual Basic
3G E-LEARNING
Control Statements and Tools 65
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).
3G E-LEARNING
66 Basic Computer Coding: Visual Basic
Flow Diagram
Example
Module decisions
Sub Main()
‘local variable definition
Dim a As Integer = 10
3G E-LEARNING
Control Statements and Tools 67
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
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
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
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
The MessageBox control has a method named Show, which is called in the code
snippet below −
Handles [Link]
[Link](“Hello, World”)
End Sub
End Class
3G E-LEARNING
76 Basic Computer Coding: Visual Basic
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.
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.
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
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
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.
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
“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
3G E-LEARNING
Menu Bar and Dialog Boxes 89
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
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
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
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.
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.
3G E-LEARNING
100 Basic Computer Coding: Visual Basic
End Module
This would produce:
3G E-LEARNING
Menu Bar and Dialog Boxes 101
3G E-LEARNING
102 Basic Computer Coding: Visual Basic
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.
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.
3G E-LEARNING
106 Basic Computer Coding: Visual Basic
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
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.
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.
3G E-LEARNING
Executing the Debugging 115
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
3G E-LEARNING
Executing the Debugging 117
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.
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
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.
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
3G E-LEARNING
Executing the Debugging 121
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
3G E-LEARNING
124 Basic Computer Coding: Visual Basic
Return 0
End Function
Module Exercise
[Link](“Enter a number: “)
Number = [Link]()
Twice = Number * 2
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
[Link](“Enter a number: “)
Number = [Link]()
Twice = Number * 2
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
Module Exercise
[Link](“Enter a number: “)
Number = [Link]()
Twice = Number * 2
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
[Link](“Enter a number: “)
Number = [Link]()
Twice = Number * 2
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:
3G E-LEARNING
128 Basic Computer Coding: Visual Basic
[Link](“Enter a number: “)
Number = [Link]()
Twice = Number * 2
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:
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
[Link](“Enter a number: “)
Number = [Link]()
Resume
3G E-LEARNING
130 Basic Computer Coding: Visual Basic
Twice = Number * 2
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
[Link](“Enter a number: “)
Number = [Link]()
Resume
Twice = Number * 2
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
[Link](“Enter a number: “)
Number = [Link]()
Twice = Number * 2
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:
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?
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.
3G E-LEARNING
Procedures and Arrays 141
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
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)]
3G E-LEARNING
Procedures and Arrays 143
Sub Assign()
Dim strFullName As String
strFullName = “Paul Bertrand Yamaguchi”
MsgBox(strFullName)
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
3G E-LEARNING
144 Basic Computer Coding: Visual Basic
End Module
End Sub
3G E-LEARNING
Procedures and Arrays 145
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
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
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
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)
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)
3G E-LEARNING
152 Basic Computer Coding: Visual Basic
3G E-LEARNING
Procedures and Arrays 153
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
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
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
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)
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()
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
strCDRack(0) = “Deftones”
strCDRack(1) = “Tool”
strCDRack(2) = “Disturbed”
3G E-LEARNING
Procedures and Arrays 159
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”
3G E-LEARNING
Procedures and Arrays 161
3G E-LEARNING
162 Basic Computer Coding: Visual Basic
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
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
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?
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
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.
3G E-LEARNING
172 Basic Computer Coding: Visual Basic
4 DataAdapter
3G E-LEARNING
Data Access 173
The DataSet class is present in the [Link] namespace. The following table
describes all the components of DataSet −
3G E-LEARNING
174 Basic Computer Coding: Visual Basic
8 PrimaryKey
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.
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.
3G E-LEARNING
Data Access 177
3G E-LEARNING
178 Basic Computer Coding: Visual Basic
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
3G E-LEARNING
Data Access 181
3G E-LEARNING
182 Basic Computer Coding: Visual Basic
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
3G E-LEARNING
Data Access 183
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 −
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
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.
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
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.
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.
3G E-LEARNING
List, Loops and Printing 197
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
[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
3G E-LEARNING
List, Loops and Printing 201
Gets a value indicating whether the list enables selection of list items.
2 AutoCompleteCustomSource
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 or sets the height in pixels of the drop-down portion of the ComboBox.
9 DropDownStyle
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
3G E-LEARNING
202 Basic Computer Coding: Visual Basic
13 ItemHeight
Gets an object representing the collection of the items contained in this ComboBox.
15 MaxDropDownItems
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 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
3G E-LEARNING
List, Loops and Printing 203
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
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.
3G E-LEARNING
204 Basic Computer Coding: Visual Basic
4 SelectedIndexChanged
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
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.
3G E-LEARNING
List, Loops and Printing 207
End If
End Sub
3G E-LEARNING
208 Basic Computer Coding: Visual Basic
End Sub
‘displaying the selected item on the label
3G E-LEARNING
List, Loops and Printing 209
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.
3G E-LEARNING
210 Basic Computer Coding: Visual Basic
2 BorderStyle
3G E-LEARNING
List, Loops and Printing 211
14 SelectedValue
• None
• One
• MultiSimple
• MultiExtended
16 Sorted
Prevents the control from drawing until the EndUpdate method is called, while
items are added to the ListBox one at a time.
2 ClearSelected
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
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
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 −
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
3G E-LEARNING
List, Loops and Printing 217
End Sub
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
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
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
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
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.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.
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.
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
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.
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
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}
[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
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 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
Public Shared Operator <=(ByVal op1 As Distance, ByVal op2 As Distance) As Boolean
Return ([Link] <= [Link])
End Operator
End Class
‘ Output: 10 14 18 22
End Sub
8.6.1 Syntax
MsgBox(prompt[,buttons][,title][,helpfile,context])
3G E-LEARNING
List, Loops and Printing 231
3G E-LEARNING
232 Basic Computer Coding: Visual Basic
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 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
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.
3G E-LEARNING
List, Loops and Printing 239
[Link] . . .
To write data to a file, the Print # statement is used, using
syntax beginning like the following:
Print #1, . . .
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):
Assuming all the variables involved were numeric, and that intFirstNum contained
3 and intSecondNum contained 2, the Print statement would generate:
3G E-LEARNING
List, Loops and Printing 241
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
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
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
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
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.
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
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
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
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
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
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.
3G E-LEARNING
Object-Oriented Programming 267
3G E-LEARNING
268 Basic Computer Coding: Visual Basic
3G E-LEARNING
Object-Oriented Programming 269
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
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”
3G E-LEARNING
272 Basic Computer Coding: Visual Basic
Select [Link]
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.
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)
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
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.
3G E-LEARNING
276 Basic Computer Coding: Visual Basic
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.
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.
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.
3G E-LEARNING
280 Basic Computer Coding: 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”.
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
3G E-LEARNING
282 Basic Computer Coding: Visual Basic
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
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()
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
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
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.
3G E-LEARNING
Object-Oriented Programming 289
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
This is how we can use the generics in visual basic to create generic classes or
methods based on our requirements.
‘ 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).
‘ 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)
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
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.
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.
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
Class InOrderClass
‘ Define the delegate function for the comparisons.
3G E-LEARNING
Object-Oriented Programming 297
3G E-LEARNING
298 Basic Computer Coding: Visual Basic
ROLE MODEL
ALAN KAY
3G E-LEARNING
Object-Oriented Programming 299
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
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.
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
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
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
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