vb-ch1 1
vb-ch1 1
vb-ch1 1
1
Gettin g Starte d with
Visual Basic 6.0
his chapter concentrates on the programming aspect~ and fundamentals of Visual Basic
T and emphasizes on teaching the various Visual Basic software tools.
I Objeawu
0 Visual Basic 6.0 Programming Environment
0 Working with Forms
0 Developing an Application
0 Variables Data Types and Modules
0 Procedures and Control Structures
0 Arrays in Visual Basic
I A>
~.1 [ INTRODUCTIO N TO VISUAL BASIC
f
W-isual Basic is an ideal programming language for developing sophisticated professional
flpplications for Microsoft Window~ It makes use of Graphical User Interface for creating
11 Jbust and powerful applications. The Graphical User Interface as the name suggests, uses
illustrations for text, which enable users to interact with an application. This feature makes
lt easier to comprehend things in a quicker and easier way.
I t oding in GUI environment is quite a transition from the traditional, linear programming
methods where the user is guided through a linear path of execution and is limited to a small
~et of operations.) ln a GUI environment, the number of options open to the user are much
eater, allowing more freedom to the user and developer. Features such as easier compre-
ension, user-friendliness, faster application development and many other aspects such as
troduction to ActiveX technology and Internet features make Visual Basic an interesting
~ ol to work with.
I( Visual Basic was developed from the programming language-BASI C in the 1970s,
~icrosoft started developing ROM-based interpreted BASIC for the early microprocessor-
based computers. In 1982, Microsoft QuickBasic revolutionized BASIC and was legitimized
2 Visual Basic 6.0 Programming
Visual Basic is initiated by using the Programs Option ➔ Microsoft Visual Basic 6.0
Visual Basic 6.0. By clicking the Visual Basic 6.0 icon, we can view a copyright scr ~
enlisting details of the license holder of the copy of Visual Basic 6.0 . Then it opens inten
screen as shown in Fig 1 .1 with interface elements such as Menubar Toolbar and the No a
Project dialog box. These elements permit the user to build different types of Visual Bas1ce~
applications .
..., Projectl - Microsoft Visual Basic (design) '!I~ fJ
EiJe ~dit ~ f1oject FQrmat Qebug Bun Q!lery Diagram Iools ~-Ins ~ ttelP
11
j~ · 1:1 ·'ffl l~ liiil i? ~ e "' I<, , .. , ► u ■ J S~ c8 '~f~ 6l ~
xj
..,fl I IUl\,l...t
i
I
1~ ~A MriHII ActiveX EXE ActiveX Dll Act1veX
"'
~,-. ~,·.
Control
~ r- ~ #.
VB Application
#.
VB Wizard
~
Data Project
~
IIS Application
t!efp
~
VB Enterprise cl
4 Fig. 1.1
~
I
Adds a new Module Add Module command on the Project menu
~ Saves the current Project Save Project command on the File menu
(Contd)
--
,4 VisuAI 1::las1c 6.ll Programming __
-
Explon~r
Start com mand on the Run menu
~ Sturt s Rn application in
dt'sign modl'
Break comman d on the Run menu
~ Used for debuggin g, stops
executio n of a program
while running
~ Stops· executio n of an
End comman d on the Run menu
application and returns
to the design mode
:: j Toggles breakpo int on Toggle Breakp oin' on the Debug menu
menu
i}, _j Displays the value of Quick Watch comman d on the Debug
the current selection
in the code window
j<.::111 Traces through each Step Into comman d on the Debug menu
line of code and steps
into procedur es
c~ I Executes one code Step Over comman d on Debug menu
procedur e or stateme nt
at a time in the Code window.
1!, I Displays the Menu Editor Menu Editor comman d on the Tools menu
Toolbox
Toolbar is contains a set of controls that are used to place on a form at desi~ time ther~b(
creating the user interface area. Additional controls can be included in the toolbox by usin~
th e Compon ents menu item on the Project menu. A Toolbox is represen ted in Fiir t. 2.
• The I\iinter helps tu move and resize the controls and Form.s.
\
Getting Started with _Visual B~s 1c 6 0 5
\
, ~
\
.. Generol I
Pointer I ft u 1'1c1urcBox .,. I
I
FranJl'
\
r¥l LJ ( 'on1111u1idBut1011
p r. Ort1on Button
Check box
\
~ ~ Lisi Box
"
l'0111huBux
I IScrojq U:1r. jJ .ti
.cl
\ ~ VScrollB ar
\ ' '
'J:iincr
0 ' D DrivcLi st Box
\ .
DirL1stBox
'
□ ~ FileListB ox
.-
Shape it>)
' Line .......
Image
\
'1)]~ \ D\ta
•1···1·..
f11i11!i=
OLE .,"tmi
~ Fig. 1.2
• Label displa ys a text that the user canno t modify or intera ct with.
• Frame control serves as a visual and functional contai ner for controls.
• CheckBox dis~lays a True/F alse or Yes/No option .
• TextBox is a control used to display messa ge and enter text.
• The ListBox displays a list of items from which a user can select one.
an item
• ComboBox contai ns a TextBox and a ListBox. This allows the user to select
from the dropdown ListBox or to type a selection in the TextBox.
specified
• HScro llBar and VScrollBar controls allow the user to select a value within the
range of values.
• Timer control execut es timer events at specified interv als of time.
yed.
• DirListBox allows the user to select directories and paths, which are displa
• Shape control adds a shape (rectangle, square or circle) to a Form.
• Image control is used to displa y icons, bitma ps, metafi les, etc.
from other
• OLE control is used to link or embed an object , displa y and manip ulate data
Windows based applic ations .
as a visual
• Pictur eBox displa ys icons/ bitmap s and metafi les. It displa ys text or acts
contai ner for other controls.
• Comm andBu tton carrie s out the specified action when the user chooses it.
to select
• The Option Button control which is a part of an option~ ou£.!llows the user
one option even if it displa ys multip le choices.
~i~ng[J___ _ _ _ _ _ _ _ _~~-~~-- -~
6 v,~~~ !'·
Visual Basic:_16~0 P~ro'!lg"'.ra~mr,rm
. IJ__!'
. dis lays . disk drives and allows the user to select one f
the valid
The DriveL1stBox p 0
.
• them. . . la s a set of files from which a user can select the desired one.
• The FileL1stBox d1sp : ai ht line to the Form. . .
st
a theg user to connec t to an ex1stmg database and dispJ ay
control drawsbles
• L.me .
• Data control en~
information from. it.
d that can be cus tomized and controls, graphics and pictures can
Form serves as a wm ow
also be added to it.
4 Fig. 1.3
Properties Window
[ The Properties window is docked under the Project Explorer window. The Prop~rties
Window exposes the various characteri stics of selected objects. Each and every Form m an
application is considered an object. Now, each object in Visual Basic has character istics SUCh
as colour and size. Other characteristics affect not just the appearan ce of the object but the
way it behaves too. All t~~ chg_ract_e ristics of an object are calle,d its properties . Thus, a
Form has properties and any controls placed on it will have propertie s too. All of these prop-
are displayed in the Properties window. Figure 1.4 shows the Propertie s window of a
erties object.
Form
Getting Started with Visual Basic 6.0 7
(Name) Form 1 •
r
Appearance 1 - 3D
AutoRedraw False
BackColor ' D &H80000C
· BorderStyle 2 - Sizable
Caption Bl
· ClipControls True
. ControlBox True
DrawMode 13 - Copy Pel
· DrawStyle 0 - Solid
DrawWidth 1
.Enabled True
FillColor I &HO000OC
__ - 1'). FillSty'le 1 - TransparE
e 8 4 Fig. 1.4
. .
Object Brows er
and.m ethods
\ The Object Brows er allows us to browse throug h the VArio11s proper ties, e~ents
the View menu
~ hat are made avJ!.ill;!_ble to U §. It is accessed by selecting Object Brows er from
s and classe s
oroy pressi ng the key F2.fVrhe leftc olumn of the object brows er lists the object
been refere nced
that are availa ble in the ,projects ~hat are opened and the controls that have
or class that we
in them. It is possible for us to scroll throug h the list and select the object
wish to inspect. After an object is picked from the Classe s'list, we can see its
members (prop-
erties, metho ds and events ) in the right column.
I A proper ty is repres ented by a small icon that has a hand holdin g a piece of paper. Meth-
lightn ing bolt
ods are denote d by little green blocks, while events are denote d by the yellow
icon. ) ) f>1l
Properties, Methods and Events
These object s
All the controls in the Toclbox except the Pointe r are objects in Visua l Basic.
have associ ated proper ties, metho ds and events .
with certai n
Real world objects are loaded with proper ties. For examp le, a flower is loaded
prope rties.
colour, shape and fragrance. Simila rly, progra mmin g objects are loaded with
6 0 programm~
3 v,sual J 85tc - ·. _:,_.:;---
... ::- -- . b·ect. Pro per ties def ine the charact-ft
"b te of a pro gra-mmmg. O es ~ 4'11'. h.
w ic h I·t be h ave s ~r.
·
tne wa y m
. rty is a narne d attn u som et1m F'
.
A p1ope b·ec t such as size, colortie ur, etc. or E ble d Fon t, M u It·1 1-m ·
e,
T . . . or
ext , V1sibl
s such as na
1st1c of an J ° accepts prope _
example a TextB~xe discuss ed below:
'
.
e,
.
ena ble d or dis abl ed at run tim e depend
Wl·dth' etc. These ar tv the TextBox to be in
allows
• Enabled pr~p_e r ., t to True or False. g
h d1t1 t B x
on t eco n 0n tse particular font in · the Tex O ·
• Font property se s a t and dis pla y mu ltip le lines at run
the TextBox to accep
Multi Line property allows
• .
time. rtic ula r tex t in the control.
extBox control set s a pa .
• Text property of the T . the object at run tim e.
• Visible property is used to hide t the . .
desired wid th at des ign tim e.
Width property sets the TextBox o
• d . tim e pro per ties tha t can be set
Th ·
perties tha t are d1sc d bove are esig n at the
usse a . d Bu t cer tain pro per ties · tb
. e ~;; e by selecting the Properties w1dnCo can no e set at de-
des1gn w. t y pro per ties of a For m can not
. t· example, t he Curr e nt X an urr be set at
sign ·ime . For .
en
X Cu rre nt y prope rt·1es are dis cus sed in eta1 m
d ·1 . Ch te 3
ap r .)
the design time. [Current ' . .
d b·e cts For exa mp le, a cat 1s an obJect. It.s
A method is an act1.0n t h a t can be performe on o J . . h
. . l d 1 . bl thr ee pou nds we ig t, etc. A complete
rop erti es mig ht me u e ong wh ite hai r ue eye s, .
P ' ·t oks but sho uld also inc . 1d
definition of cat mus t ~~ t only encc ompass on 1 s 1o ' .
u e a complete
1
itemization of its actiV1t1es. There1ore , a t' methods mig ht be move, JUID
ca s P, p ay, breathe,
etc. . . . a method is a con nec ted or bui lt-i n pro
Similarly, in obJect-onen~d p:o r:~ mm cedure,
~ some action on a par ticu lar object.
a blo_ck of cod~ tha t can A method
reqmres an obJect to prov~ed
1
I~~o e wi; h1: ~:n tex t. For exa mp le, the
wo rd Move has no mean-
ing in Visual Basic, but theefollem
owing sta tem ent, performs a ver y pre . t"
cise ac 10n.
Textl.Move 700, 400
The TextBox control has other associated
methods suc h as Ref res h, Set Foc us, etc
• The Refresh method enforces a comple .
te rep ain t of the con trol or a For m. For
Textl .Refresh refreshes the Text Box. example,
• The SetFocus method moves the focus
to the control. For exa mp le, Tex tl .Se tFo
the focus to TextBox control Tex tl. cus sets
Eve nt Driven Pro gra mm ing
Visual Basic programs are bui lt around eve
nts. Eve nts are var iou s thi ngs tha t can
a program. This will become clearer when happen in
( stu die d in con tras t to pro ced ura l pro gra
procedural languages , a written applica mm ing. In
l tion is executed by che cki ng for the
I cally through the program statements, one pro gra m logi-
afte r ano the r. For a tem por ary pha se,
may be transferred to some other point the control
in a program. While in an eve nt dri ven
the program stat em ent s are executed onl application ,
y when a par ticu lar eve nt cal ls a specifi
code tha t is assigned to the event. c par t of the
Let us consider a T,extBox control and
a few of its ass oci ate d eve nts to und
concept of event driven programming. The ers tan d the
TextBox control sup por ts var iou s eve
nts such as
Getting Started with Visual Basic 6.0 9
n
Change, Clic k, Mou seM ove and man y more
that will be liste d in the Prop erties drop -dow
list in the code window for the TextBox cont
rol. Few of them are give n below.
when ther e is a chan ge in the con tent s of
• The code ente red in the Change even t fires
the TextBox.
rol is clicked.
• The Click eve nt fires whe n the TextBox cont
is moved over the TextBox .
• The MouseMove eve nt fires whe n the mouse
ed with diff eren t controls and forms, som e
As exp lain ed above, seve ral even ts are asso ciat
a few bein g specific to each con~
of the even ts bein g common to mos t of them and _.,/
I. Points to ,Ponder
I
1 1.3 WO RK ING WIT H FORMS
I
Border Styl e
r
Some of the avai labl e sett ings can cau se othe
For ms can hav e a vari ety of type s of borders.
are avai labl e are liste d in Tab le 1.2:
For m prop ertie s to be ignored. Th_e bord ers that
10 Visual Basic~ -~ ~rog ra~- - - - - --
Table 1.2
---
-----:Jlf_~- -=- - =- - =- - =-~~~s;~;.~~~~~~~=----
Option
None
Purpose
No border is shown . In additio~, t h e Minimize
button , Maximize button, ~he title bar and Close
-----
Caption
The title for the windo w is stored in the Captio n prope rty. The captio n
appea rs below the
form's icon when the form is minim ized.
Control Box
This proper ty determ ines wheth er the Contro l box, availa ble by clickin
g the upper left cor-
ner/ico n of a window, will be shown or not.
Icon
This prope rty specifies the icon for the windo w in the upper left corne r
of the window.
Mouse Pointe r
This proper ty sets the value that indica tes the type of mouse pointe r
displa yed when the
mouse pointe r appea rs over a partic ular area of the object at runtim e.
Max Button
This proper ty indica tes wheth er the Maxim ize button should be shown
and the Maximize
choice made availa ble in the Contro l Box menu.
MD/C hild
This prope rty specifies if this windo w must be shown within a multip le
docum ent interface
(MDI) windo w.
MinBu tton
This prope rty indica tes wheth er the Minim ize button should be shown
and the Minimize
choice made availa ble in the Contro l Box menu.
Getting Started with Visual Basi~ 6.0 ~
---- ----
Moveable
This is a property introduced in Visual Basic 5. By setting it to False , it is possible to
nd
preve~t the us~r fro~ moving the window manually. This is useful for splash screens a
other mformat10nal drnlog boxes that are shown and dismissed quickly.
StartUpPosition
This is a property introduced in Visual Basic 5 so that instead of writing code to position your
window, you can pick a starting position from this drop-down menu. The available choices
are given in Table 1.3:
Table 1.3
Option Purpose
Manual Any positioning must be done in the Layout window.
CenterOwner The forw should be shown in the center of the form
that owns it .
CenterScreen The form should be shown in the center of the
user's screen.
Windows Default It lets Windows decide where the form should be
shown
WindowState
V
This property indicates whether the window is shown normally, maximized or minimized. It
is possible to pick a starting state for your Form at design time so that when you show the
window, it comes up in that state.
0isplaY-i.ng Forms
The following sections give a brief description about displaying and loading a Form object.
Show Method
The Show method is used to display the Form object. For example, to display the form
frmCalculator, the following code is written.
FrmCalculator.Show
Using Load Statement
The Load statement is used to load a form or control into memory but does not display it. To
load the form frmCalculator, the following code should be entered.
Load frmCalculator
Hiding and Unloading Forms
--- ~- - -- --- - _,,.,,,A
The following sections discuss briefly the steps required to hide and unload forms.
12 Visual Basic 6.0 Programming
4 FiQ., 1,5
14
~ - -
\llsual Basic 6.0 _Pr o~ r~~
- -- - -- - - - -
CASESTUDY
. mmodities be lon gin g to dif fer en
M & Co is a famous sup en na rk t which se11 s co d d
t cate .
S · . e . t· tio ne ry t
rea yma e ga rm en s, etc. Th goli
. · appliances, s a
tha t include groceries. e1ectI0~ ' es
1c . . t·
ers of the supermarket are gomg ute riz ing the ir op era wn s. Durm . e OW}i
g thi s Pr .
m for ~dompd
. ·t
the following reqmsi es nee d to be cons1 ere . OCess
d f d t ·y lis t fro m the se t of
• To select the mo e O pa~m en t an ca egoi av ail ab le choice
• To update the category hs t as he n the new sto ck arr ive s. s.
and w d up da te it
• To maintain a database of reg
ular cuSt0mers an ·
• To enlist the availability of the
items. . .
• To give a lis t of choices for the t ha vin g dif fer en t siz es.
pro duc s
• To choose the mode of payment.
• To display messages on entry
and exit of the customers.
• To record the date and the day
of transaction.
• To choose the day of delivery of
goods to a customer.
• To maintain a record about the
sales made on various cat eg ori
• To access details of the transa es ov er a year.
ctions and all activities of the su
How Visual Basic can be used to pe rm ark et.
att ain these req uis ite s ha s be en
ples throughout the book. elu cid ate d using exam.
Example 1.2 Let us consider
a simple display program usi ng
example. the TextBox control in this
A New Standard EXE Project ite
m is selected from the File me
Project dialog box. The sta nd ard nu tha t displays a New
EXE is chosen for normal applic
sponds by displaying the Project ations. Vi sua l Basic re-
and Form windows as shown in
Fig. 1.6.
Iii Pm jec tl · Forml (Form)
• pil [ij £!
□
Iii Forml
. .. ... . . .. ... . .. . .
'
I · . ► A
4 Fig.1.6
Though no changes hav
stage of the design. When ea been made to the F . .
project is saved t or :, it
f~e. The project file ha s .VBP ext is be tte r to save the project at the
ens ion a~d early
for building the Project. The Fo ~; co es ~re ~aved, na ~e ly ProjeeHiie a n
rm file co t . 1,1-tams mformati ~
.FRM extension. The Save Projec on tha t Visual Basic uses
t comman~ ~ms {nformation ab
responds by displaying a Save Fil ou t the Form an d has the
e As dialog ~o:e a:cted fro ~ th~
File me . Visual Basic
shown m Fig. 1.7. A nu file na me called
Getting Started with Visual Basic 6.0 15
--
ed on. Visual 8 aH1c the n <.hsp iays a
Displ ay. fr~i is given and the Save butto n has to be click
File As dialog·box . The proje ct file
Save ProJec~ As dialo g box, whic h is simi lar to the Save
is saved as Disp lay .vbp.
~ combo ti menu
~ commond,alog tl Mousedown
~ conl4.,ra_~ ~ Mousemove
~ customd1alog ~ scrollbar
~ Dialog
t'.1.list
s~ :I
)4 '
.:] -~.. ]
H"' I
4 Fig. 1.7
Property Setting
Object
Caption The Display Prog ram
Form
Name FrmD ispla y
~--~
....
,, ' ? ·~ , _ ,,
... ·
,, ·-
4 Fig. 1.8
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdDisplay_Click()
S.O 17
Getting Started with Visual Basic
-. , \, : 1
Fil l in the bla nk s
saved wit h an extension ' ..v ~ : ~ •
1
1. Visual basic project files are
ension ..!' {.2 I A . \
2. Form files are saved with an ext the Fo rm .
j et.k nam e of the selected object ass oci ate d wit h
3. The Ob box dis pla ys the
-------
1 - 1.5 VARIABLES, DATATYPES AN Q.. MOD.UL_E.S.-
By default Visual Basic variables are of the variant data type. The variant data tYPe can
store numeric, date/time or string data. When a variable is declared, a data type is supplied
for it that determines the kind of data it can store. The fundamenta l data types in Visual
Basic including variant are integer, long, single, double, string, currency, byte and
boolean~Visual Basic supports a vast array of data types. Each data type has limits to the
kind of information and the minimum and maximum values it can hold. In addition, sowe
types can interchange with some other types. A list of Visual Basie's simple data types are
given in Table 1.5.
Table 1.5
Type Name Value Range
Byte 0 to 255
Boolean True or False
Integer -32, 768 to 32,767
Long
, -2,147,483,648 to 2,147,483,647
Single 3 45
-3.402823 * 10 to -1.401298 * 10 for negative values.
1.401298 * 10· to 3.402823 * 10 38 for positive values.
45
Variables
Variables are used for storing values temporarily. A defined na mmg· t t h to be fol-
·1 · • bl A s ra egy as
lowed wh 1 e nammg a var1a e. variable name must begin with an alphabet letter and
should not exceed 255 characters. It must be unique within the s ame scope. It should not
. . h t er l'k _ & , 1. , #,@or$.
{]/70,
contam any spec1a1 c arac 1e
-
Getting Started with Visual Basic 6.0
---· - --- - - - ---
19
ure static,
return t~e same val~e with which it was called. To make all variables in a proced
given in the
the Static keyword 18 placed at the beginning of the procedure headin g as
statem ent below.
Static Function Runni ngTota l ( )
andBu tton that
Example 1·3 . The following is an example of an event procedure for a Comm
counts and displays the numbe r of clicks made.
Private Sub Commandl Click()
Static Counter As Integer
Counter= Counter+ 1
Print Counter
End Sub
t value of zero.
The first time we click the CommandButton ' the counter starts with its defaul
Visual Basic then adds 1 to it and prints the result.
Module-Leve/ Variables
are declar ed
A module-level variable is available to all the procedures in the module. They
using the Public or the Private keyword.
Public intPermanent As Integer
Private intTemp As Integer
the applica-
Declaring a variable using the Public keyword makes it available throug hout
en Dim and
tion even for the other modules. At the module-level there is no difference betwe
variab les
Private, but Privat e is preferred because it makes the code easier to read. Public
es can share
should not be declared within a procedure. Public variables in different modul
public intege r
the same name and they can be differentiated in code. For example, if the
be referre d as
variable intY is declared in both Forml and Modulel of a project it can
Forml .intY and Modulel.intY.
Public vs Local Variables A variable can have the same name and differe
nt scope. For ex-
declar e a local
ample, we can have a public variable named R and within a procedure we can
local variab le
variable R. References to the name R within the procedure would access the
and references to R outside the procedure would access the public variable.)
/J)
1--- ---- - - - - - - IV. Points to Ponder
State True or False
1. String is a data type that can be used to declar e a text of
maxim um 10 million
characters.
2. A module-level variable is available to all the procedures in the module.
ure and
3. Static variables are not re-initialized each time Visual Basic invokes a proced
thus retains or preseryes value even when a procedure ends.
les and
4. The Dim statem ent checks in the module for usage of any undeclared variab
reports an error to the user.