Date post: | 16-Jan-2016 |
Category: |
Documents |
Upload: | dwight-underwood |
View: | 222 times |
Download: | 1 times |
Vis
Vis
ual
ual
Bas
Bas
icic201
201
00
CH
APTER
1
Intro
du
ction
to
Visu
al Basic
2010
A b
rief d
es
crip
tion
of V
isu
al B
as
ic 2
01
0
Ge
tting
to k
no
w th
e V
isu
al B
as
ic 2
01
0
Inte
gra
ted
De
ve
lop
me
nt E
nv
iron
me
nt
Prepared by: B.B.ARMINTIA
ObjectivesObjectivesTo learn the functions of the Visual Basic 2010.To learn how to program in visual basic 2010.At the end of the session students can differentiate Visual Basic to other programming languages such as java etc.
A
A
Brie
f B
rief
De
sc
riD
es
cri
ptio
n
ptio
n
of
of
Vis
ua
l V
isu
al
Ba
sic
B
as
ic
20
10
20
10
Visual B
asic 2
010 is th
e latest versio
n of
Visual B
asic lau
nched by M
icrosoft in
2010
. It
is a
lmost
similar
to
Visu
al
Ba
sic 200
8 but it ha
s add
ed m
any
new
featu
res. V
isual B
asic has g
one
throug
h m
any
pha
ses
of
deve
lopm
ent
since th
e d
ays of
BA
SIC
tha
t w
as bu
ilt fo
r D
OS
.
BA
SIC
sta
nds
for
Beg
inne
rs' A
ll-
purpo
se S
ymb
olic Instruction
Cod
e.
Th
e p
rogram
co
de in
Visua
l B
asic
resembles
the
En
glish lang
uage
.
Diffe
rent
softw
are
com
pan
ies
had
produ
ced m
any d
ifferent versio
ns of
BA
SIC
for DO
S, such as M
icroso
ft
QB
AS
IC, Q
UIC
KB
AS
IC, G
WB
AS
IC,
and IB
M B
AS
ICA
and
mo
re. Th
en,
Microsoft lau
nched th
e first grap
hical
BA
SIC
, V
isual
Basic
Ve
rsion
1 in
1991
. It is GU
I based
and e
specially
deve
lope
d fo
r M
S
win
dow.
Sin
ce
then M
icrosoft slowly p
hase
d out th
e
DO
S
versions
of B
AS
IC
and
comple
tely replaced the
m b
y Visua
l
Ba
sic.
Con
Con
t.t.
Visu
al
Ba
sic w
as in
itially
a
functio
nal
or p
roce
dura
l p
rogra
mm
ing
la
ngu
age
u
ntil th
e p
opu
lar
Visu
al
Ba
sic 6
. T
he
n,
Microso
ft tra
nsformed
V
isua
l B
asic
into a m
ore
pow
erful ob
ject
orie
nted
pro
gra
mm
ing
lan
gua
ge
b
y la
unchin
g V
isua
l , Visu
al B
asic 200
5,
Visu
al B
asic 2
008
and
the
late
st V
isua
l B
asic
20
10.
Visu
al B
asic 2
010
is a fu
ll-fle
dge
d
Ob
ject-O
rien
ted
Pro
gram
ming
(O
OP
) L
ang
uag
e; it h
as cau
ght up
w
ith oth
er O
OP
lang
uag
es
such a
s C+
+, Ja
va, C#
and
o
the
rs. H
ow
eve
r, yo
u d
o n
ot have
to kn
ow O
OP
to lea
rn
VB
20
1 0
. In
fa
ct, if
you are fam
iliar with
Visua
l B
asic
6,
you
can
lea
rn
VB
201
effortle
ssly be
cau
se
the
syntax
and
in
terfa
ce
are a
lmo
st similar.
Navi
Navi
gatin
gatin
g th
e g
the
Visu
Visu
al al B
asiB
asic c 2010 2010 In
tegIn
tegrated
rated
D
eveD
evelo
pm
lop
men
t en
t E
nvir
En
viro
nm
on
men
ten
t
Wh
en you
la
un
ch
V
isu
al B
asic 2
01
0 E
xp
ress, you
can
see
th
e start p
ag
e o
f th
e In
te
gra
ted
D
eve
lo
pm
en
t E
nviro
nm
en
t:
Co
Co
nt.
nt.
Th
e IDE
con
sists of a few
pan
es, n
amely:
Th
e Re
cen
t Pro
jects
Pa
ne- it sho
ws th
e list of
proje
cts tha
t you h
ave
create
d rece
ntly.
Th
e Ge
t Sta
rted P
ane
- It
provide
s som
e he
lpful tips
so that yo
u ca
n qu
ickly
deve
lop
your n
ew
app
licatio
n.
Th
e Late
st Ne
ws p
ane
- It
provide
s latest o
nlin
e
new
s abo
ut V
isual B
asic
201
0 E
xpre
ss. It will
ann
ou
nce n
ew
release
s
and
upd
ate
s.
Be
sides th
at, it a
lso sh
ows
two
icons, N
ew
Pro
ject
and
Op
en P
roje
ct
Th
e T
he
Ne
Ne
w
w
Pro
Pro
ject ject D
ialD
ialo
go
g
When you click on the New
Pro
ject icon, the V
isual Basic 2010 New
Project dialog will appear, as shown:
Co
Co
nt.
nt.
The
d
ialog
box
offers
you
five
types o
f proje
cts that yo
u can
create
. T
hey
are W
indow
s
Form
A
pplication
, W
PF
App
licatio
n, C
onso
le
App
licatio
n, C
lass L
ibrary
and
W
PF
B
rowse
r
App
licatio
n. As w
e are
goin
g
to
create
a
stan
dard
Wind
ow
s applica
tion, w
e w
ill
sele
ct W
indow
s F
orm
s
App
licatio
n. At th
e bo
ttom
of
this
dialo
g b
ox, you
can
cha
nge
the
defa
ult p
roject
nam
e Win
do
ws
Ap
plic
ation
1
to som
e othe
r nam
e yo
u like,
for
exa
mple
,
MyF
irstA
pp
licatio
n.
Afte
r
you
ha
ve
ren
amed
th
e
project,
click O
K
to
go
into
the D
esig
ner interface.
Th
e T
he
Des
Des
ign
ign
er er
Inte
Inte
rfacrfac
ee
The V
B201 0 ID
E D
esigner interface is
shown
below.
The
Designer
consists of
the M
enu
b
ar, the
Too
lbars,
an em
pty F
orm
, the
So
lutio
n
Exp
lorer
and the
Pro
perties W
ind
ow
.
The
VB
2010 D
esigner environm
ent that appears on your P
C or laptop m
ight not be
the sam
e here,
depending how
you
customize
it. Y
ou can
customize your interface by
dragging the
window
s and
dock them or let them
float. Y
ou can also hide them. To
dock a window
, you drag its title
bar and
drag it
to the
side, top
or bottom
of
the w
orkspace or
another w
indow. Y
ou can also resize the
docked w
indow
by dragging
the side
of the
window
. To free up and float the docked w
indow, you just
drag its title bar and move it
away
from
the edge
of the
workspace. If you do not see
a particular window
such as the
properties w
indow,
you can click on the V
iew m
enu and
click the
name
of the
window
, that
particular w
indow w
ill appear
Co
Co
nt.
nt.
VB2010 IDE with A New Form:
Co
Co
nt.
nt.
Fo
rm-T
he F
orm
is the
first pla
ce to b
uild
your a
pplica
tion
. It is the
pla
ce to design the user interface.
So
lutio
n
Ex
plo
rer
-Th
e solu
tion
exp
lorer d
ispla
ys a list of proje
cts, file
s and
other components that you
can easily
browse
and access.
For
example, it displays M
y Project and
Form
1.vb.
Pro
pertie
s
Win
do
w-
Th
is is
the
p
lace to
set the
prop
ertie
s of th
e
obje
cts in
yo
ur application.
The
objects include the default form and
the controls you place in the form. W
e w
ill learn
more
about setting
properties later.
Un
dU
nd
ersterstan
di
and
in
g
ng
th
e th
e C
on
Co
ncep
t cep
t o
f o
f O
bje
Ob
ject ct O
rieO
rien
ted
nted
P
roP
rog
rag
ram
mi
mm
in
gn
g
The
main
difference betw
een V
B201
0
and Visual B
asic 6 is that is it is a full
Object O
riented Program
ming Language
while V
B6 m
ay have OO
P capabilities, it
is not
fully object
oriented. In
order to
qualify as
a fully
object oriented
programm
ing language,
it m
ust have
three core
technologies nam
ely
encap
sulatio
n,
inh
eritance
and
po
lymo
rph
ism.
Read
more
about the
three terms in the box below
:
En
capsu
lation
refers to the creation of
self-contained modules that bind
processing functions to the data. These
user-defined data types are called
classes. Each class contains data as w
ell
as a set of methods, w
hich manipulate
the data. The data com
ponents of a class
are called instance variables and one
instance of a class is an object. For
example, in a library system
, a class
could be mem
ber, and John and Sharon
could be two instances (tw
o objects) of
the library class.
Co
Co
nt.
nt.
Inh
eritance
Classes are created according to hierarchies,
and inheritance allows the structure and
methods in one class to be passed dow
n the
hierarchy. That m
eans less programm
ing is
required when adding functions to com
plex
systems. If a step is added at the bottom
of a
hierarchy, then only the processing and data
associated with that unique step needs to be
added. Everything else about that step is
inherited. The ability to reuse existing objects
is a major advantage of object technology.
Po
lymo
rph
ismO
bject-oriented programm
ing allows
procedures about objects to be created w
hose exact type is not known until
runtime. F
or example, a screen cursor
may change its shape from
an arrow to
a line depending on the program m
ode. T
he routine to move the cursor on
screen in response to mouse
movem
ent would be w
ritten for "cursor," and polym
orphism allow
s that cursor to take on w
hatever shape is required at run tim
e. It also allows new
shapes to be integrated easily.
Co
Co
nt.
nt.
VB
201
0
is a
fu
lly O
bje
ct O
riente
d
Pro
gram
ming
La
ng
uag
e, ju
st like
oth
er O
OP
such a
s C+
+ a
nd Java
. It is diffe
rent from
the
earlier ve
rsions of V
B b
eca
use
it focuse
s more
on th
e data
itself while the
previou
s versio
ns
focus m
ore on
the actio
ns. P
reviou
s versio
ns of
VB
are p
roce
du
ral o
r fun
ction
al prog
ram
min
g
lang
uag
e. S
om
e o
ther p
roce
dura
l pro
gram
min
g
lang
uag
es a
re C, P
ascal and
Fo
rtran.
VB
201
0 allo
ws u
sers to w
rite prog
ram
s tha
t
brea
k dow
n in
to mod
ule
s. Th
ese
mo
du
les re
prese
nt the re
al-wo
rld
obje
cts; we
also call th
em
classe
s or
type
s. An o
bject ca
n be
crea
ted ou
t of a
class , it is a
n in
stan
ce of the
class. A
class ca
n also com
prise subcla
ss. For
exa
mp
le, app
le tree is a
subclass o
f the
pla
nt cla
ss and
the ap
ple in you
r
backya
rd is a
n in
stan
ce of the
app
le tree
class.
Co
Co
nt.
nt.
An
oth
er e
xam
ple
is stud
en
t class is a
sub
class o
f the
po
pu
latio
n cla
ss wh
ile a
stud
en
t with
the
na
me
Joh
n is
an
insta
nce
of th
e stu
de
nt cla
ss. A cla
ss con
sists of d
ata
me
mb
ers a
s we
ll as m
eth
od
s. In V
B2
01
0, th
e p
rog
ram
structu
re to
de
fine
a p
op
ula
tion
class ca
n b
e w
ritten
as
follo
ws:
Pu
blic C
lass Po
pu
lation
'Data M
emb
ers
Private N
ame A
s Strin
g
Private B
irthd
ate As S
tring
Private G
end
er As S
tring
Private A
ge A
s Inte
ger
'Meth
od
s
Overrid
able S
ub
Sh
ow
Info
( )
Messa
geBo
x.Sh
ow
(Nam
e)
Messa
geBo
x.Sh
ow
(Birth
date)
Messa
geBo
x.Sh
ow
(Gen
der)
Messa
geBo
x.Sh
ow
(Age)
En
d S
ub
En
d C
lass
Co
Co
nt.
nt.
After
you have
created the
population class, you can create a subclass that inherits the
attributes or data from
the population class. For
example, you can create a student
class that
is a
subclass of
the
population class. Under the
student class,
you do
not
have to
define any
data
fields that
were
already
defined under
the
population class;
you only
have to
define the
data
fields that are different from
an instance
of the
population class.
For
example, you m
ay want to
include S
tudentID
and
Address
in the
student
class. The program
code for
the S
tudentClass
is as
follows:
Co
Co
nt.
nt.
Pu
blic Cla
ss Stu
dent
Inherits P
opulation
Pu
blic Stud
entID
as Strin
g Pu
blic Ad
dress A
s Strin
g
Ove
rrides S
ub S
how
Info( ) M
essageB
ox.Sho
w(N
ame)
Messa
geBox.S
how
(Stud
entID
)
Messa
geBox.S
how
(Birth
date) M
essageB
ox.Sho
w(G
end
er)
Messa
geBox.S
how
(Age) M
essageB
ox.Sho
w(A
ddress)
En
d Su
b
Su
Su
mmma
ma
ryry
you learned about the evolution
of V
isual B
asic.
you have learned how
to launch
the start
page, the
new
project dialog and the designer interface.
You
have also
learned that
the designer
interface consists
of the
Form
, the
Solution
Explorer
and the
Properties
window
.
You have also learned
some basic concepts of
object oriented
programm
ing, w
hich com
prises encapsulation, polym
orphism
and inheritance.
Vis
Vis
ual
ual
Bas
Bas
icic20
12
01
00
Ch
ap
ter 2
Desig
nin
g
the
Inte
rface
Learning to Design the
Interface Adding controls
Setting C
ontrol Properties
Ad
Ad
din
din
g
g
Co
Co
ntr
ntr
ols
ols
to
to
the
the
Fo
rF
or
mm
The
first step
in creating
a new
V
B2010
project is
to design
the interface
of the
application. Y
ou design
an interface
by
adding controls to the form and then set their
properties. You can add controls from
the
Toolbox. To
see the
Toolbox w
indow,
you
can use
the short-cut
keys C
trl+A
lt+X
or
click on the Toolbox icon on the toolbar on
top of
the designer
environment.
The
Toolbox consists
of m
any useful
controls
such as Button, TextB
ox, Label, Com
boBox,
CheckB
ox and more.
Co
Co
nt.
nt.
Th
e Visu
al B
asic 2
010
Co
ntrol
Toolbo
x consists o
f all th
e con
trols e
ssen
tial fo
r d
evelo
pin
g a V
ISU
AL
BA
SIC
20
10 a
pplica
tion.
Co
ntro
ls in VB
201
0 a
re
use
ful tools tha
t can
p
erform
variou
s tasks. We
catego
rized
into C
om
mo
n C
on
trols, C
onta
iners,
Me
nu
s, Toolba
rs, Da
ta, C
om
po
nen
ts, Prin
ting
s and
D
ialo
gs. N
ow
, we
will fo
cus o
n the com
mo
n co
ntrols.
So
me
of th
e m
ost use
d com
mo
n co
ntrols are
Bu
tton, L
abe
l, Co
mb
oB
ox, L
istBox, P
icture
Box,
TextBox an
d m
ore. To a
dd
a co
ntrol to
the
form
, just
drag
the pa
rticular con
trol
and
drop
it into
the fo
rm.
Afte
r puttin
g it in
to the form
, you
can
chan
ge
its size
and
positio
n easily. Y
ou can
a
dd a
s ma
ny con
trols as
you w
ant, bu
t avoid
crow
ding th
e form.
Sett
Sett
ing
in
g
the
the
Co
nC
on
trol
trol
Pro
Pro
pert
pert
ies ies U
siU
sin
g
ng
P
roP
rop
ertp
erties ies W
inW
ind
ow
do
w
To customize the interface to the users,
you need to set the properties of
the controls, from the form
itself to
the controls you add to the form.
You can set the properties of the
controls in the properties window
at
design time or by using the code.
We shall learn how
to set the
control properties using the
properties window
first.
To set the properties of an object, right
click on the object and choose properties
in the dialog that appears to view the
properties window
. In the properties
window
, you can change the values of the
properties that appear in a dropdown list,
as shown below
. It is a typical Properties
window
for a form. T
he default text of the
Text property is Form
1, its default name is
also Form
1. You can change the title of
the text to whatever title you like by editing
the text.
Co
Co
nt.
nt.
Th
e p
rop
ertie
s of th
e o
bje
ct ap
pe
ar in
a list in
the
left co
lum
n w
hile
the
item
s listed
in th
e rig
ht
colu
mn
rep
rese
nt th
e sta
tes o
r valu
es o
f the
pro
pe
rties. Y
ou
can
set th
e p
rop
ertie
s by
hig
hlig
htin
g th
e ite
ms in
the
righ
t colu
mn
the
n
cha
ng
e th
em
by typ
ing
or b
y sele
cting
op
tion
s. Fo
r exa
mp
le, to
cha
ng
e th
e fo
rm's
title to
an
y na
me
tha
t you
like, sim
ple
click in
the
bo
x on
the
righ
t of th
e Te
xt pro
pe
rty an
d
type
in th
e n
ew
na
me
. In th
e p
rop
ertie
s
win
do
w, th
e ite
m a
pp
ea
rs at th
e to
p p
art is
the
curre
ntly se
lecte
d o
bje
ct.
Creat
Creat
ing
a in
g a
Sim
pS
imp
le le
Pro
gP
rog
ram
ram
that
that
disp
ld
ispl
ay a ay a
welc
welc
om
ino
min
g
g
mess
mess
age
age
In this
exam
ple,
we
will
create
a simpl
e progr
am
that
will
displa
y a
welco
me
mess
age
when
you
load
the
form.
First,
chang
e the
prope
rties
of the
form
as
follow
s:
In this example, we will create a simple program that will display a welcome message when you load the form.
First, change the properties of the form as follows:
Co
Co
nt.
nt.
N
ext, insert a label into the form and set its properties as follows:
Co
Co
nt.
nt.
Next, click on the F
orm
and enter the following
code:
Private S
ub W
elcomeM
sgF
rm_Load
(ByV
al sender As
System
.Ob
ject, ByV
al e A
s System
.EventA
rgs) H
andles MyB
ase.Load
Ms
gLbl.Text =
"Welcom
e to V
B2010
Pro
gramm
ing"
End S
ubN
ow press F
5 to run the program
, you w
ill see the m
essage displayed on the label.
Set
Set
ting
tin
g
Co
Co
ntr
ntr
ol
ol
Pro
Pro
per
per
ties ties u
siu
sin
g
ng
C
oC
od
ed
e
Yo
u ca
n a
lso ch
ang
e th
e
prop
ertie
s of th
e o
bje
ct u
sing cod
e. T
he
syntax to
m
an
ipu
late th
e p
rope
rties o
f an
ob
ject is
Ob
ject.prop
e
rty=p
rope
rty
_V
alu
e
Fo
r exam
ple,
TextBox1
.Text=
”Wel
come to
V
B2
010
”TextB
ox2.
Text=10
0
Th
e abo
ve code
sets the
text
prop
erty o
f TextB
ox1
to d
ispla
y the
text “Welcom
e to
VB
20
1 0” an
d
set the va
lue of TextB
ox2 to
100
.
Co
Co
nt.
nt.
Other properties you can change to give
special effects at runtime are color, shape,
animation effect and so on. F
or example, the
following code w
ill change the form color to
yellow every tim
e the form is loaded. V
B201
0 uses RG
B (R
ed, Green, B
lue) to determine
the colors. The R
GB
code for yellow is 255,
255, 0. Me in the code refers to the current
form and B
ackcolor is the property of the
form's background color. T
he formula to
assign the RG
B color to the form
is Color.
Form
Arbg(R
GB
code). Now
, click on the
form to go into the code w
indow. N
ext, enter
the following code betw
een the opening
statement P
rivate Sub and the closing
statement E
nd Sub, as show
n below. Y
ou
don’t have to w
orry about the code and the
code structure yet; we w
ill explain that in
chapter 3.
Co
Co
nt.
nt.
Public C
lass Form
1
Private S
ub Form
1_Load(ByV
al sender As
System
.Ob
ject, ByV
al e As S
ystem.E
ventA rgs)
Handles M
yBase.Load
Me.B
ackColor =
Color.F
romA
rgb(255, 255,
0)
End S
ub
End C
lass
No
w P
ress F
5 an
d yo
u w
ill see a
form
app
ea
r w
ith a ye
llow
backg
roun
d, a
s show
n in p
icture b
elow
.
Yo
u m
ay a
lso u
se the follow
ing
pro
ced
ure to
prod
uce
the sa
me e
ffect.
Private S
ub Form
1_Load(ByV
al sender As S
ystem.O
bject,
ByV
al e As S
ystem.E
ventA rgs) H
andles MyB
ase.Load
Me.B
ackColor =
Color.Y
elow
End S
ub
Co
Co
nt.
nt.
Th
e form with yellow background
Co
Co
nt.
nt.
Here are som
e
of the comm
on
colors and the
corresponding
RG
B codes.
You can alw
ays
experiment w
ith
other
combinations,
but remem
ber
the maxim
um
number for
each color is
255 and the
minim
um
number is 0.
The table below
shows som
e of
the comm
on
colors with their
corresponding
codes.
Co
Co
nt.
nt.
Th
e followin
g is a
progra
m tha
t
allo
ws th
e use
r to ente
r the
RG
B co
de in
to three
differen
t
Textboxes an
d w
hen
he or
she clicks th
e Disp
lay C
olo
r
butto
n, the
backg
roun
d co
lor
of th
e form ch
ang
es
acco
rding to
the R
GB
code
.
Th
e code
Priva
te Su
b Bu
tton
1_C
lick(ByV
al
send
er As S
ystem
.Ob
ject, B
yVa
l e A
s S
ystem
.Eve
ntA
rgs) Han
dle
s B
utto
n1.C
lick
Dim
rgb1, rgb
2, rgb3 A
s Inte
ger
rgb1 =
TextBox1
.Text
rgb2 =
TextBox2
.Text
rgb3 =
TextBox3
.Text
Me
.BackC
olo
r =
Co
lor.From
Argb
(rgb1, rgb
2,
rgb3)
En
d Su
b
Co
Co
nt.
nt.
The RGB Program
Su
Su
mmma
ma
ryry
you ha
ve lea
rne
d how
to a
dd
contro
ls to
the form
from
the
Toolb
ox
you le
arn
ed
how
to se
t the
p
rope
rties o
f the
con
trols u
sing th
e p
rope
rties
win
dow
.
you le
arn
ed
how
to se
t the
p
rope
rties o
f the
con
trols u
sing cod
e.
Fo
r exam
ple,
you le
arn
ed
how
to se
t foreg
roun
d
and
b
ackgrou
nd
colors u
sing
RG
B co
de.
Vis
Vis
ual
ual
Ba
Ba
sicsic20102010
Ch
apter 3
Writin
g th
e
Co
de
Le
arnin
g h
ow
to w
rite V
isu
al B
as
ic 2
010
Co
de
Un
dU
nd
erstaersta
nd
inn
din
g
g
Even
Even
t t Driv
Driv
en
en
Pro
gP
rog
ramram
min
gm
ing
In this ch
apte
r, you w
ill lea
rn som
e ba
sic concep
ts ab
out
VB
201
0 p
rog
ramm
ing a
nd
the tech
nique
s in w
riting
code
.I will ke
ep the
the
ories sh
ort so th
at it w
ou
ld no
t be to
o ta
for
beg
inne
rs.
VB
201
0 is an o
bje
ct orie
nted
a
nd e
ven
t drive
n p
rogra
mm
ing
lan
gua
ge. In
fact, a
ll win
dow
s a
pplica
tions are e
ven
t d
riven. E
ven
t drive
n m
ean
s the
use
r decid
es w
ha
t to d
o
with the
prog
ram
, wh
ethe
r h
e or sh
e w
ants to
click the
comm
an
d butto
n, ente
r text
in a te
xt box, o
r close the
a
pplica
tion a
nd m
ore
. An
e
ven
t is relate
d to a
n
obje
ct, it is an in
cide
nt that
hap
pe
ns to th
e ob
ject du
e to th
e action
of the
use
r, such
as a
click or pre
ssing
a
key o
n the keyb
oard
.
Co
Co
nt.
nt.
A class co
ntain
s events a
s it create
s insta
nt
of a
class o
r an o
bje
ct. Whe
n w
e start
a w
ind
ows a
pplica
tion in V
B2
01 0
in
previou
s ch
apte
rs, w
e
will
see
a
defa
ult fo
rm w
ith th
e Fo
rm 1
ap
pea
rs
in the ID
E. F
orm
1 is th
e F
orm
1 C
lass
that
inh
erits fro
m
the
Fo
rm
class
Syste
m.W
ind
ows.F
orms.F
orm
, as
show
n in
the
picture
.
Co
Co
nt.
nt.
The other
events
associate
d with the
Form
1
class are
click,
DoubleC
li
ck,
DragD
rop
, Enter
and more,
as shown
in the
image
below (It
appears
when you
click on
the upper
right pane
of the
code
window
)
Un
Un
der
der
stastan
di
nd
in
g
ng
th
e th
e C
oC
od
e d
e S
trS
tru
ctu
ctu
re u
re o
f o
f an
an
E
veE
ven
t n
t P
roP
rocedcedu
reu
re
No
w you
are re
ady to
write
the
code
for
the e
ven
t pro
ced
ure so
tha
t it will d
o
someth
ing m
ore
than
loa
din
g a
blan
k
form. T
he stru
cture
of th
e co
de ta
kes
the follow
ing
form
:
Priva
te Su
b...
State
me
nts
En
d Su
b
Yo
u ha
ve to en
ter the
cod
e betw
ee
n
Priva
te Su
b an
d En
d Su
b.
Priva
te Su
b
En
ter yo
ur co
de h
ere
En
d Su
b.
Co
Co
nt.
nt.
Th
ere
are
varia
tion
s of th
e stru
cture
such
as
i)P
ub
lic Su
b
En
ter yo
ur co
de
he
re
En
d S
ub
.
ii)S
ub
En
ter yo
ur co
de
he
re
En
d S
ub
.
iii)F
un
ction
En
ter yo
ur co
de
he
re
En
d F
un
ction
Let us enter the following code:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventA rgs) Handles MyBase.Load
Me.Text="My First VB2010 Program" Me.ForeColor = Color.Yelow
Me.BackColor = Color.Blue
End Sub
There are variations of the structure such as
i) Public Sub
Enter your code
here
End Sub.
ii) Sub
Enter your code
here
End Sub.
iii) Function
Enter your code
here
End Function
There are variations of the structure such as
i) Public Sub
Enter your code
here
End Sub.
ii) Sub
Enter your code
here
End Sub.
iii) Function
Enter your code
here
End Function
There are variations of the structure such as
i) Public Sub
Enter your code
here
End Sub.
ii) Sub
Enter your code
here
End Sub.
iii) Function
Enter your code
here
End Function
Co
Co
nt.
nt.
When you press F
5 to run the program
, the output is:
The first line of the code
will chang
e the title of the form
to “My F
irst VB
201 0 Program
” , the second line w
ill change the foreground
object to yellow( in this case, it is a label th
at you insert into the form
and change its
name to F
oreground) and the last line
changes the background to blue color. The
equal sign in the code is to assign
something to the object, like assigning
yellow color to the foreground
of the Form
1 object (or an instance o
f Form
1). Me is the
name given to the
Form
1 class. We can
also call those lines as State
men
ts.
Th
e T
he
Ou
tO
ut
pu
t p
ut
Win
Win
do
do
ww
He
re is a
no
the
r exam
ple
:
Priva
te Su
b Bu
tton
1_C
lick_1(B
yVal se
nd
er As
Syste
m.O
bje
ct, ByV
al e
As S
ystem.E
ventA
rgs) H
an
dles B
utto
n1.C
lick
Dim
nam
e1, na
me2
, na
me
3 A
s Strin
g
nam
e1 =
"John
"
nam
e2 =
"Ch
an
"
nam
e3 =
"Ali"
Ms
gBo
x(" Th
e nam
es a
re " & n
am
e1 &
"
, " & na
me
2 &
" and
" & na
me3
)
En
d Su
b
In this exa
mp
le, yo
u in
sert o
ne
com
ma
nd
butto
n into th
e fo
rm a
nd re
nam
e its
captio
n as S
ho
w H
idde
n Na
mes. T
he
keywo
rd D
im is to
decla
re va
riab
les
nam
e1, na
me2
and
nam
e3
as string
,
wh
ich m
ean
s the
y can on
ly han
dle
text.
Th
e functio
n Msg
Bo
x is to disp
lay th
e
nam
es in a
me
ssage
box th
at are join
ed
toge
ther by the
"&" sig
ns.
Co
Co
nt.
nt.
Ou
tpu
t:
Wri
Wri
ting
tin
g
a a S
imS
imp
le p
le M
ul
Mu
ltip
litip
licaticatio
n
on
P
roP
rog
rag
ramm
In th
is pro
gra
m, y
ou
inse
rt tw
o te
xt b
oxe
s, thre
e
lab
els a
nd
on
e b
utto
n.
Th
e te
xt b
oxes a
re for th
e
use
r to ente
r num
be
rs, the
labe
l is to d
isplay th
e
mu
ltiplication
ope
rator a
nd
the o
the
r lab
el is to displa
y the
equ
al sig
n. T
he
last
labe
l is to d
isplay th
e
answ
er. T
he
run
time
inte
rface is sh
own b
elow
:
Co
Co
nt.
nt.
Th
e Co
de
Priva
te Su
b Bu
tton
1_C
lick(ByV
al se
nde
r A
s Syste
m.O
bje
ct, ByV
al e
As
Syste
m.E
ven
tArgs) H
and
les B
utto
n1
.Click
Dim
num
1, n
um2
, pro
duct A
s Sing
le
num
1 =
TextBox1
.Text
num
2 =
TextBox2
.Text
prod
uct =
num
1 * nu
m2
TextBox3
.Text =
pro
duct
En
d Su
b
Wri
Wri
ting
tin
g
a a P
roP
rog
rag
ram
m
th
at th
at A
dA
dd
d
IteItem
s m
s to
a to
a L
ist L
ist B
oB
oxx
Th
is pro
gram
will a
dd
on
e item
at a tim
e to a
list box as th
e use
r en
ters an
item
into
the
text b
ox a
nd click th
e
Ad
d b
utton.
In this
pro
gram
, you
inse
rt a TextB
ox a
nd
a ListB
ox in
to
the
Form
. T
he
fu
nction
o
f the
TextB
ox is to le
t the
user e
nte
r an
item
on
e at a
time
and
add
it to the
L
istbox. T
he
me
tho
d to a
dd a
n item
to th
e L
istBox
is A
dd
. T
he
ou
tput
interface
is show
n belo
w, T
he
Cod
e:
Cla
ss Frm
1P
rivate S
ub B
utto
n1_
Click(B
yVa
l send
er A
s S
ystem
.Ob
ject, B
yVa
l e A
s S
ystem
.Eve
ntA
rgs) Han
dle
s Bu
tton
1.C
lick
Dim
item
As S
tring
item
= TextB
ox1.Te
xt
ListB
ox1.Item
s.Ad
d(ite
m)
En
d Su
b
En
d Cla
ss
Co
Co
nt.
nt.
Outp
ut:
Su
Su
mmma
ma
ryry
you le
arn
ed th
e co
nce
pt o
f eve
nt
drive
n pro
gram
ming
.
you le
arn
ed ho
w to w
rite a
simple
code
for an
even
t
proce
dure
, inclu
ding th
e
usa
ge o
f Msg
Bo
x().
you le
arn
ed ho
w to cre
ate a
m
ultip
lication p
rogra
m.
you le
arn
ed ho
w to w
rite a
p
rogra
m to
ad
d some
items to
a
list bo
x.
Vis
Vis
ual
ual
Ba
Ba
sicsic201
201
00
Ch
apter 4
Man
agin
g
VB
2010
Data
Ge
tting
to kn
ow va
riou
s da
ta
type
s in Visua
l Ba
sic 201
0
Assign
ing valu
es to th
e
variable
s
Ge
tting
to kn
ow va
riou
s
arith
me
tic ope
rato
rs in V
isual
Ba
sic 20
10
Co
Co
nt.
nt.
In ou
r da
ily life w
e co
me
across
ma
ny type
s of d
ata. F
or
exa
mp
le, we
nee
d to
han
dle
data
such
as
nam
es, ad
dresses, m
one
y,
date
s, stock q
uotes,
statistics a
nd m
ore
eve
ryday. S
imila
rly, in
Visu
al B
asic 2
010
, we
ha
ve
to de
al with
all sorts o
f
data
; som
e a
re nu
meric in
natru
re w
hile some a
re in
the form
of text o
r othe
r
forms. V
B2
01 0 d
ivides
data
into d
iffere
nt type
s so
that it is ea
sier to m
an
age
wh
en w
e ne
ed
to w
rite th
e
code
invo
lving th
ose d
ata
.
Co
Co
nt.
nt.
Vis
ua
l Ba
sic 2
01
0 Da
ta Ty
pe
s
Visu
al B
asic classifies th
e
inform
atio
n m
ention
ed a
bove
into
two
ma
jor da
ta type
s; nam
ely th
e
num
eric da
ta type
s an
d the n
on-
num
eric da
ta type
s.
Nu
meric
Da
ta Typ
es
Nu
me
ric da
ta typ
es are type
s of
data
tha
t consist o
f n
umb
ers, which you
can
com
pute
them
m
ath
ematica
lly with
variou
s sta
nda
rd op
era
tors su
ch as
add
, minu
s, multip
ly, divide
a
nd so
on
Nu
Nu
mer
mer
ic ic D
atD
ata a TypTypeses
In Visual B
asic 2010, we
divide numeric data
into seven types, depending on the range of values they can store. C
alculations that only involve round figures or data that do not need precision can use Integer or Long integer in the com
putation. P
rograms that
require high precision calculation need to use S
ingle and D
ouble decision data types, w
e also call them
floating-point num
bers. For
currency calculation, you can use the currency data types. Lastly, if even m
ore precision is requires w
hich involve many
decimal points, w
e can use the decim
al data types. W
e sum
marized the
data types in Table below
.
No
No
n-
n-
nu
nu
mer
mer
ic ic D
atD
ata a TypTypeses
No
nn
um
eric
da
ta
type
s
are
d
ata
tha
t
can
no
t b
e
ma
nip
ula
te
d
ma
the
ma
ti
cally u
sing
stan
da
rd
arith
me
tic
op
era
tors.
Th
e
no
n-
nu
me
ric
da
ta
com
prise
s
text
or
string
da
ta
type
s, th
e
Da
te
da
ta
type
s, th
e
Bo
ole
an
da
ta
type
s
tha
t sto
re
on
ly tw
o
valu
es
(true
o
r
false
),
Ob
ject
da
ta
type
an
d
Va
rian
t
da
ta typ
e .
Su
fS
uf
fixefixes s fo
r fo
r L
iteL
iteralsrals
Lite
rals are
value
s tha
t you assig
n to
a
data
. In so
me
cases, w
e nee
d to
add
a su
ffix be
hind a
literal so
tha
t
VB
201
0 can h
and
le th
e ca
lcula
tion
mo
re accura
tely. Fo
r exam
ple
, we
can use
nu
m=
1 .3
089
# fo
r a D
ou
ble
type
da
ta.
In a
dditio
n,
we
n
eed
to
en
close
strin
g
literals w
ithin
two q
uota
tion
s and
date
an
d
time
litera
ls with
in two
# sig
n. S
tring
s can
contain
any ch
aracte
rs, includ
ing n
umbe
rs.
Th
e followin
g a
re fe
w e
xam
ples:
Dec
Dec
larilari
ng
n
g
Vari
Vari
abl
abl
eses
In Visual B
asic 2010, one needs
to declare
the variables
before using
them
by
assigning names and data
types. If you fail to do so,
the program
w
ill show
an
error. T
hey are
normally
declared in
the general
section of
the codes'
window
s using
the D
im
statement.
The form
at is as follows:
Dim
Variable
Nam
e As
Data Type
Co
Co
nt.
nt.
Sam
ple
cod
eP
rivate S
ub F
orm
1_
Loa
d(ByV
al sen
der A
s S
ystem
.Ob
ject, B
yVa
l e A
s S
ystem
.Eve
ntA
rgs) Han
dle
s M
yBa
se.Lo
ad
Dim
passw
ord A
s String
Dim
yourN
am
e A
s Strin
g
Dim
firstnum
as In
terge
r
Dim
second
num
As In
tger
Dim
total a
s Inte
ge
r
Dim
doD
ate A
s Da
te
En
d Su
b
Yo
u m
ay a
lso co
mb
ine
the
m in o
ne lin
e,
sepa
rating e
ach va
riab
le w
ith a
com
ma,
as follow
s:
Dim
passw
ord A
s Strin
g, yourN
ame
As
Strin
g, firstnu
m A
s Integ
er...
Co
Co
nt.
nt.
Fo
r string
de
clara
tion, the
re a
re tw
o
possib
le forma
ts, on
e fo
r the
variable
-len
gth
string a
nd a
noth
er for the fixe
d-le
ngth
string. F
or the varia
ble-len
gth
string, ju
st
use
the
sam
e form
at as e
xam
ple a
bove
.
Ho
we
ver, fo
r the
fixed
-leng
th strin
g, you
have
to use
the fo
rma
t as sh
own b
elow
:
Dim
Va
riableN
ame a
s Strin
g * n
, wh
ere n
define
s the
nu
mb
er o
f cha
racters the string
can ho
ld.
Dim
yourNam
e as String * 10
you rN
am
e ca
n h
old
s no
mo
re than
10
Ch
aracters.
Ass
Ass
ign
iig
ni
ng
n
g
Val
Val
ues
ues
to
to
Vari
Vari
abl
abl
eses
After declaring various variables using the D
im
statements, w
e can assign values to those
variables. The general form
at of an assignment is
Variable=
Expression
The variable can be a declared variable or a
control property value. The expression
could be a mathem
atical expression, a
number, a string, a B
oolean value (true or
false) and more. T
he following are som
e
examples:
FirstN
umber=
100 secondN
umber=
f irstNum
ber-99
userNam
e="John Lyan
"
userpass.Text = passw
ordLabel1.V
isible = T
rue C
omm
and1.Visible =
false
Label4.Caption =
textbox1.Text T
hirdNum
ber =
Val(usernum
1.Text)
total = firstN
umber +
secondNum
ber+T
hirdNum
ber
Co
Co
nst
nst
ant
ant
ss
De
cla
ring
a C
on
stan
t
Th
e forma
t to de
clare a
consta
nt is
Const C
onstant Nam
e
As D
ata Type = V
alue
Exam
ple:
Priva
te Su
b Fo
rm1
_Lo
ad(B
yVa
l
send
er As S
ystem
.Ob
ject, B
yVa
l e
As S
ystem
.Eve
nt A
rgs) H
and
les
MyB
ase
.Loa
d
Co
nst P
i As S
ingle=
3.14
2
Co
nst Tem
p As S
ingle
=3
7
Co
nst S
core
As S
ingle
=10
0
En
d Su
b
Su
Su
mmma
ma
ryry
you
lea
rned
th
at
we
could
catego
rize
data
type
s in
to
num
eric
and
n
on
-num
eric
data
types.
you
lea
rned
ab
out
the
rule
s to
nam
e
varia
ble
s in
V
isual
Ba
sic 2
010
. B
esid
es,
you
also
learn
ed
ho
w to
decla
re
variable
s u
sing
the
Dim
keywo
rd
an
d a
ssign
value
s
to them
.
you le
arn
ed ab
out con
stan
ts and
the w
ay to
de
clare th
em
Vis
Vis
ual
ual
Ba
Ba
sicsic201
201
00
Ch
apter 5
Perfo
rmin
g
Math
ematic
al
Op
eration
s
Learn
ho
w to
use
Math
ematical o
perato
rs.
Perf
Perf
orm
io
rmi
ng
n
g
Math
Math
emat
emat
ical ical
Op
erO
per
atioatio
ns
ns
Com
puters can
perform
mathem
atical calculations
much
faster than
human
beings. H
owever,
the com
puter itself
will
not be
able to
perform
any m
athematical
calculations w
ithout receiving instructions from
the programm
er.
The V
B201 0 arithm
etic operators
are very
similar
to the
normal arithm
etic operators,
only w
ith slight
variations.
The
plus and
minus
operators are
the sam
e
while
the m
ultiplication
operator use
the *
symbol
and the
division operator
use the / symbol. T
he list of
VB
2010 arithmetic operators
are shown in table below
:
Co
Co
nt.
nt.
Co
Co
nt.
nt.
In th
is pro
gra
m,
you
ne
ed
to
insert
two
Te
xtboxes,
four
labe
ls and
one
bu
tton
. Click
the
button
a
nd
ente
r th
e cod
e
as
show
n b
elo
w.
Wh
en yo
u run
the
prog
ram,
it will p
erform
the fou
r basic
arith
me
tic op
era
tions
and
d
ispla
y th
e re
sults o
n th
e fou
r labe
ls.
Co
Co
nt.
nt.
Th
e p
rogra
m
can
use
P
ythag
ora
s
Th
eore
m
to
calculate
the
len
gth
of
hyp
oten
use
c
give
n the len
gth
of
the a
djace
nt sid
e a
and
the
op
po
site
side
b. In
case you
have
fo
rgotte
n the
formu
la
for
the
Pyth
ago
ras
Th
eore
m,
We
are
show
ing it b
elo
w:
c2=
a2+
b2
Co
Co
nt.
nt.
BM
I Ca
lcu
lato
r
Ma
ny p
eop
le are
ob
ese n
ow
and
it cou
ld affect th
eir hea
lth
seriously. O
besity ha
s pro
ven
by the
me
dica
l exp
erts to b
e a
one
of the
ma
in facto
rs that
brin
gs m
any a
dve
rse med
ical
prob
lem
s, including
the
hea
rt d
isease
. If your B
MI is m
ore
tha
n 30
, you a
re co
nsidere
d o
bese. Y
ou ca
n refe
r to th
e
followin
g ra
ng
e of B
MI valu
es for yo
ur we
ight sta
tus:
Un
derw
eight =
<1
8.5
No
rma
l weig
ht = 18
.5-24
.9
Ove
rwe
igh
t = 25
-29
.9
Ob
esity =
BM
I of 30
or gre
ater
Co
Co
nt.
nt.
In order to calculate your BM
I, you
do not have to consult your
doctor, you could just use a
calculator or a homem
ade
computer program
, and this is
exactly what I am
showing you
here. The B
MI calculator is a
Visual B
asic program that can
calculate the body mass index,
or BM
I of a person based on
the body weight in kilogram
and the body height in meter.
BM
I is calculated based on the
formula w
eight/ (height) 2,
where w
eight is measured in
kg and height in meter. If you
only know your w
eight and
height in lb and feet, then you
need to convert them to the
metric system
(you could
indeed write a V
B program
for
the conversion).
Co
Co
de
de
an
an
d
d
ou
ou
tptput
ut
Cod
e:
ou
tpu
t:
Vis
Vis
ual
ual
Ba
Ba
sicsic201
201
00
Ch
apter 6
Strin
g
Man
ipu
latio
n
Le
arn h
ow
to m
anip
ula
te
Strin
gs
Stri
Stri
ng
n
g
Ma
Ma
nip
nip
ulat
ulat
ion
ion
String m
anipulation is an important
part of
programm
ing because
it
helps to process data that come in
the form of non-num
eric types such
as nam
e, address,
city, book
title
and etc.
Strin
g M
anip
ulatio
n U
sing
+
and
& sig
ns.
Strings can be m
anipulated using
the & sign and the +
sign,
both perform the string
concatenation which m
eans
combining tw
o or more
smaller strings into a larger
string. For exam
ple, we can
join "Visual" and "B
asic" into
"Visual B
asic" using
"Visual"&
"Basic" or "V
isual
"+"B
asic", as shown in the
example below
Co
Co
nt.
nt.
Th
e lin
e
text3
=te
xt1+
te
xt2
can
be
repla
ced
b
y
text3=te
xt1
&
text2
a
nd
prod
uce
d
the
sa
me
ou
tput.
Ho
we
ver,
if o
ne
o
f th
e
variable
s is
declare
d
as
num
eric
data
type
, yo
u
cann
ot use
the
+ sig
n, you
can on
ly use
the &
sign.
Co
Co
nt.
nt.
Dim
text1, text3 a
s string
Dim
Text2
As In
tege
r
text1 = "V
isua
l"
text2=2
2
text3=te
xt1+
text2
Lab
el1
.Text =
text3
Th
is co
de
will p
rod
uc
e a
n
erro
r bec
au
se
of d
ata
mis
matc
h. H
ow
eve
r,
us
ing
& in
ste
ad o
f + w
ill
be
all rig
ht.
Co
Co
nt.
nt.
Dim
text1, text3 a
s string
Dim
Text2
As In
tege
r
text1 = "V
isua
l"
text2=2
2
text3=te
xt1 &
text2
Lab
el1
.Text =
text3
Yo
u ca
n co
mb
ine
mo
re than
two
strings to form
a large
r string, like
the follow
ing
exam
ple:
Strin
Strin
g
g
Man
iM
ani
pu
lap
ula
tion
tio
n
Usin
Usin
g
g
VB
2V
B2
010 010
Bu
iltB
uilt
-in
-in
Fu
nF
un
ctioctio
ns
ns
A fu
nction
is similar to
a no
rmal
proce
dure
bu
t th
e
ma
in
purp
ose
of th
e functio
n is to
acce
pt a certa
in inpu
t an
d
return
a
value,
wh
ich
is
passed
on
to
the
ma
in
prog
ram
to
finish
the
exe
cution.
VB
20
10
has
num
erou
s b
uilt-in
strin
g
ma
nip
ulation
fu
nctio
ns bu
t
we
will on
ly discu
ss a fe
w
here
. Y
ou
w
ill le
arn
mo
re
abo
ut
these
fu
nction
s in
later C
hap
ters.
Th
e T
he
Len
L
en
Fu
nF
un
ctioctio
nn
Th
e leng
th fun
ction re
turns a
n
intege
r value tha
t is the
leng
th o
f a ph
rase
or a
senten
ce, includ
ing th
e
em
pty spa
ces. Th
e fo
rma
t is
Le
n (“
Ph
rase”
)
Fo
r exam
ple,L
en (V
isua
l Ba
sic) =
12 a
nd
Len
(we
lcom
e to
VB
tutorial) =
22
Co
Co
nt.
nt.
Cod
e:
outp
ut:
Th
e T
he
Rig
Rig
ht
ht
Fu
nF
un
ctioctionn
The R
ight function extracts the right
portion of a phrase.
The form
at for
Visual B
asic 6 is
Rig
ht (“P
hrase
”, n)
Where n is the starting position from
the right of the phase where the
portion of the phrase is going to be
extracted. For exam
ple,
Right(“V
isual
Basic”, 4) =
asic
How
ever, this format is not
applicable in VB
201 0. In VB
201 0,
we need to use the follow
ing format
Microsoft.V
isual
Basic.R
ight("Phrase
" ,n)
Co
Co
nt.
nt.
Th
e abo
ve pro
gram
will re
turn
four righ
t mo
st cha
racters
of th
e phrase
en
tere
d in
to
the textbo
x,
Th
e T
he
Left
Left
Fu
nF
un
ctioctio
nn
Th
e Left fu
nction
extract th
e le
ft
portio
n of a
phra
se. T
he
forma
t is
Microso
ft.Visu
alB
asic.
Left("P
hrase", n)
Wh
ere n is th
e starting
position
from
the
left o
f the p
hase
wh
ere
the p
ortion o
f the p
hrase is g
oing
to be
extra
cted
. Fo
r exam
ple
,
Microso
ft.Visu
alB
asic.L
eft (“V
isua
l
Ba
sic”, 4) =
Visu .
We
will le
arn m
ore
abo
ut string
ma
nip
ulation
fun
ction in
Ch
apte
r 11.
Su
mm
ary
In section
6.1, you
learn
ed h
ow to
ma
nipula
te
strings using
+ a
nd
&
sign
s. Th
e + an
d &
sign
s
are u
sed to
join u
p tw
o
strings.
In section
6.2, you
learn
ed h
ow to
use strin
g
ma
nip
ulation
fun
ctions.
Am
on
g the fun
ction
s are
Len
, Rig
ht a
nd L
eft,
Vis
Vis
ual
ual
Ba
Ba
sicsic201
201
00
Ch
apter 7
Co
ntro
lling
Pro
gram
Flo
w
Un
de
rstan
din
g C
on
ditio
nal
an
d L
og
ica
l Op
era
tors
Us
ing
the
If co
ntro
l s
tructu
re w
ith th
e
Co
mp
aris
on
Op
era
tors
Co
Co
ntr
ntr
olli
olli
ng
n
g
Pro
Pro
gra
gra
m
m
Flo
Flo
ww
In the previous Chapters, w
e have learned
how
to w
rite code
that accepts
input from
the
user and displays the output w
ithout controlling
the program
flow. In this chapter,
you w
ill learn
how
to w
rite V
B201 0 code that can m
ake decision
when
it processes
input from
the
user, and
controls the program flow
in the process.
. F
or exam
ple, w
e can
write
a
VB
201 0
program
that can
ask the computer to perform
certain task
until a
certain
condition is
met,
or a
program that w
ill reject non-
numeric
data. In
order to
control the program flow
and
to make decisions, w
e need
to use
the conditional
operators and
the logical
operators together with the If
control structure.
Co
Co
nd
itn
dit
ion
ion
al al O
pO
peraterato
rso
rs
Th
e con
dition
al
op
erators
are
pow
erful
tools
that
can
compa
re
value
s a
nd
then
decide
w
hat
action
s to
take, w
he
ther to e
xecute
a
prog
ram
o
r te
rmin
ate
th
e
prog
ram
a
nd
mo
re.
Th
ey
are
also
kn
ow
n
as
num
erica
l com
pariso
n
ope
rators. N
orma
lly we
use
them
to
co
mp
are
two
values to
see
wh
ether th
ey
are e
qua
l or o
ne va
lue is
grea
ter
or
less th
an
the
oth
er
value
. T
he
compa
rison
will retu
rn true
or
false
resu
lt. T
hese
ope
rators
are
show
n
in
Table b
elow
.
Lo
gL
og
ical ical
Op
Op
eraterat
ors
ors
So
me
times w
e m
igh
t ne
ed to
ma
ke mo
re
than
on
e
com
pa
rison
befo
re
a
decisio
n can be
ma
de a
nd a
n action
take
n. In this ca
se, usin
g nu
me
rical
compa
rison
op
erato
rs a
lone
is
no
t sufficie
nt, we n
eed
to u
se ad
dition
al
ope
rators, a
nd
they are the
log
ical
ope
rators. T
he lo
gica
l ope
rators are
sho
wn
in ta
ble b
elow
.
* Norm
ally the above operators are use to compare
numerical
data. H
owever,
you can
also com
pare strings with the above operators. In
making strings com
parison, there are certain rules to follow
s: Upper case letters are less
than lowercase letters, "A
"<"B
"<"C
"<"D
"...<"Z
" and num
ber are less than letters.
Usi
Usi
ng
n
g
the
the
If If co
nco
ntro
l tro
l strstru
ctu
ctu
re u
re w
itw
ith
h
th
e th
e C
oC
om
pm
parisariso
n
on
O
pO
peraterato
rso
rs
To effectively co
ntrol th
e VB
prog
ram
flow
,
we
sh
all
use
the
If
contro
l stru
cture
d
toge
ther w
ith the
con
dition
al ope
rato
rs
and
log
ical o
pera
tors. The
re are
three
type
s o
f If
contro
l stru
cture
, n
am
ely
If...Th
en
statem
ent,
If...Th
en...
Else
statem
ent
and
If...T
hen
...Els
eIf
statem
ent.
If...Th
en S
tatem
en
t
This is the sim
plest control structure which ask the
computer to perform
a certain action
specified by the VB
expression if the
condition is true. How
ever, when the
condition is false, no action will be
performed. T
he general format for the
if.. .then... statement is:
If con
ditio
n th
en
VB
exp
res
sion
En
d if
Co
Co
nt.
nt.
Exam
ple
:
Priva
te Su
b Bu
tton
1_C
lick(ByV
al se
nde
r As
Syste
m.O
bje
ct, ByV
al e
As
Syste
m.E
ven
tArgs) H
and
les B
utto
n1
.Click
Dim
myN
um
be
r As
Inte
ger
myN
um
ber =
TextB
ox
1.Te
xt
If my
Nu
mb
er >
10
0 Th
enL
ab
el2.Te
xt =
" Yo
u w
in a
luc
ky
p
rize"
En
d If
En
d Su
b
Wh
en yo
u run
the
prog
ram an
d e
nter a
num
ber tha
t is grea
ter than
100
, you
will se
e th
e "Y
ou w
in a lu
cky prize
"
statem
ent. O
n th
e othe
r han
d, if th
e
num
ber
ente
red
is less
than
o
r
equ
al to
10
0, you do
not se
e a
ny
disp
lay.
Co
Co
nt.
nt.
If...Th
en...E
lse S
tate
me
nt
Using
just If..
.Then
statement
is not
very useful
in
programm
ing and it does not provides choices for the
users. In order to provide a choice, we can use the
If.. .Th
en. . . E
lse Statem
ent. T
his control structure will
ask the computer to perform
a certain action specified
by the VB
expression if the condition is true. When the
condition is false, an alternative action will be executed.
The general form
at for if. ..then... Else statem
ent is:
If con
ditio
n th
en
VB
expressio
n
Else
VB
expressio
n
En
d if
Co
Co
nt.
nt.
Exam
ple
:
Priva
te Su
b Bu
tton
1_C
lick(ByV
al se
nde
r As
Syste
m.O
bje
ct, ByV
al e
As S
ystem.E
ventA
rgs) H
an
dles B
utto
n1.C
lick
Dim
myN
um
be
r As
Inte
ger
myN
um
ber =
TextB
ox
1.Te
xt
If my
Nu
mb
er >
10
0 Th
enL
ab
el2.Te
xt =
“Co
ngra
tula
tion
! Yo
u
win
a luck
y p
rize!" Els
e
La
be
l2.Tex
t = “S
orry, Y
ou
did
no
t win
a
ny p
rize"
En
d If
En
d Su
b
When you run the program
and enter a number that
is greater
than 100,
it displays
a m
essage
“Congratulation! Y
ou win a lucky prize!” O
n the other
hand, if the number entered is less than or equal to
100, you will see the "S
orry, You did not w
in any
prize" message.
Co
Co
nt.
nt.
Ex
amp
le
Priva
te Su
b Bu
tton
1_C
lick(ByV
al se
nde
r As
Syste
m.O
bje
ct, ByV
al e
As S
ystem.E
ventA
rgs) H
an
dles B
utto
n1.C
lick
Dim
myN
um
be
r, MyA
ge
As In
tege
r
myN
um
ber =
TextB
ox
1.Te
xt
My
Ag
e = Tex
tBo
x2.Te
xt
If my
Nu
mb
er >
10
0 An
d m
yA
ge >
60
Th
en
La
be
l2.Tex
t = " C
on
gra
tula
tion
! Yo
u
win
a luck
y p
rize" E
lse
La
be
l2.Tex
t = " S
orry, Y
ou
did
no
t w
in an
y p
rize”
En
d If
En
d Su
b
Co
Co
nt.
nt.
Th
is pro
gram
use th
e logica
l An
d
ope
rator
be
side
the
con
dition
al
ope
rators. T
his mea
ns th
at for the
sta
teme
nt to
be
true,
both
con
dition
s m
ust
be
fulfilled
in
o
rder; oth
erw
ise, th
e second
blo
ck o
f code
will b
e exe
cuted
. In th
is e
xam
ple,
the
num
ber
ente
red
mu
st be
more tha
n 10
0 a
nd th
e a
ge m
ust b
e more
than
60
in ord
er
to win
a
lucky prize
, any on
e of the
abo
ve
cond
itions
no
t fu
lfilled
will
disq
ualify th
e u
ser from
winn
ing a
prize
.
Co
Co
nt.
nt.
If...Th
en...E
lseIf S
tatem
en
t
If there
are m
ore
tha
n tw
o altern
ative
s, using
just If.. .The
n. . . E
lse sta
tem
ent w
ill no
t
be
en
oug
h. In
orde
r to
pro
vide
mo
re
choice
s, w
e
can
u
se th
e If..
.Th
en..
.
Else
If Sta
tem
ent. T
he g
ene
ral form
at
for the if.. .th
en... E
lse sta
temen
t is:
If...If...
Th
eT
he
n...
n...
Els
Els
eIf eIf
Sta
Sta
temtem
ent
ent
Exam
ple
:
Su
mm
ary
In th
is cha
pte
r, you
lea
rne
d h
ow
to
use
the
If con
trol stru
cture
tog
eth
er
with
the
com
pa
rison
op
era
tors to
con
trol p
rog
ram
flow
.
you
lea
rne
d h
ow
to u
se th
e
con
ditio
na
l op
era
tors in
VB
20
10
such
as =
, <,>
, >=
,
<=
an
d <
>.
you
lea
rne
d h
ow
to u
se
the
log
ical o
pe
rato
rs An
d,
Or, X
or a
nd
No
t.
you
lea
rne
d th
ree
type
s of If
con
trol stru
cture
, i.e.
If.. .Th
en
, If.. .Th
en
. . . Else
an
d If.. .T
he
n. .. E
lse If.
Be
side
s, you
also
lea
rne
d
ho
w to
write
cod
e in
volvin
g
the
use
of th
e If co
ntro
l
structu
re.
Ch
ap
ter 9C
ha
pter 9
Lo
op
ing
Lo
op
ing
Ch
apter 8
Select C
ase C
on
trol
Stru
cture
Un
derstan
din
g T
he S
elect C
ase
…
.End
Sele
ct Stru
cture
Sel
Sel
ect
ect
Ca
Ca
se
se
Co
Co
ntr
ntr
ol
ol
Str
Str
uct
uct
ur
ur
ee
In the previous Chapter, w
e have learned
how to control the program
flow using the
If... ElseIf control structure. In this chapter,
you will learn another w
ay to control the
program
flow,
that is,
the S
elect C
ase
control structure.
How
ever, the
Select
Case control structure is slightly different
from the If... E
lseIf control structure. The
difference
is that the Select C
ase control structure
basically only
make
decision on
one expression
or dim
ension (for
example
the exam
ination grade)
while
the If...
ElseIf
statement
control structure may evaluate only
one expression,
each If...
ElseIf
statement
may
also com
pute
entirely different dimensions. S
elect
Case is preferred w
hen there exist
many different conditions because
using If.. .Then. . .E
lseIf statements
might becom
e too messy.
Co
Co
nt.
nt.
Th
e Se
lect C
ase
. . . En
d S
elect co
ntrol
structu
re is sh
ow
n b
elo
w:
Co
Co
nt.
nt.
Ex
amp
le:
Priva
te Su
b Bu
tton
1_C
lick(ByV
al se
nde
r As S
ystem.O
bje
ct, B
yVal e A
s Syste
m.E
ven
tArgs) H
and
les B
utto
n1
.Click
Dim
mark A
s S
ing
le
Ma
rk =
mrk
.Tex
t
Se
lec
t Cas
e m
ark
Ca
se 0
to 4
9
La
ble
1.Tex
t = “N
eed
to w
ork h
ard
er”
Ca
se 5
0 to 4
9
La
ble
2.Tex
t = “A
ve
rage
”
Ca
se 6
0 to 6
9
La
ble
3.Tex
t = “A
bo
ve
Ave
rag
e”
Co
Co
nt.
nt.
Ca
se 7
0 to 8
4
La
ble
4.Tex
t = “G
oo
d”
Ca
se E
lese
La
ble
5.Tex
t = “E
xc
elle
nt!!!”
En
d S
elec
t
En
d sub
Su
mm
ary
In this ch
apte
r, you le
arne
d ho
w
to contro
l pro
gram
flow
usin
g the S
ele
ct Ca
se
contro
l structu
re. Y
ou a
lso
learn
ed h
ow to
write
cod
e for th
e pra
ctical u
sage
of
the S
elect C
ase
con
trol stru
cture
, such
as the
p
rogra
m th
at processed
e
xam
inatio
n ma
rks.
Vis
Vis
ual
ual
Ba
Ba
sicsic201
201
00
Ch
apter 9
Lo
op
ing
Understanding and using
Do…
Loop
Understanding and using
While…
End w
hile Loop
Lo
Lo
op
iop
i
ng
ng
Visual B
asic 2010
allows
a proce
dure to
repeat
many
times
as long
as the
processor could supp
ort. We call
this lo
oping. Looping is required
when
we
need
to process
some
thing
repetitively until
a
certain condition
is m
et. F
or
example,
we
can
design a
program
that
adds
a serie
s of
numbers until it exce
ed a certain
value, or
a program
th
at asks
the user to enter data repeatedly
until he or she keys in the w
ord
'Finish'. In V
isual Basic 2010, w
e
have three types of Loops, they
are the Fo
r...Next loo
p, the Do
loo
p and the W
hile...E
nd
wh
ile
loop.
Fo
r.F
or.
..Ne
..Ne
xt xt L
oo
Lo
opp
Th
e form
at is:
Fo
r cou
nter=
startNu
mb
er to
end
Nu
mb
er (Step
increm
ent)
On
e or m
ore V
B statem
ents
Next
Som
etimes the user m
ight want
to get
out from
the
loop before the w
hole repetitive process is com
pleted. The
comm
and to
use is
Exit
Fo
r. To exit
a F
or….N
ext Loop,
you can
place the
Exit
For
statement
within
the loop; and it is normally
used together
with
the If…
..Then…
statement. F
or its
application, you
can refer
to E
xample
on the
next slide.
Lo
Lo
op
iop
in
g
ng
C
oC
on
t.n
t.
Exam
ple 1.
Dim
cou
nter as In
teger
Fo
r cou
nter =
1 to 10
Listb
ox1.Item
s.add
(cou
nter)
Next
* The program
will enter
number 1 to 10 into the Listbox.
Lo
Lo
op
iop
in
g
ng
C
oC
on
t.n
t.
Exam
ple 2.
Dim
cou
nter , su
m A
s Inte
ger
Fo
r cou
nter=
1 to 100 step
10
sum
+=
cou
nter
ListB
ox1.Item
s.Ad
d (su
m)
Next
* The program
will calculate the sum
of the numbers as follow
s:
sum=
0+1 0+
20+30+
40+...
Lo
Lo
op
iop
in
g
ng
C
oC
on
t.n
t.
Exam
ple 3.
Dim
cou
nter, su
m A
s Integ
er
sum
= 1000
Fo
r cou
nter =
100 To 5 S
tep -5
sum
- = co
un
ter
ListB
ox1.Item
s.Ad
d(su
m)
Next
****Notice that increm
ent can be negative.
The program
will com
pute the
subtraction as follows:
1000-100-95-90-…
..
Lo
Lo
op
iop
in
g
ng
C
oC
on
t.n
t.
Exam
ple 3.
Dim
n as In
teger
F
or n
=1 to
10
If n>
6 then
Exit F
or
En
d If
Else
ListB
ox1.Item
s.Ad
d ( n
)
Next
The process w
ill stop when n is
greater than 6.
Do
D
o
Lo
oL
oo
pp
Th
e form
ats are:
a) D
o While condition
Block of one or m
ore VB
statements
Loop
b)D
o
Block of one or m
ore VB
statements
Loop While condition
c)D
o Until condition
Block of one or m
ore VB
statements
Loopd)D
o
Block of one or m
ore VB
statements
Loop Until condition
* Exitin
g th
e L
oo
p
So
me
time w
e ne
ed e
xit to exit a
loo
p pre
ma
ture
ly
beca
use o
f a certain
cond
ition is fu
lfilled
.
Th
e syntax w
e u
se is Exit D
o. L
et us
exa
min
e the fo
llowin
g e
xamp
le:
Do
D
o
Lo
oL
oo
p
p
con
con
t.t.
Exam
ple 1.
Do
wh
ile cou
nter <
=1000
TextBo
x1.Text=co
un
ter
cou
nter +
=1
Lo
op
* The above exam
ple will keep on
adding until counter >100
Th
e abo
ve examp
le can b
e rewritten
as:
Do
Text Bo
x1.Text=co
un
ter co
un
ter+=
1
Lo
op
un
til cou
nter>
1000
Do
D
o
Lo
oL
oo
p
p
con
con
t.t.
Exam
ple 2.
Private S
ub Button1_C
lick(ByV
al sender A
s System
.Ob
ject, ByV
al e A
s System
.EventA
rgs) Handles
Button1.C
lick
Dim
sum
, n A
s Inte
ger D
o n
+=
1 su
m +
= n
ListB
ox1.Item
s.Ad
d(n
&
vbTab
& su
m)
If n =
100 Th
en E
xit Do
En
d If
Lo
op
Su
b
Do
D
o
Lo
oL
oo
p
p
con
con
t.t.
In th
e a
bo
ve E
xam
ple
, we
find
the
su
mm
atio
n
of
1+
2+
3+
4+
……
+1
00
. In
the
d
esig
n
stag
e,
you
ne
ed
to in
sert a
ListB
ox
into
th
e
form
fo
r
disp
layin
g
the
o
utp
ut,
na
me
d
List1
. T
he
pro
gra
m
use
s th
e
Ad
dIte
m
me
tho
d
to
po
pu
late
the
ListB
ox. T
he
state
me
nt
ListB
ox1
.Item
s.Ad
d
(n
&
vbTa
b &
sum
) will d
ispla
y
the
h
ea
din
gs
in
the
ListB
ox, w
he
re it u
ses th
e
vbTa
b fu
nctio
n to
crea
te a
spa
ce
be
twe
en
th
e
he
ad
ing
s n a
nd
sum
.
Wh
iW
hi
le ..le ...E
n.E
nd
d
W
hi
Wh
ile le L
oo
Lo
opp
The structure of a W
hile…. E
nd
While is very sim
ilar to the Do
Loop. It takes the following
format:
Wh
ile con
ditio
n
Statem
ents
En
d W
hile
Wh
iW
hi
le ..le ...E
n.E
nd
d
W
hi
Wh
ile le L
oo
Lo
op
p
co
nco
nt.t.
Exam
ple 3.
Dim
sum
, n A
s Inte
gerP
rivate Su
b
Bu
tton
1_Click(B
yVal sen
der
As S
ystem.O
bject, B
yVal e A
s S
ystem.E
ventA
rgs) Han
dles
Bu
tton
1.Click
Dim
sum
, n A
s Inte
gerW
hile n
<>
100n
+=
1su
m =
sum
+ n
ListB
ox1.Item
s.Ad
d(n
&
vbTab
& su
m)
En
d W
hile
En
d S
ub
Su
mm
ary you learned how to w
rite
code for the For...N
ext
loop. The loop stops w
hen
a condition is met. Y
ou
also learned how to use
Exit F
or to exit the loop.
you learned how to w
rite
code for
the D
o loop
procedure. It includes the
use of the While keyw
ord
to set
the condition
for
stopping the
loop. Y
ou
also learned how to use
Exit D
o to exit the loop.
you learned how to w
rite code for the W
hile.. .End W
hile loop. Y
ou also learned that the loop stops w
hen a condition is m
et.
Vis
Vis
ual
ual
Ba
Ba
sicsic201
201
00
Ch
apter 10
Intro
du
ction
to
F
un
ction
s
Getting to know
all the
functions in Visual B
asic
2010
Int
Int
rorodu
du
cti
cti
on
on
to
to
Fu
Fu
nct
nct
ion
ion
ss
A function is sim
ilar to a normal
procedure but the main purpose of the
function is to accept a certain input
and return a value, which is passed
on to the main program
to finish the
execution. There are tw
o types of
functions, the built-in functions (or
internal functions) and the functions
created by the programm
ers.
The general form
at of a function is
Fu
nctio
nN
ame
(argu
men
ts)
The argum
ents are values that are
passed on to the function.
In this Chapter, w
e are going to learn
two very basic but useful internal
functions of Visual B
asic, i.e. the
MsgB
ox( ) and InputBox ( ) functions.
Ms
Ms
gB
gB
ox (
ox (
) ) Fu
nF
un
ctioctionn
Th
e obje
ctive of M
sgB
ox is to
prod
uce
a p
op-up
me
ssage
box
and
prom
pt the use
r to click on
a
comm
an
d butto
n befo
re yo
u can
contin
ue. T
his fo
rmat is as follow
s:
yo
urM
sg
=M
sgB
ox
(Pro
mp
t, Style
Va
lue
, Title
)
Th
e first arg
um
ent, P
rompt,
disp
lays the
me
ssag
e in the
me
ssag
e bo
x. The
Style V
alue
dete
rmin
es the
type o
f com
ma
nd
butto
ns app
ear o
n the m
essa
ge
box, a
s sho
wn in
Tab
le be
low.
Styl
Styl
e e V
alV
alu
esu
es
We
can
use n
ame
d consta
nt in
place
of in
teg
ers for the
secon
d arg
um
en
t
to make
the p
rogra
ms m
ore
read
able.
In fact, V
B6
will au
tomatica
lly sho
ws
up a
list of n
ame
s consta
nt w
he
re yo
u
can se
lect on
e o
f the
m.
Fo
r exam
ple,
you
rMsg
=M
sgB
ox( “C
lick OK
to
Pro
ceed", 1, "S
tartup
men
u”)
and
you
rMsg
=M
sg(“C
lick OK
to
Pro
ceed". vb
OkC
ancel,"S
tartup
Men
u”)
are the same.
Styl
Styl
e e V
alV
alu
esu
es
you
rMsg
is a variable that
holds values that are returned
by the MsgB
ox ( ) function. The
type of buttons being clicked by
the users determines the
values. It has to be declared as
Integer data type in the
procedure or in the general
declaration section.
Ret
Ret
urn
u
rn
Val
Val
ues
ues
and
an
d
Co
Co
mm
mm
and
an
d
Bu
tB
ut
ton
ton
ss
A function is sim
ilar to a normal
procedure but the main
purpose of the function is to
accept a certain input and
return a value, which is passed
on to the main program
to
finish the execution. There are
two types of functions, the
built-in functions (or internal
functions) and the functions
created by the programm
ers.
The general form
at of a function is
Fu
nctio
nN
am
e (arg
um
ents)
The argum
ents are values that are
passed on to the function.
Ex
Ex
am
am
ple
ple
::
Co
Co
nt.
nt.
To make the m
essage box
looks more
sophisticated, you can
add an icon besides the
message. T
here are four
types of icons available
in VB
201 0 as shown in
Table below:
Ex
Ex
am
am
ple
ple
::
Th
e T
he
Inp
Inp
utB
utB
ox(
ox(
) ) Fu
nF
un
ctioctionn
An
Inpu
tBo
x( ) fun
ction a
llow
s the u
ser to
ente
r a value o
r a messa
ge
in a
text
box.
use
rMsg
=M
icroso
ft.Visua
lBasic. I
npu
tBox(P
rom
pt, T
itle, d
efau
lt_te
xt, x-p
osition, y-po
sition)
use
rMsg
is a variant d
ata type
but typ
ically it
is declare
d as string
, which a
ccepts th
e
me
ssag
e inpu
t by th
e u
ser. The
argu
me
nts
are e
xplain
ed a
s follows:
Pro
mp
t- T
he m
essa
ge d
ispla
yed
norm
ally a
s a qu
estion
asked
.
Title
- The
title of th
e Inpu
t Bo
x.
defa
ult-text - T
he
defau
lt text th
at
app
ea
rs in the in
pu
t field w
he
re th
e
use
r ma
y chan
ge th
e me
ssag
e
acco
rding to
his o
r he
r wish
..
x-position
and
y-po
sition
- the p
ositio
n
or th
e co
ordina
tes o
f the inp
ut b
ox.
Co
Co
nt.
nt.
Su
Su
mmma
ma
ryry
You learned that a function is a
procedure that accepts an
input and returns a value,
which is passed on to the m
ain
program to finish the execution.
You also learned that the
format of a function is
FunctionN
ame (argum
ents).
you learned to use the
Msg () function to
produce a popup
message box to prom
pt
the user to click on a
button to continue the
execution.
you learned how to use the
InputBox to get the input
from the user.
Vis
Vis
ual
ual
Ba
Ba
sicsic201
201
00
Ch
apter 11
Strin
g
Fu
nctio
ns
Understanding the S
tring
Functions
Str
Str
ing
in
g
Fu
Fu
nct
nct
ion
ion
ss
We have learned about the basic concept of
function as well as the M
sgBox and InputB
ox
functions in Chapter 10. In fact, I have already
shown you a few
string manipulation functions in
Chapter 6; they are the Len function, the Left
function and the Right F
unction. In this Chapter, w
e
will learn other string m
anipulation functions.
Th
e Mid
Fu
nctio
n
The M
id function is to retrieve a part of text from a given
phrase. The form
at of the Mid F
unction is:
Mid
(ph
rase, po
sition
,n)
Co
Co
nt.
nt.
Where
ph
rase is the string from w
hich a part of text is to be retrieved. p
ositio
n is
the starting position of the phrase from
which the retrieving process
begins. n is the num
ber of characters to retrieve.
Exam
ple:
Private S
ub
Bu
tton
1_Click(B
yVal
send
er As S
ystem.O
bject, B
yVal e
As S
ystem.E
ventA
rgs) Han
dles
Bu
tton
1.Click
Dim
myP
hrase A
s Strin
g
myP
hrase =
Micro
soft.V
isual
Basic.In
pu
tBo
x(" En
ter you
r
ph
rase")
Lab
el1.Text = M
id(m
yPh
rase, 2, 6)
Co
Co
nt.
nt.
In this example, w
hen the user clicks the com
mand
button, an input box will
pop up asking the user to input a phrase. A
fter a phrase is entered and the O
K button is
pressed, the label will
show the extracted text
starting from position 2
of the phrase and the num
ber of characters extracted is 6, as show
n in F
igure below.
Th
e T
he
Rig
Rig
ht
ht
Fu
nF
un
ctioctio
nn
The R
ight function extracts the right
portion of a phrase. The form
at is
Microsoft.V
isualbasic.Right
(“Phrase”, n)
Where n
is the starting position from the
right of the phase where the portion of the
phrase is to be extracted. For exam
ple:
Microsoft.V
isualbasic.Right (“V
isual Basic”,
4) = asic
For exam
ple, you can write the follow
ing code to extract the right portion any phrase entered by the user
Th
e T
he
Left
Left
Fu
nF
un
ctioctionn
The Left function extracts the
Left portion of a phrase.
The form
at is
Microsoft.V
isualbasic.Lef
t (“Phrase”, n)
Where n
is the starting position
from the right of the phase
where the portion of the phrase
is going to be extracted. For
example:
Microsoft.V
isualbasic.Left
(“Visual B
asic”, 4) = V
isu
For exam
ple, you can write the
following code to extract the left
portion any phrase entered by
the user.
Th
e T
he
TriTri
m
m
Fu
nF
un
ctioctio
nn
The T
rim function trim
s the empty spaces
on both side of the phrase. The form
at is
Trim
(“Phrase”)
.For exam
ple : Trim (“ V
isual B
asic
”) = V
isual b
asic
The Ltrim
function trims the em
pty
spaces of the left portion of the
phrase. The form
at is
Ltrim(“P
hrase”)
.For exam
ple: Ltrim
(“ Visu
al
Basic”)=
Visu
al basic
The R
trim function trim
s the empty
spaces of the right portion of the
phrase. The form
at is
Rtrim
(“Phrase”)
.For exam
ple: Rtrim
(“Visu
al Basic
”) = V
isual B
asic
Th
e T
he
InS
InS
tr tr fu
nfu
nctioctionn
The InS
tr function looks for a
phrase that is embedded w
ithin
the original phrase and returns
the starting position of the
embedded phrase. T
he format
is Instr (n, original phase,
embedded phrase) w
here n is
the position where the Instr
function will begin to look for
the embedded phrase.
For exam
ple
Instr(1, “Visual B
asic”,”
Basic”)=
8
The function returns a
numeric value
You can w
rite a program
code as shown below
:
Th
e T
he
Uca
Uca
se se an
d
and
th
e th
e L
caL
case se F
un
Fu
nctioction
sn
s
The U
case function converts all the
characters of a string to capital
letters. On the other hand, the
Lcase function converts all the
characters of a string to small
letters. The form
at is:
Microsoft.V
isual Basic.U
Case(P
hrase)
Microsoft.V
isual Basic.LC
ase(Phrase)
For exam
ple,
Microsoft.V
isual Basic.U
case (“Visual
Basic”) =
VIS
UA
L BA
SIC
Microsoft.V
isual
Basic.Lcase (“V
isual Basic”) =
visual basic
Th
e T
he
Ch
r C
hr
and
an
d
the
the
Asc
Asc
fun
fun
ctioction
sn
s
The C
hr function returns the string that
corresponds to an AS
CII code
while the A
sc function converts an
AS
CII character or sym
bol to the
corresponding AS
CII code. A
SC
II
stands for “Am
erican Standard
Code for Inform
ation Interchange”.
Altogether there are 255 A
SC
II
codes and as many A
SC
II
characters. Som
e of the characters
may not be displayed as they m
ay
represent some actions such as
the pressing of a key or produce a
beep sound. The form
at of the Chr
function is: Ch
r(charco
de) and the
format of the A
sc function is:
Asc(C
haracter).
The follow
ing are some exam
ples:
Chr(65)=
A, C
hr(122)=z, C
hr(37)=%
,
Asc(“B
”)=66, A
sc(“&”)=
38
Su
mm
aryIn th
is cha
pter, you
lea
rned
how
to use
vario
us strin
g man
ipulation
functio
ns.you
lea
rned
how
to use the
Mid
functio
n to
re
trieve a
pa
rt of te
xt from a p
hrase.
you le
arn
ed ho
w to u
se the R
ight fu
nction
to e
xtracts th
e rig
ht p
ortion o
f a ph
rase
.you
lea
rned
how
to use the
left fu
nction
to
extra
cts the
left p
ortion o
f a p
hra
seyou
lea
rned
how
to use the
Trim
fun
ction
to
trims th
e em
pty spa
ces on bo
th side
of the
phra
se.you
lea
rned
how
to use the
the Ltrim
fun
ction
to trim
the e
mp
ty spa
ces o
f the
left po
rtion
of the
phra
se.
you le
arn
ed ho
w to u
se the R
trim fu
nction
to trim
emp
ty spa
ces o
f the
right p
ortion
of th
e phrase
.you
lea
rned
how
to use the
InStr fu
nction
loo
ks for a ph
rase
that is e
mbe
dde
d
within
the
origin
al phra
se and
retu
rns th
e sta
rting
position
of the em
bed
ded
p
hrase.
you le
arn
ed ho
w to u
se the U
case fu
nctio
n
to convert a
ll the
cha
racters of a strin
g to
cap
ital le
tters a
nd th
e Lca
se functio
n to
con
vert all th
e ch
aracters of a strin
g to
sm
all le
tters. you
lea
rned
how
to use the
Ch
r fun
ction
to return
the string
that co
rresp
ond
s to
an A
SC
II code
and
the
Asc fu
nction
to
convert a
n AS
CII cha
racte
r or symb
ol to
the co
rrespo
ndin
g AS
CII co
de
Vis
Vis
ual
ual
Ba
Ba
sicsic201
201
00
Ch
apter 12
Math
ematic
al
Fu
nctio
ns
Learn
ing
Ho
w to
use th
e M
athem
atical fun
ction
s
Mat
Mat
he
he
mat
mat
ical ical
Fu
nF
un
ctioctio
ns
ns
We have learned how
to write
code to perform m
athematical
calculations using standard
mathem
atical operators.
How
ever, we need to use the
built-in Math functions in V
B201
0 to handle complex
mathem
atical calculations.
Math functions are m
ethods
that belong to the Math C
lass
of the .Net fram
ework. T
hey are
similar to the m
ath functions in
Visual B
asic 6. The M
ath
functions in VB
2010 are Abs,
Exp, F
ix, Int, Log, Rnd(), R
ound
and the trigonometric functions.
Th
e T
he
Ab
Ab
s s fu
nfu
n
ctioctio
nn
The A
bs returns the
absolute value of a
given number.
The syntax is
Math
. Ab
s (nu
mb
er)
The M
ath keyw
ord here
indicates that the Abs function
belongs to the Math class.
How
ever, not all mathem
atical
functions belong to the Math
class.
Th
e T
he
Exp
E
xp
fun
fun
ctioctionn
The E
xp of a number x is the exponential
value of x, i.e. ex. For exam
ple, E
xp(1)=e=
2.71828182 the syntax is:
Math
.Exp
(nu
mb
er)
Th
e T
he
Fix
Fix
Fu
nF
un
ctioctionn
The F
ix function truncates the decimal
part of a positive number and returns
the largest integer smaller than the
number. H
owever, w
hen the number
is negative, it will return sm
allest
integer larger than the number. F
or
example, F
ix (9.2)=9 but F
ix(-9.4)=-
9.
Exam
ple:
Th
e T
he
Int
Int
Fu
nF
un
ctioction
/Ln
/Lo
g
og
F
un
Fu
nctioctionn
Th
e Int F
un
ction
The Int is a function that converts a
number into an integer by truncating
its decimal part and the resulting
integer is the largest integer that is sm
aller than the number. F
or exam
ple Int(2.4)=2, Int(6.9)=
6 , Int(-5.7)=
-6, Int(-99.8)=-1 00.
Th
e Lo
g F
un
ction
The Log function is the function that
returns natural logarithm of a
number. F
or example, Log(1
0)=2.302585. * Label1 show
s the
value of logarithm of num
1.
Th
e T
he
Ro
Ro
un
du
nd
( ) ( ) F
un
Fu
nctioctionn
The R
ou
nd
function
rounds up a number to
a certain number of
decimal places. T
he
Form
at is Round (n, m
)
which m
eans to round a
number n to m
decimal
places. For exam
ple,
Math.R
ound (7.2567, 2)
=7.26.
Exam
ple:
Th
e T
he
Sq
rS
qr
t t Fu
nF
un
ctioctio
nn
The S
qrt function returns the square
root of a number. F
or example,
Sqrt(400) w
ill returns a value of
20. You can use this function to
solve problems related to
Pythagoras theorem
. For exam
,
you may w
ant to find the length
of the hypotenuse given the
length of the adjacent side and
the length of the opposite side
of a triangle. The code in
VB
2010 is:
c=M
ath.S
qrt(a^2+
b^
2)
*As S
qrt is a function that belongs
to the Math class, w
e need to
use the Math keyw
ord. The
following code com
putes the
hypotenuse c given the length
of adjacent side and the length
of the opposite side of triangle.
Co
Co
nt.
nt.
Exam
ple
:
TrigTrigo
no
on
om
etm
etric ric F
un
Fu
nctioction
sn
s
Trigonom
etric functions handle problem
s involving angles. T
he basic trigonom
etric functions in V
isual Basic
2010 are Sin, C
os, Tan and A
tan. Sin is the
function that returns the value of sine of an angle in radian, C
os returns the value of cosine of an angle in radian and Tan returns the value of tangent of an angle in radian. A
tan returns the value of A
rc tangent, w
hich represents the value of the angle in radian given the value of tangent of this angle.
Exam
ple:
Su
mm
ary
In th
is chap
ter, you
learn
ed h
ow
to w
rite cod
e to
perfo
rm calcu
lation
s usin
g va
riou
s bu
ilt-in
math
ematical fu
nctio
ns in
VB
201 0.
you
learn
ed h
ow
to u
se the A
bs
fun
ctio
n to
return
the
abso
lute va
lue o
f a g
iven n
um
ber.
you
learn
ed h
ow
to u
se the E
xp fu
nctio
n to
express a
nu
mb
er in e
xpo
ne
ntial fo
rm.
you
learn
ed h
ow
to u
se the F
ix fun
ction
to tru
nc
ate the
decim
al p
art o
f a p
ositiv
e n
um
ber a
nd
retu
rn
the la
rgest in
teg
er s
malle
r than
the
nu
mb
er.
you
learn
ed h
ow
to u
se the In
t fun
ction
to co
nvert a
nu
mb
er into
an
inte
ger b
y tru
ncatin
g its
decim
al
part a
nd
the re
su
lting
inte
ger is
the la
rgest
inte
ger th
at is
sm
alle
r than
the n
um
ber.
you
learn
ed h
ow
to u
se the L
og
fun
ction
to retu
rn valu
e
of th
e natu
ral lo
garith
m o
f a n
um
ber
you
learn
ed h
ow
to u
se the R
nd
( ) fun
ctio
n to
ge
nerate
a rand
om
value b
etwe
en 0 a
nd
1.
you
learn
ed h
ow
to u
se Ro
un
d fu
nctio
n to
rou
nd
up
a
nu
mb
er to a certain
nu
mb
er of d
ecimal p
laces.
you
learn
ed h
ow
to u
se the S
qrt fu
nctio
n to
ob
tain th
e
squ
are roo
t of a n
um
ber.
you
learn
ed h
ow
to u
se the trig
on
om
etric fun
ction
s Sin
,
Co
s and
Tan to
co
mp
ute
the va
lues o
f sine, co
sine
and
tang
ent o
f an an
gle in
radia
n. Y
ou
also learn
ed
ho
w to
ob
tain th
e value o
f Pi u
sing
the
form
ula
Pi=
4xA
tan
(1)
Vis
Vis
ual
ual
Ba
Ba
sicsic201
201
00
Ch
apter 13
Fo
rmattin
g
Fu
nctio
ns
Learn
ing
ho
w to
use th
e
Fo
rmattin
g F
un
ction
s
Fo
rF
or
mat
mat
ting
tin
g
Fu
nF
un
ctioctio
ns
ns
The F
orm
at function is a very
powerful form
atting function
that can display the numeric
values in various forms. T
here
are two types of F
ormat
function, one of them is the
built-in or predefined format,
and the user can define
another one.
(i) The form
at of the predefined
Form
at function is
Fo
rmat (n
,
“style
argu
men
t”)
pr
pr
ed
ed
efi
efi
ne
ne
d
d
Fo
Fo
rmrmat
at
Where n is a num
ber and the list of style argum
ents is given in Table:
Co
Co
nt.
nt.
Exam
ple:
us
us
er-
er-
def
def
ine
ine
d
d
For
For
ma
ma
tt
(ii) The form
at of the user-defined F
ormat function
is:
Fo
rmat (n
, “u
ser’s form
at”)
Although it is know
n as user-defined form
at, we still
need to follow certain
formatting styles.
Exam
ples of user-defined form
atting style are listed in Table
Co
Co
nt.
nt.
Exam
ple:
Fo
rF
or
mat
mat
ting
tin
g
Usi
Usi
ng
n
g
ToS
ToS
trintrin
g
g
Met
Met
ho
dh
od
Other than using the F
ormat
function, has introduced
the ToString m
ethod to
format output. It is used
together with the
standard numeric form
at
specifiers such as “c”
which stand for currency.
Som
e of the most
comm
on numeric
specifiers are listed in
the table below:
Co
Co
nt.
nt.
Co
Co
nt.
nt.
Mo
rM
or
e e o
n
on
To
STo
Strintring
g
M
etM
eth
od
ho
d
The ToS
tring method together w
ith the
currency specifier “C” displays the output
with the currency sign $ and in tw
o decimal
places. The default currency is the currency
used by your computer system
; in this case,
it is the US
currency. If you are not sure of
what default currency your com
puter uses,
you can add the keyword
“CultureInfo.C
urrentCulture” to the ToS
tring
method as show
n in the example below
:
Fu
tureV
alue =
FV
.ToS
tring("C
", C
ultu
reInfo
.Cu
rrentC
ultu
re)
If you wish to display the output in different
currencies, you can use the keyw
ord” “C
ultureInfo.CreateS
pecificCulture
together with the culture identifiers.
For exam
ple, if you want to display
the output in Japanese currency, you can use the ja-JP
culture identifier, as show
n in the example below
:
Fu
tureV
alue =
FV
.ToS
tring("C
",
Cu
ltureIn
fo. C
reateSp
ecif
icCu
lture(“
ja-JP”)
The output is in Japanese currency sign ¥
instead of the $ sign.
Su
mm
ary
In this chapter, you learned
how to form
at your output
using the Form
at and the
ToString functions.
you learned how to use
various formatting styles
you learned how to form
at output using ToS
tring output.