An Introduction To Programming Using Visual Basic 2010
An Introduction To Programming Using Visual Basic 2010
An Introduction to
Programming Using
David I. Schneider
with
Microsoft<!
Visual Studio®2010
Express Edition DVD
Help is here. Now.
VideoNotes are quick video tutorials that show you how to solve a
problem step-by-step as if you were in your instructor's office.
With the purchase of a new copy of this textbook, you immediately
have access to Video Notes ~ tutorials and the Student Solutions Manual.
Use a coin to scratch off the coating and reveal your student access code. Do not use a
knife or other sharp object as it may damage the co de.
Note to Instructors: VideoNotes and an Instructors Solutions Manual for this title are available in the Instructor
Resource Center. Contact your Pearson representative 1j you do not have IRC access.
IMPORTANT: The access code on this page can only be used once to establish a subscription to the
premium content for Schneider, An Introduction to Programming Using Visual Basic
2010, Eighth Edition. If the access code has already been scratched off, it may no
longer be valid. If this is the case, follow steps 1-3 and select "Get Access" to purchase
a new subscription.
Some Common Commands
(keyl +key2 meam "llold down keyl while pressing key2.")
(l<.e)•l/key2 means "Release keyl before pressing key2.")
Controls
Tab Cycle forward through controls
Shift+ Tab Cycle backward through contro ls
Double-clic k obJect Create a template for object's default e\·ent procedure
arrow key Move selected control in the Form Designer
Crrl +arrow key Move selected control to align with another contro l
Shift+amiU.' key Resi ze selected control in the Form Designer
Delete Remove the se lected control
Toolbox
Click on upright push pin Collapse Toolbox into a tab at left side of the screen
Click on reclining push pin Keep Toolbox permanent ly displayed
AN INTRODUCTION
TO PROGRAMMING USING
EIGHTH EDITION
David I. Schneider
University of Maryland
Prentice Hall
Boston Co lu mbus India napo lis New York San Francisco Upper Sadd le River
Amste rdam Cape Town Dubai Lond on Mad rid Milan Munich Paris Montrea l Toro nto
Delhi Me x ico C ity Sao Paulo Sydney Hong Kong Seou l S ingapore Taipe i Tokyo
Vice President and Ed ito ri a l Director, ECS: Marcia J. Horto n
Executive Ed ito r: Tracy Dunkelberger
Ass istant Editor: Melinda Hagge rty
Editoira l Ass istant: A llison Michae l
Vice President, Production : Vince O 'Brien
Sen ior Managing Editor: Scott Disa nno
Producti on Li aison: Irwin Zucker
Production Edi tor: Sangee tha Parthasara thy, Laserwords
Seni or Ope rations Specialist: A lan Fisc her
Art Director: Kenn y Beck
Cove r Des igner: Laura C. Ierardi
Cove r Image:© lmages.co m/Corbis/M ark Shave r
A rt Editor: G reg Dull es
Media Editor: Daniel Sand in
Co mpositi on/ Full -Se rvice Projec t Manage ment: Lase rwords, Inc.
10 9 8 7 6 5 4 3 2 I
Student Edition
Prentice Hall ISBN-1 3: 978-0- 13-212 856-8
is an imprint of ISBN-1 0: 0-13-21 2856-X
In tructor Edition
-------
PEARSON
www.pearsonhighered.com
ISBN-1 3: 978-0- 13-255 284-4
ISBN-1 0: 0-13-2 55284- 1
. .
. · Guide to VideoNotes ·
,,,. .
www.pearsonhighered.com/Schneider · ..... " . .. .
Chapter 4 Decisions
Relational and Logica l Operators 105
If Blocks 112
Select Case Blocks 132
Grading Sys tem (Rep resentative Exampl e of Homework Exercise 27) 141
Chapter 7 Arrays
Filling Arrays 26 1
Array Methods 263
UNQ 282
Presidents (Repre entative Example of Homework Exercise 35 ) 294
Two-Dimensional Arrays 320
Chapter 10 Databases
Introduction to Databases 45 8
Querying Tables 464
Editing Databases 479
Richard's Ca tering (Represe nta ti ve Example of Programming Project 1) 487
vii
v iii • Gu ide to App licat ion Top ics
General Interest
Animati on , 443, 449 O ld McDona ld H ad a Farm, 188
America n H ea rt Assoc ia ti o n recomm endati on, 155 Pa lind rome, 252, 28 1
Anagram, 293 Phases of the moon , 424
Ana lyze grades, 246 Phys ic ian 's abbrevia t ions, 142
Analyze a S hakespea re sonnet, 280 Pig latin , 127
Bachelo r degrees conferred, 344 Populati on growth , 229
Body Mass l ndex , 1 73 Popu lation of large c ities, 467,474 , 482, 564-8, 572
Caffe ine absorpt ion, 25 1 Pres ident ia l eligibili ty, 15 2, 559
Ca lcu late age, 88, 89, 128 Principa l languages , 449
C hain-lin k se ntence, 28 1 Proverbs, 215
C loud iness desc ri ptors, 140 Quiz, 113, 126, 127, 134, 189
College ad mi ss ions, 157 Qwerty words, 242
College cred its, 305 Rad ioactive decay, 229, 241
Co llege majors, 448 Rating of hurri canes, 173
Earli est co ll eges , 300, 303, 387 Spread of an ep idemi c, 453
C rayola crayo ns, 279, 365 S upreme Court justices, 3 16,317, 354,356 ,365,56 0
Declarat ion of Indepen dence, 97 The Twe lve Days of C hri stmas, 3 17
Determi ne day of week, 97 Times Squa re ba ll , 424
Dialing a telephon e, 347 Training heart rate, 82, 173
Distance between c ities, 320,32 1, 560 U .S . cities, 3 12
Distance from a storm, 82 U .S. presiden ts, 127, 134, 142, 263, 264, 278, 279,
Draw flags, 446, 449
285,293 ,352,35 3,356,3 64,365, 386,409
Famous peop le, 3 18 U.S . Senate, 387,397
Freshma n li fe goa ls, 448 U.S. states, 141 ,244,245,249, 250,268 ,279,28 2,
Game of Life, 346 287,3 14, 3 15,350, 358,359 ,365,36 7,384, 386,
GPA, 214 516,550
Idea l weight, 24 1 Un ited Nations, 294, 296, 297, 299, 474, 560
Language trans latio n, 342 Un ive rsity rankings, 320, 329
Leap yea rs, 127, 174 Voting machine, 452
Month ly prec ipitati on, 330 Vowe l words, 166
Movies, 127, 145, 2 19, 478, 479,4 5 Weather beacon, 11 5
Nutritio na l content of foods, 322
Mathematics
A reas of geo metric shapes, J 41, 173, 52 7 Cu rve grades, 342
Calculat e a range , 227, 250, 280, 534 Factoriz ation, 22 7
alc ulate a su m, 240, 278, 279, 280, 283, 38 1 G reatest common divisor, 227
Calcu late an average , 84, 127, 174, 188, 240, 246, Magic sq uares, 330
263,26 ,278, 279,280 ,293,33 0,3 42, 38 1, 435, Mean, 280, 342
488,507 ,53 4 Med ian, 294, 330
Calcu lato r, 100, 520, 534 Projectil e mot io n, 67, 252
Calcu late with fraction , 507, 516 Quad rat ic formu la, 156
Coeffic ient of restituti on, 227 Standard dev iati on, 250, 280, 342
Con ve rt percenta ge to dec imal, 83 Tempera ture con ve rsion, 16 1, 227, 424, 559
Conve rt units of length, 100,341 ,409
Guide to VideoNotes v
Preface xiii
Acknowledgments xix
Summary 53
3.2 Strings 68
Summary 98
ix
X
• Co ntents
Summary 154
Programming Projects 154
Summary 214
Programming Projects 214
Summary 251
Programming Projects 251
Summary 340
8 .3 XML 382
Summary 396
Summary 450
Summary 486
Summary 535
Summary 571
Appendic es 575
Appendix A ANSI Values 575
Index 699
PREFA CE
ince its introdu ction in 199 1, Visual Bas ic h as beco me one of the world 's most wid e-
S ly used programmin g languages. The latest incarnation, Visual Bas ic 2010, further re-
fines the language and ex tends fea tur s such as Language Integrated Que ry. Visual Bas ic
programme rs are enthusias tica ll y embrac ing VB 2010's powerfu l capabilities . Likewise,
stude nts lea rning their first programmin g language will find VB 20 10 the ideal too l for
und erstanding the deve lop ment of co mpu te r programs.
My obj ectives in writing this tex t are as follows:
1. To develop focused chapters. Rather than cove ring many topics superficially, I con -
centrate on important ones and cover them thorough ly.
2. To use examjJles and exercises that students can relate to, apjJreciate, ancl feel comfort-
able with. I frequently use real data. Example do not h ave so many embellish -
ments that they distract students from the programmin g techniques illustrated.
3. To produce compactly written text that students will find both readable ancl informative .
The main po ints of each topic are discussed first, and then peripheral details are
presented as co mments.
4. To teach good programming practices that are in step with modern programming method-
ology . Problem-so lv ing techniqu es and structured programm ing are discussed ea rl y
and used through out the book. The style follows object- oriented programmin g
principles.
5. To jJrovide insights into the major ajJplications of computers.
VideoNotes. VideoNotes a re step-by-s tep video tu torials spec ifica lly des ign ed to enhance
the programming conce pts prese nted in the eighth edition. Stud ents can view the entire
problem-sol ving process outside the classroo m, when they need help the most. A
Vid eoN ote icon in the margin of the tex tbook alerts the reader that a topic is discussed in
a video. A lso, a G uide to Vid eoN otes in th e front of the book summarize the difD rent
videos fo und in the tex t . N ea rly 50 VideoN otes for this edition are avai lable at www.pear-
so nhighered .co m/schneider. See the Stud ent Resources secti on later in the Preface for in-
formation on how to access VideoN ote .
Exercises for Most Sections. Each section that teaches programmin g has an exe rcise se t.
The exe rcises reinforce the understandi ng of the key ideas of the section, and they challenge
the student to ex plore applications. Most of th e exercise se ts requ ire the stud ent to trace
programs, find errors, and write programs. The answers to all the odd-numbered exercises in
C hapters 2 through 8 and se lected odd -numbered exercises from C hapters 9, 10, 11, and 12
are given at the end of the text. Screen captures accompany most programming answers.
xiii
x iv • Preface
at the end
Practice Problems. Practice Problems are ca refully selected exe rc i es located
ing the exer-
of a section, just before the exe rcise se t. Co mplete solution s are given follow
confusi ng o r are
c i e set. The practice problems ofte n focus o n points that are poten t ially
them. Read rs should seriousl y attemp t
best apprec iated after th e stud ent has worked on
o n to the exerc ises.
the prac tice problems and tud y the ir olution s before mov ing
ming
Programming Projects. Beginni ng with C hapter 3, eve ry ch apter co nta ins program
in the business
projects. These projects refl ec t the va riety of ways that comput ers are used
-interes t top ics. The large num-
co mmunit y, and they a lso prese nt some games and general
to adap t th e
ber and range of d ifficulty of the program ming projects prov id e flex ibility
in later chapter s
co urse to the student s' interest s and ab ili ties. Some program m ing projects
can be ass igned as end-of- the-sem ester projects.
points of
Comme nts. To avo id breakin g the flow of the present ation, ex tensio ns and fine
n.
new top ics are deferred to the "Comm ents" portion at the end of each sectio
ming app li-
Case Studies. Each of the three case studies focuses on an impo rtant program
top-dow n ch arts
cation . The problem are analyzed and the programs are develop ed with
from the co mpani on webs ite at
and pseudocode. The programs can be down loaded
http://www.pearson highere d.com/schne ider.
s are
Chapter Summaries. At the end of each of C h apters 2 through 12, the key concept
stated and th e importa nt t rms summarized'.
on how to
"How To" Append ix. Append ix B prov ides a compact, step-by- tep referenc e
carry out sta ndard tasks in the Visual Basic env ironme nt.
r is locat-
Append ix on Debugging. The discussion of Visual Basic's sophist icated debugge
cove r this top ic.
ed in Append ix 0, allow ing the instru ctor flex ibility in decid ing when to
Studen t R esourc es
nd Vid oN t tut rial i l at d at www.pearsonhighered
of the book to
.com/sc hneider . S tud ents must use the access ca rd located in the front
Preface • XV
register and access the online material. lf no access card is provid ed, stud ents can purchase
access by go ing to www.pearsonhighered.com/schne ider and selecting "purchase access to
premium content. " Instructors must register on the site to access the material.
The following content is ava ilable through the Premium Web site:
• VideoN otes: Pearson 's new visual tool des igned for teaching key programming concepts
• Stud ent Solutions Manu al: All the answers to th e odd -numbered exe rcises (along with
scree n cap tures ) will be ava ilable for download in a solutions manual in pdf form at.
• All programs in th e book and all tex t fil es and databases needed for the exercises.
Notice: This book contains many screen captures. When you run one of the programs
downloaded from the webs ite, what yo u see on your monitor might not look exactl y like
the screen capture shown in the book. To make them appea r the same, you must ch eck
that your monitor is set to display 96 DPI (Dots Per Inch). To determine and/o r change
the DPl setting for your monitor, see th e first item und er "Co nfiguring the Windows Envi-
ro nment" in Appendix B on pages 584- 5. A lso, there may be slight differences due to the
version of Wind ows be ing used. See page 3.
1. A secti on on using radio buttons, check boxes, and list boxes for selection h as
bee n added to C hapter 4. (Mu ch of this material was previously in C hapter 9.
N ow it appea rs alongs ide If and Select Case blocks. )
2. A secti on on using loops with list boxes has been add ed to Chapter 6. (This sec-
t ion prese nts man y operations on lists, such as searching, summing, and finding
max imum values. )
New Concepts
1. C hapter 3: Implicit line continu ation. (The und erscore line-continu ation ch arac-
te r is rarely needed in VB 20 10.)
2. C hapter 3: Date data type. (This data type enables us to crea te so me interesting
programs, such as a program that tells use rs whether they are e ligible to run for
pres ident in 20 12. See Exe rcise 20 on page 152.)
3. C hapter 3: Se nding output to the printer. (This optional material demonstrates
h ow to produ ce a major type of output with Visual Bas ic.)
4. C hapter 7: The ReadAllLines method for filling an array with the contents of a
tex t file. (This powerful method allows us to place the contents of a tex t fil e in an
a rray without hav ing to use repea ted ReDim Preserve statements.)
xvi • Preface
5. Chapter 7: Language Integrated Query. (This recent addition to Visual Basic and
other .NET languages provides a standardiz ed way to spec ify queries for a variety
of data sources. In this textbook, LINQ is used to sort, ea rch , and filter informa-
tion from arrays, text files, XML files, and databases. This approach enables stu-
dent to write concise , higher- leve l code focused more on problem so lving than
on data-struc ture manipulat ion. Instructors wishing to teach a more e lementary
or traditiona l course ca n om it or reduce the use of LINQ. The textbook presents
most of the sta ndard operations on arrays and sequentia l file with and without
LINQ.)
6. C hapte r 8: The Set operators Concat, Union, Intersect, and Except are used to
manage data from text files. (These ope rato rs allow us to perform tasks that previ-
ous ly requ ired complicat ed algorithm s.)
7. C hapter 9: Too lTip control. (This control gives us a capability possessed by near-
ly eve ry commerci al Window app lication.)
8. C hapter 11 : Auto- Imp lemented properties. (This new-to-VB -2010 concept sim -
plifies the creation of classes.)
Other Changes
1. The version of Visual Bas ic has been upgraded from Vi ual Basic 2008 to Visual
Basic 2010, and releva nt new fe ature of Visual Basic 2010 h ave been added.
2. The rea l-life data in the exa mp les and exe rcise have been upd ated and revised.
3. So me new large co llections of data have been added. For instance, data on eve ry
Supreme Co urt justice (pa t and present) are contai ned in both a text file and a
database.
4. Named co nstants are introd uced earli er (Chapter 3).
5. The use of input va lid ati on has been increased (Chapter 4 on).
6. Function procedures are presented before ub procedure s (Chapter 5 ). With this
change, students begin learning about general procedure s with a familiar and s-
sential construct. Also, the instructor has the optio n of omitting the concep t of
passing by refe rence.
7. The use of text fi les for input h as been postponed until C h apter 7.
8. Tables are displayed in OataGridV iew controls rather than in list boxes (Chapter
7 on).
9. Many new business app lications have been added. ee the Guide to Applicatio n
Top ics on page vii.
10. The OpenFileO ialog control is discussed ea rlier (Chapter 8, Text Files).
11. The discussion of mu ltiple-form programs in Chapte r 9 has been expanded to an
entire section.
12. Databases are connected to programs with the Visual Basic wizard rather than
with code (Chapter 10).
Preface • xvii
1. G uid e to A pplicatio n Topics. (This section prov ides an index of programs that
dea l with va rio us topics including Business, Mathemat ics, and S ports.)
2. A complete solu tion manua l in pdf format. (The manual will conta in the code fo r
eve ry programming exe rc ise along with a screen capture of the o utput.)
1. Screen captures h ave bee n add ed to the programs in the answer section of the
book.
2. All th e answer to the odd -numbered exercises (along with scree n captures ) will
be ava ilable fo r download in a solutions manu al in pdf fo rmat.
3. Nearly 50 Vi cleoNotes are ava ilable at www.pea rsonhighered.com/schne ider.
VideoN otes are Pea rson 's new visual tool des igned for teaching key programming
concepts and techniqu es. A Vid eoN ote icon in the margin of the textbook a lerts
the reader when a topic is discus edin a video. See the Stud ent Resources sectio n
earlier in this Preface fo r info rmatio n on how to access VideoN o tes.
AcKNOW LEDGME NTS
any talented instruc~ors and programmers provided h e lpful comm ents and co ns tru e~
M tive suggestio ns durmg the va n o us edtttons of dus text, and I am most grateful fo r
th e ir contributions. The current edition benefited grea tly from the va luable co mmen ts of
th e fo llowing rev iewers:
G.W. Willis, Bay lo r U niversity
Jaygarl H ojun, Iowa S tate University
Teresa Peterman, G rand Valley S tate University
Joel We inste in, Northeastern U niversity
Daniel E. Turk, Colorado State University
Paul Norrod , Lo ra in County Commun ity College
Cynthia Brown , Portland S tate U niversity
Karen A rlien , Bismarck S tate College
Ron Conway, Bowling G reen S tate Unive rsity
Phil Larsch an , Tulsa Community College
Ca rol Roberts, U ni ve rsity of Ma ine at O rono
Ma rkita Price, U niversity of Missouri- Columbi a
Josh Pauli , Dakota tate University
Many people are invo lved in the successful publi ca tion of a book. I wish to thank the
dedica ted team at Pear on whose suppo rt and d iligence made this textbook poss ible, espe-
c ia lly Melinda H aggerty, Ass istant Edi tor of Computer Science, and Scott Disanno,
Senio r Ma nag ing Ed itor.
I also exp ress my thanks to John Tarcza, a talented programmer, who helped with the
develop ment of the book and prov ided va lu able insights and ca refu l proofreading. I would
like to thank Jeremy Schne ide r and Rob Teaga rd en for the ir helpfu l proofreading. Pro-
du ction editor Irwin Zucker did a fantastic jo b produ c ing the book and keeping it o n
ched ule. I am grateful to Jo hn Russo of the Wentwo rth Institute of Techno logy fo r pro-
d uc ing th e VideoN otes that accompa ny the book. The skill and grac iou ness of the tea m
at Lase rwo rds made for a pleasant production process. Copyedito r Bob Lentz contributed
many suggestions for improv ing the book's qu ali ty.
I extend special thanks to my editor Tracy Dunkelberge r. H er ideas and enthusiasm
helped immen sely with the preparation of the book.
XIX
UsiNG THIS BooK FoR A SHORT
OR CONDENSED COURSE
This book prov ides more than enough material for a fu ll-se mester co ur e. For a shorter course,
it will be necessa ry to bypass some sections. The following syllabu prov ides on e poss ible way to
present an abbrev iated introduct ion to programming.
1
Pas ing by reference ca n be o mitted or just me ntioned briefl y. In C hapters 6 th ro ugh 12, By Ref is used
o nl y in Example 6 of Section 7.3 (Arrays of Structures ) and in the C hapter 7 case study. In both of those
progra ms it is used to obtain input.
2
ections 8.1 and 8.2 are independe nt of each other.
xxi
AN INTR ODU CTIO N
TO PRO GRA MMI NG USIN G
1
2 • Chapter 1 An Introd uct io n to Comput ers and Problem So lving
Questio n: What are the meanings of the terms "hardware" and "softwar e"?
g a ll periphe r-
Answer : Hardware refers to the physica l co mponen ts of the comput er, includin
ical and electric a l devices . Program s
als, the central processing unit, disk drives, and a ll mechan
are referred to as software.
Questio n: What are the meanings of the terms "program mer" and "user"?
s on a compu te r.
Answer : A programmer is a person who so lves prob lems by writing program
he writes and te ts the
After ana lyz ing the problem and deve loping a plan for so lving it, h e or
1.1 An Introduction to Computers • 3
program that instructs the computer how to carry out the plan. The program might be run
many times, either by the programmer or by other . A user is any per on who uses a program.
While working through this tex t, you wi ll funct ion both a a programmer and as a user.
ll U.N. (E][][l[I D
o Yes g Yes
No No
Mouse Actions
Hover: Linger the mouse at a particular place and wait for a message (such as a tooltip) to
appear.
Drag an object: Move th mouse po inter until it is at the obj ect, press the left mouse button
and hold it down, move the mouse pointer until the obj ect moves to where you want it to be,
and finally, release the mouse button. (Sometimes this whole act ivity is called drag-and-drop.)
Right-clic k: Press and release the right mouse button once.
Click: Press and relea e the left mouse button once. (so metimes referred to as single-click or
left-click)
Double-cl ick: C lick the left mouse button twice in quick succession.
Note: A n important Windows conventio n is that clicking selects an obj ect so you can give
Windows further direction about it, but double-cli cking tells it to perform a default operation .
For exa mple, double-cli cking on a folder will open that folder.
File: Either a program file or a data fil e. Its name typically consists of letters, digits, and spaces.
The name of the file is also called the base name.
Extension of a file name: O ne or more letters, preceded by a period, that identify the type of
file. For exa mple, files created with Word have the ex tension doc or docx.
Filename: The combinat ion of the base name, the period, and the ex tension. The only char-
acters that cannot be used in filenames are \ , /, :, *, ?, <, > , ", and I. Filenames are not case
se nsit ive.
Folder: A container ho ld ing files and other folders. Folders also are known as directories.
Subfolder: A fo lder contained inside another folder.
Path: A sequence of folders, separated by backslashes ( \ ), where each folder is a subfolder of the
fo lder preceding it. Paths are used to identify the locations of fo lders and files. A n exa mple is:
Programs\C h07\Text_ Files_ for_ Exercises
Filespec: An abbrev iation of file specification, it is the combinatio n of a drive letter followed by
a colon , a path , and a filename. A n exa mple is:
In practice, yo u rarely hav to type a filespec, since both Windows and Visual Bas ic prov ide
Browse fac ilities that loca te files and fo lders for you.
Root folder (also known as the base folder): The highest fo lder on a disk. It co ntains all the
other fo lders on the disk and can also contain fil es . The fil espec of the root folder of yo ur hard
dri ve is most likely C: \ .
Windows Explorer: A program used to view, organize, and manage the fo lders and files on
your d isks. The de tails are presented in Appendix B in the section Manage Files and Folders with
W indows Explorer. To invoke Windows Exp lorer, right-click the Wind ow Start butto n a nd
click on Explore or Open W indows ExfJlorer in the context menu th at appears.
Displaying File Extensions: By default, Window shows only the base names of files. The fo l-
lowing steps configure Window to also display the ex tensions. (In this boo k we assume that
exte nsions are always show n) .
Windows XP
1. From Windows Exp lorer, click on O ptions in the Tools menu to disp lay the Folder Op tions
d ialog box.
6 • Chapter 1 An Introduct ion to Compute rs and Prob lem So lving
dvanced !3ettings :
Rles and Folders ,...
[Pl Ahv-a', • shmv icons . never thumbnails r--;
[ ] AJwa)~ !3ho•. • menu!3
[{] Display file icon on thumbnails -
f'Jl Display "ile size infom1ation in folder tips
[ ] Display the full path in the title bar Passic theme on~·)
Hidden files and folders
o Don show hidden files , folders . or drives
) Show hidden files . folder.> . and drives
~ Hide empty drives in the Computer folder
[ ] Hide extensions for known tile types I
0 Hide protected operating so1n,iem files (Recommended) ~
[ Restore Defaults ]
..____O_K______,) [ Cancel
1.3 will
2. C li ck on the View tab in the dialog box . (A dialog box similar to the one in Fig.
appear.)
click on
3. lf there is a check mark in the box next to "Hide ex tensions for known file types,"
the box to remove the check mark.
4. C lick on the OK button to close the Folder Options d ialog box.
input, necessary to obtain the output. The last step is to determin e how to process the input to
obtain the desired output- that is, to determine what formulas or ways of doing things can be
used to obtain the output.
This problem-solving approach is the sa me as that used to solve word problems in an alge-
bra class. For exa mple, conside r the following algeb ra prob lem:
The fi rst step is to determine the type of answer requested. The answer should be a number giving
the speed in miles per hour (the output ). (SJJeed is also called velocity. ) The information needed to
obtain the answer is the d istance and time the car has traveled (the in put). The formula
speed = distance/tim e
is used to process the dista nce trave led and the t ime elapsed in order to dete rmine the peed.
That is,
speed = 50 miles/2 hours
= 25 miles/hour
c___
lnp-ut ___,/ • .___/-Proce-ssing ___,/ • /.____
Out-put ---'
We de termine what we wa n t as outpu t, ge t the needed inpu t, and process the input to pro-
du ce the des ired output.
In th e chapte rs that fo llow we discuss how to write programs to carry out the preceding
operations. But first we look at the general process of wr it ing progra ms.
Program Planning
A baking rec ipe prov ides a good exa mp le of a plan. The ingred ien ts and the amounts are deter-
mined by what is to be baked. That is, the output determines the infJut and the processing. The
recipe, or plan, reduces the number of mistakes you migh t make if you tried to bake with no
plan at all. Although it's difficult to imagine an architect build ing a bridge or a factory without
a deta iled plan , man y programmers (pa rticularly students in their first programmin g cour e ) try
to wri te programs without fir t making a careful plan. The more complicated the proble m, the
more complex the plan may be. You will spend much less time working on a program if yo u
dev ise a carefull y though t out step-by-s tep plan and tes t it before actually writing the program.
Many programmers plan the ir programs using a sequence of steps, referred to as the
program developmen t cycle. The following step-by-step process will enab le yo u to use yo ur
t ime efficiently and help you design error-free programs that prod uce the desired output.
the nex t section, we discuss three popular methods used to develop the logic plan: flo wcharts,
in to a
pseudocode, and top-down charts. These tools help th e programm er break a problem
seq uence of small tasks the compute r can perform to solve the problem. Planning also involves
correct.
using represent ative data to test the logic of the algorithm by hand to ensu re that it is
3. Design the interface: Select the objects (text boxes, buttons, etc.).
cre-
Determi ne how the input will be obtained and how the output wi ll be displayed. Then
ate buttons and
ate objec ts to receive the inpu t and di play the output. A lso, create appropri
menus to allow the user to co ntrol the program.
4. Code: Translate the algo ri thm into a program ming language.
is
Coding is the technica l wo rd fo r wr iting the program. During th is stage, the program
compute r. The program mer uses the a lgo rithm
written in Visua l Basic and entered into the
devised in Step 2 along with a knowledge of Visual Basic.
5. Test and debug: Locate and remove any erro rs in the program.
of cor-
Testing is the process of finding errors in a program, and debugging is the process
the program is
recting erro rs that are found. (An error in a program is called a bug.) As
will be
typed, Visua l Bas ic points o ut certa in kinds of program errors. Other kinds of errors
is executed ; ho wever, many errors due to typing
detected by Visual Ba ic when the program
Basic language rules can be
mistakes , flaws in the algorithm , or incorrec t use of the Visual
such an error
uncove red and corrected only by careful detect ive work. An example of
wou ld be using addition when multiplic ation was the proper operatio n.
6. Complete the documentation: O rga nize all the material that describes the program.
date, to
Docume ntation is intended to allow another person, or the program mer at a late r
(comme nts) consists of statemen ts in the
understa nd the program. Internal documen tation
program that are not executed but point out the purposes of various parts of the program.
and
Docume ntation might also consist of a deta iled descriptio n of what the program does
, doc-
how to use it (for instance, what type of input is expec ted) . For commerc ial programs
on-line help. Other types of documen ta-
umentat ion includes an in truction manu al and
were used to construc t the
tion are the flowch art , pseudocode, and hierarch y chart that
ent
program. A ltho ugh documen tatio n is listed as the last step in the program developm
cycle, it should take place as the program is be ing coded.
Of th e program des ign too ls ava ilab le, three popu lar o n es a re the fo ll o
wing:
Flowch arts: G raphica lly dep ict the log ica l ste ps to ca rry o ut a tas k and
sh o w h o w the steps
re late to each oth e r.
Pseudo code: Uses English -li ke phrases with some Visua l Bas ic te rms to o
utline the task.
Hierarc hy charts: S h o w h ow the diffe rent pa rts o f a progra m re late to each
o the r.
Flowcharts
A flowch art con sists of specia l geometri c symbo ls connec ted by arro ws.
Within each symbol is a
phrase presenti ng th e act iv ity at th at step. The sh ape of the symbo l indica
tes the type o f o pe ratio n
th at is to occur. Fo r instance, the pa rallelog ram denotes input o r o utput.
The a rrows connec ting
the symbo ls, ca lled flowline s , sh ow the progres ion in which the steps
take place. Flo wcha rts
sh o uld "flow" from the top of th e page to the bo tto m. A ltho ugh th e symbo
ls useJ in fl owcha rts are
standa rdized , no stand ards ex ist fo r the amo unt of deta il req uired within
each symbo l.
Start
- ------~ input
Set stamps =
sheets /5 ------1L__ P_ro_c_es-si-ng_ _
~'---p-ro_c_es-si-ng_ _
Round stamps
up to next ------
whole number
------- ~ output
Pseudocode
al co mpute r code (hence ,
Pse ud ocode is an abb rev ia ted pla in English ve rsio n of actu
d by English -like sta te-
pseudocode). The geo metric symbo ls used in fl owch arts a re replace
mo re like co mpute r code
ments that o utline the proce s. A s a res ult, pse ud ocode loo ks
o n the steps require d to
than does a fl o wch a rt . Pse udocod e a llows th e progra mm e r to focus
r langua ge . The progra mm er can
so lve a pro ble m rather tha n on h ow to use the co mpute
res tricted by the rules of
d sc ri be the a lgo rithm in Vi ua l Ba ic-like fo rm witho ut be ing
ly tra nsla ted in to the Vi ua l
Visu al Bas ic. When the pse ud ocode is co mple ted, it ca n be easi
Bas ic la nguage .
1.4 Progra mmin g Too ls
• 11
Hierarchy Chart
The las t programmi ng too l we'll discuss is th e hiera rchy
chart , which shows the overall pro-
gram struct ure. Hiera rchy charts are also called struct
ure charts, HIPO (Hierarchy plus Input -
Process-Ou tput) charts, top-d own chart , or VTO C
(Visual Table of Cont ents) charts. All
these names refer to plann ing diagra m that are simila
r to a comp any's organ izatio n chart .
Hiera rchy charts depic t the orga nizati on of a progra
m but omit the specific processing
logic. They describe what each part, or modu le, of the
progra m does and they show how the
modu le relate to each other. The detail s on how the tTtodu
le work, howeve r, are omitt ed. The
chart is read fro m top to botto m and from left to right.
Each modu le may be subdivided into a
succession of subm odules that branc h out und er it. Typic
a lly, after the activities in the succes-
sion of ubmo dules are carried out, the module to the right
of the origin al module is co nsidered.
A quick glance at the hierarchy chart revea ls each task
perfor med in the program and where it
is performed. Figure 1.5 shows a hierarchy chart for the
postage-stamp proble m.
Postage-stamp
program
Read Calculate
sheets Display
stamps stamps
Decision Structure
The postage-s ta mp probl e m was solved by a se ries of
instru ction s to read data, perform calcu -
lation s, and display result . Each step was in a sequ ence;
that is, we moved from one line to the
nex t witho ut skipp ing ove r an y lines . This kind of struct
ure is ca lled a seque nce struc ture.
Man y probl ems, howeve r, requir e a decision to deter
mine wheth er a se ri es of instru ction s
should be execu ted. If the answe r to a ques tion is
"yes, " then on group of instru ction s is
Probl em So lving
12 • Chap ter 1 An Introd uctio n to Com pute rs and
No Yes
cond ition
true?
ture.
FIGURE 1.6 Pseud ocod e and flowc hart for a decis ion struc
Start
No Yes
street
even?
Display
Display
Eastbound
Westbound
End
Street
direction
program
FIGURE 1.9 Hierarchy chart for the numbered New York City streets problem.
Repetition Structure
A programm ing structure that executes instructions many times is called a repetition structure or
a loop structure. Loop structures need a test (or condition) to tell when the loop should end. With-
out an exit condition, the loop would repeat endlessly (an infinite loop ). One way to control the
number of times a loop repeats (often referred to as the number of passes or iterations) i to check a
condition before each pass through the loop and continue executing the loop as long a the condi-
tion is true. See Fig. 1.10. The solu tion of the next problem requires a repetition structure.
Is
No
condition
Discussion: The average grade equals the um of all grades divided by the number of students. We
need a loop to read and then add (accumula te) the grades for each student in the class. In ide the
loop, we also need to total (count) the number of students in the class. See Figs. 1.11 to 1.13 .
Input: Student grades.
Start
read next
grade
display the
answer
Class
average
problem
Processing: Find the sum of th e grades; co unt th e numbe r of stud e nts; ca lcula te
ave rage
grade = sum of grades/ numbe r of stude nts.
Output: Average grade.
Comments
1. Trac ing a flowch a rt is like play ing a boa rd ga me . W e beg in a t the S ta rt sy mbo l and
proceed
fro m symbo l to symbo l until we reach the End symbo l. At a n y time , we will be a
t just on e
sy mbo l. ln. a boa rd ga me, the pa th take n de pe nds o n th e result of spinning a spinne
r or
ro lling a pa ir of dice. The pa th ta ken through a flowc h a rt de pends on the input.
2. The a lgo rithm sh o uld be tes ted a t the fl o wc h a rt stage befo re be ing cod ed
into a pro-
gra m. Diffe re nt da ta sh o uld be used as input, a nd the o utput c h ecked. This
p rocess is
kno wn as desk checking . The tes t d a ta sh o uld includ e n o n ta nd a rd d a ta as
we ll as
t ypica l d a ta.
3. Flowc h a rts, pse ud ocode, a nd hierarc hy ch a rts a re unive rsa l proble m-so lving
too ls. They
ca n be used to constru c t programs in an y compute r language , no t just Vi sual Basic.
4. Flowch a rts are used through out this text to provid e a visualiza tio n of th e flo
w of ce rta in
progra mming ta ks a nd Visua l Bas ic contro l tru ctures. Majo r exa mples of pseudoco
de a nd
hi e ra rc h y ch a rts appea r in the case studies.
5. Flowcha rts a re time co nsuming to write and difficu lt to update . Fo r this reaso n
, profess io na l
progra mme rs a re mo re likely to favo r pse udocode and hi e rarchy cha rts. Because fl
owcha rts
so clearly illustrate the log ica l flow of program ming techniqu es, h owe ve r, they a
re a valu-
a ble too l in the educa tion of progra mme rs.
16 • Chapter 1 An Introductio n to Computers and Problem So lving
6. There are man y styles o f pse udocode. So me programm ers use an outline fo rm, whereas oth-
ers use a form that looks almost like a programm ing language. The pseudocod e appea ring in
t he case studie of this tex t focuses on the primary tasks to be perfo rmed by the p rogram and
leaves many of the routine details to be completed du ring the coding process. Several
Visua l Bas ic keyword , such as lf, Else, Do , and While, are used ex tensive ly in the
pse ud ocode appearing in this tex t.
Visual Basic, Controls ,
and Events
17
18 • Chapter 2 Visua l Basic, Controls, and Events
Figure 2.2 show how an eq ui va lent Visua l Ba ic prog ra m ge ts its info rmat io n . The boxes
may be filled in an y o rd er. When the use r clicks o n a box wit h t he mo use , the c urso r moves
to th at box. The use r ca n e ithe r type in new info rmation o r ed it th e ex isting info rm ati on.
When sa tisfied th at a ll the info rma ti on is co rrec t, th e use r clicks on the Write to Database
button. The boxes will clea r, and t he data fo r ano the r pe rso n ca n be ente red. Afte r a ll n ames
~· Vu'ashington
State : DC
Phone:
h ave been entered, the user clicks o n the Exit button. ln. Fig. 2.1, the prograrn
is in control; in
Fig. 2.2, the user is in control!
1. You literally draw the user interface, mu ch like using a paint program
.
2. Perhaps mo re importa nt, when you're done drawing the interface, the
buttons , text boxes,
and oth er objects that you have placed in a blank window wi ll automa tica
lly recogni ze user
action uch as mouse movem ents and button cl icks. That is, the seq uence
of procedu res
executed in you r program is control led by "events " that the user initiates
rather than by a
predete rmined seq uence of procedu res in your program.
ln any case, only after you des ign the interfac e does anythin g like traditio
nal program ming
occur. Objects in Visual Basic recogni ze events like mouse clicks; how the
object respond to
them depend s on the instru ctions yo u write. You always need to write instruct
ions in order to
make controls respond to events. This makes Visua l Basic program ming
fundam entally differ-
ent from traditio nal program ming. Programs in trad itiona l program ming languag
es ran from the
top down. For these program ming languages, exec ution sta rted from the
first line and moved
with the flow of the program to differen t parts as needed. A Visua l Bas ic
program works differ-
ently. Its core is a set of independ ent groups of instruct ions that are ac tivated
by the eve nt they
have been told to recogni ze. This event-d riven method ology is a fundam
ental sh ift. The use r
decides the o rder in which things happen , not the programmer.
Most of the program ming instruct ions in Visua l Basic that tell your
program how to
respond to events like mouse clicks occur in what Visua l Basic ca ll event fJrocedu
res. Essentially,
an ything exec utab le in a Visual Basic program either is in an event procedu
re or is used by an
event procedu re to help the procedu re carry out its job. ln fact, to stress that
Visua l Basic i fun-
dament ally differen t from traditio nal program ming languages, Microso ft uses
th e term project or
afJjJlication, rathe r than program , to refer to the combin at io n
of program m ing instruct ions and
user interfac e that makes a Visua l Basic program possible. H re is a summa
ry of the teps you
take to design a Visual Ba ic program:
Tool bar
Get Started te WS
I(}J New ProJ~ct .•
Welcome
t65 Op~n ProJed ...
The process for in voking Visual Bas ic varies lightly with the edition of Visual Bas ic
installed on the compu ter. To invoke Visual Bas ic from a computer that h as Visual Bas ic
Express installed, click the Windows Start button, hover over All Programs, and then click on
Microsoft Visua l Bas ic 20 10 Express. With the o ther editio ns of Visua l Bas ic, hover over All
Program , hover over Microsoft Visual S tudio 201 0, and then click on Microsoft Visual Studio
2010 in the sh ort list that is revea led.
Figure 2.3 shows the top h alf of the creen after Visual Bas ic is invo ked. A Menu bar and a
Toolbar are at the very top of the sc ree n. These two bars, with minor vari ations, are always pre-
se nt while you are working with Visua l Bas ic. The rema inder of the screen is ca lled the Start
Page. Some tasks can be initiated fro m the Menu bar, the Toolbar, and the Start Page. We will
usua lly initiate them fro m the Menu bar or the Toolbar.
The first item on the Menu bar is File. C lick on File, and then click o n New Project to pro-
du ce a N ew Project dialog box . Figure 2.4 shows the N ew Project dialog box produced by Visual
Bas ic Express.
The Wind ows Fo rms Applica ti o n ite m should be selected in the ce nter list. If this is not the
case, click on Windows Fonns A pplication to elect it. Note: The number of items in the list will
va ry depe nding on the ed ition of Visual Bas ic you are using.
The name of the program, initially set to Wind owsApp lica ti onl , can be specified at this
time. S ince we will have a chance to change it later, let's just u e the n ame Wind owsA pplica-
tion1 for now. C lick on the OK button to invoke the Visua l Bas ic programming env iro nment.
See Fig. 2.5. The Visual Basic programming environment is referred to as the Integrated Devel-
opment Environment o r IDE.
Ve ry likely, yo ur screen will look different than Fig. 2.5. The IDE is extremely configurable.
Each window in Fig. 2.5 can have its loca tion and size altered. New windows can be d isplayed
in th e IDE, and any wind ow ca n be closed or hidden behind a tab. Fo r instance, in Fig. 2. 5 the
Toolbox window is hidden behind a tab. The View menu is used to add additional windows to
the IDE. If you would like your screen to look exactly like Fig. 2.5, click on Reset Windows Layout
in the Windows menu , and then click on Yes.
New Project
l
So rt by: Defau lt
Installed Te mplates
~
Type: Visual Basic
mdows Forms Application
flftil:ffltl Visual Basic
A project for creating an application with a
Online Templates V'/indows user interface
Ve Class Library Visual Basic
~
ve WPF Browser Application Visual Basic
FIGURE 2.4 The Visual Basic New Proj ect dialog box.
22 • Chapter 2 Visual Basic, Controls, and Events
Menu bar
Toolbar
• f1 X
Forml System .Windo ws. Forms.Fo ...
Form
:: 11 l:.]
St artPositio WindowsDefaultl • ~
Ta g
lffi Forml
TopMost False
Sizing handle
FIGURE 2.5 The Visual Basic integrated development environment in Form Designer mode.
The Menu bar of the IDE display the menus of commands you use to work with Visual
Basic. Some of the menus, like File, Edit, View, and Window, are common to mo t Windows
app lication . Others, such as Project, Data, and Debug, prov ide commands spec ific to program-
ming in Visual Basic.
The Toolbar holds a collection of buttons that carry out standard operations when clicked.
For exa mple, you use the fifth button, which looks like a stack of three diskettes, to save the
files assoc iated with the current program. To reveal the purpose of a Toolbar button, hover the
mouse pointer ove r it. The little informat ion rectangle that pops up is called a tooltip.
The Document window currently holds the rectangu lar Form window, or form for short.
The form becomes a Window window when a program is executed. Most informat ion dis-
played by the program appea r on the form. The informat ion usually is di played in control
that the programmer has placed on the form. You can change the size of the form by dragg ing
one of its sizing handles.
The Properties window is used to change how objects look and react.
The Solution Explorer window displays the files assoc iated with the program and provide
access to the commands that pertain to them. (Note: If the Solution Explorer or th e Properties
window is not vis ible, click on it in the View/Other Windows menu.)
The Toolbox holds icons rep rese nting object (ca lled controls) that can be placed on the
form. If yo ur screen does not show the Toolbox, hover the mouse over the Toolbox tab at the
left side of the screen. The Toolbox will slide into view. Then click on the pushpin icon in the
title bar at the top of the Toolbox to keep the Toolbox permanently displayed in the IDE.
(Note: If th re is no tab marked Toolbox, click on Toolbox in the View/Other Windows menu.)
The controls in the Toolbox are grouped into ca tegories such as All Windows Forms and
Common Controls. Figure 2.6 shows the Toolbox after the Common Controls group ha been
expanded . Most of the control discussed in this text can be found in the list of common con-
tr l . (Y u n brain d cripti n fa ntr l by h v ring them u e ver th ntrol.) The
four control discussed in this chapter are text boxes, labe ls, buttons, and list boxes. In order to
see all the group names, co llapse each of the groups.
2.2 Vi sual Basic Controls • 23
~ :.......-
~ Comb oBox
~ DateTim eP icker
A Label
A LinkLa bel
- ListBox
,,,
', List 'ie'-'1'
IL MaskedT extBox
I'VlonthC alend ar
___J
~ Notifylcon
1 A
;;: ., Num ericUpDo wn
PictureBox
fill:! ProgressBar
0 Radio Button
~ Rich TextBox
8b~ TextBox
Text boxes: Yo u use a text box to get info rmat ion fro m t he use r, referred to as input, o r to dis-
play inform at ion produced by the program, referred to as output.
Labels: You place a labe l near a text box to te ll the use r what type of information is d isplayed VidcoN otc
C = :J
Sizing handles
2. C lic k a n ywhere o n the fo rm o utsid e the rec tangle to dese lec t the tex t box.
id to be
3. C li c k o n the recta ngle to resto re the h a nd les. An o bj ect sho wing its h a ndles is sa
o ther prop-
selected . A se lected text box can h ave its width a lte red , loca tio n c h anged , and
e rti es modified .
. The
4. Mo ve the mo use arro w to the h andle in the ce nter of the righ t side of th e tex t box
move
c urso r sho uld c ha nge to a d o uble a rrow (~) . H o ld d own th e left mo use button, a nd
th e tex t
the mo u e to the right. The text bo x is stre tched to the right. S imila rl y, grabbing
the left . Yo u
box o n the left sid e and mov ing the mo use to the left stre tch es the text box to
lle r. S teps 1 a nd 4 a llo w yo u to place a
a lso ca n use the ha ndles to make th e text box sma
uld no w be se lected ;
tex t box of a n y width an ywhe re o n the fo rm. Note: The tex t box sho
tex t box to
tha t is, its sizing h andles sho uld be sho wing. If no t , click anywhe re insid e the
se lect it.
a n a lte rnative
5. Press the d e le te key, DEL, to remo v the tex t box from the fo rm . S tep 6 g ives
way to place a tex t bo x of a n y width a t a n y loca tion o n th e fo rm .
an y place o n
6. C li ck o n the tex t box icon in the Too lbox . Th en mo ve the mo use po inte r to
thin lines.)
t h e fo rm. (Whe n over the fo rm, the mo use po inte r becomes a pa ir of crossed
te a rectan -
H o ld down the left mo use button, and drag the mo use o n a di agona l to gen e ra
r th e width
gle . R e lease th e mo use button to obta in a selected text box. Yo u ca n n ow a lte
w be se lected. If no t , click a n ywhe re
a nd loca tio n as befo re. Note: The tex t box sh o uld no
insid e the text box to se lect it.
es wind ow by
7. Press F4 to acti va te the Prope rti es wind ow. [Yo u a lso ca n activa te the Prope rti
se lecting
clic king o n it, clicking o n the ProjJerties Window b utto n ( ....J ) o n the Toolbar,
ProjJerties W indow fro m the View menu , o r clicking o n the text box wi th t h e right mo use
ow (ca lled
butto n a nd selecting ProjJerties .] See Fig. 2.8 . The first line o f the Prope rti es wind
is th current na me of the tex t box. The
the Obj ect box) reads "Tex tBox l tc ." TextBox l
o f pro p rties e ithe r
first two butto ns be lo w the Obj ect box permit you to v ie w the list
t h e up- and
grouped into categories o r a lphabe tica lly. U se t h e up- and do wn -arro w keys (o r
Properties Propertie
TextBoxl System .Windows. Forms. T e>.'tBox Text Bo xl System.Windo ws.Forms.T extBox Object
box
MaxLength 32767
Acc e.sibleDe.cript ion MinimumSize 0, 0
Acc essibl eName Modifi ers Friend
Acc e.sibleRole Default Multiline False
PasswordCha r
BackColor D Win dow Rea dOnly False
B l eft
TextAiign Left TextAiign Description
Text Text pane
The text associated with the control. The text associated with the control.
down-scroll arrows) to move through the list. The left column gives the property names,
and the ri ght column gives the current settings of the properties. W discuss four properties
in this walkthrough .
Note 1: The third and fourth buttons below the Object box, the Properties button and the
Events button, determine whether properties or events are di played in the Properties win-
dow. Norma ll y the Propertie button is highlighted. If not, cli ck on it.
Note 2: If the Description pane is not visible, right-cl ick on the Properties window, then
click on Description. The Description pane describes the currently highlighted property.
8. Move to the Tex t property with the up- and down-arrow keys. (A lternatively, scroll until
the property is visible, and click on the property.) The 0 xt property, which determines the
words disp layed in the text box, is now highl ighted. C urrently, there is no text di splayed in
the Settings box on the right.
9. Type your first name. Then press the Enter key, or click on another prope rty. Your name
now appears in both the Settings box and the tex t box. See Fig. 2.9.
c _. David Properties
l extBoxl System.Windows.Fo rms..TextBox
Tabind ex 0
David TabStop True
Tag
I
TextAii gn
Davrfl E!LJ
Left
lext
The text ass.o ciated with t he co ntro I.
10. C lick at the beginning of your name in the Tex t Settings box, and add your title, uch as
Mr., Ms., or The Honorab le. (lf you mistyped your name, you can eas ily correct it now.)
Then, press Enter.
11. Use the up-a rrow key or the mouse to move to the ForeColor property. This property deter-
mines the color of the information displayed in the tex t box.
12. li ck on the down arrow in th e right part of the Settings box, and the n click on the C us-
tom tab to display a election of colors. See Fig. 2.10. C lick on one of the co lors, such as
blue or red. Notice the change in the color of you r name. (Note: The sixteen wh ite boxes at
the botto m of the grid are used to create custom colors. See item L und er "Manage Vi ual
Basic ontro ls" in Appendix B for deta ils.)
13. Se lect the Font property with a single click of the mouse. The current font is named
Microsoft Sans Seri f.
14. C lick on the ellipsis ( . . . ) box in the right part of the Settings box to display a di alog box.
See Fig. 2. 11. The three lists give the current name (Microsoft Sans Serif) , current style
26 • Chapter 2 Visual Ba ic, Controls, and Events
Cu stom
111 111 11
111 111 11
FIGURE 2.10 Setting the ForeColor property.
Font
Effects Sample
[ ] Strikeout
A.aBbYyZz
[ ] Underline
Script:
Westem
(Regular), and current size (8) of the font. You can change any of these attributes by click-
ing on an item in its list o r by typing into the box at the top of the list. C lick o n Bold in the
style list, and click on 12 in the ize list. N ow click on the OK button to see you r name di -
played in a large r bold font. The text box will be longer so that it can accommo date the
larger font.
15. C lick on the text box and res ize it to be about 3 inches wid e.
Visual Basic programs consi t of three parts: interface, values of propertie , and code. Our
interface consists of a form with a single object, a text box. We h ave se t a few properties fo r
the text box-the text (namely, your name), the foreground color, the font style, and the
fo nt size. In Section 2.3, we discuss how to place code into a program. Visual Basic endows
2.2 Visual Basic Contro ls • 27
certa in capabilities to programs that are independent of any code we will write. We will
now run the ex isting program without adding any code in order to experience these capa-
bilitie .
16. C lick on the Start Debugging button ( ) on the Toolbar to run the program. [Alternative ly,
you can press FS to run the program or can click on Start Debugging in the Debug menu .]
After a brief delay, a copy of the fo rm appears that has ne ither the form nor the tex t box
selected .
17. Your name is highligh ted. Press the End key to move the cursor to the end of your name. N ow
type in your last name, and then keep typ ing. Eventually, the words will scroll to the left.
18. Press H o me to return to the beginning of the tex t. Yo u have a min iature word processo r at
your disposal. You ca n place the curso r anywhere you like in order to add or delete tex t. Yo u
can drag the cursor across tex t to select a block, place a copy of the block in the C lipboa rd
with Ctrl + C, and th en duplica te it elsewhere with C trl + V.
19. C lick on the Sto/J Debugging button ( ) on the Toolbar to end the program. [A lternatively,
you can end the program by clicking on the form's Close button ( J J) or press ing
Alt + F4 .]
20. Select the text box, act ivate the Prope rti es window, select the ReadO nly property, cl ick on
the down -a rrow button , and finally click on True. N o tice that the background color i now
gray.
21. Run the program, and try typing into the tex t box . Yo u can 't. S uch a text box is used fo r
o utput. O nly code ca n d isplay info rmation in the tex t box.
(Note: In this tex tbook, wheneve r a tex t box wil l be used on ly fo r the purpose of display ing
o utp ut , we will always se t the ReadO nly property to True.)
22. End the program.
23. Let's now ave the program on a disk. C lick on the Toolbar's Save A ll button ( ) to save
the work done so far. (Alternatively, you ca n click on Save All in the File menu.) You will be
prompted fo r the name of the program and the path to the fold er where you want the pro-
gram to be saved. Type a name, such as "VBdemo". You ca n either type a path o r use Browse
to locate a fold er. (Thi folder wi ll automat ically be used the n ext t ime you click on the Save
A ll button .) The files fo r the program will be saved in a subfolder of the selected fold er.
Important: If the "Create directory for so lutio n" check box is checked , then click o n the
check box to unch eck it. Finally, click on the Save button.
24. C reate a new program as before by clicking o n New Project in the File menu. [A lternati ve ly,
you ca n click on the New Project button ( ), the first button on the Too lbar, or you ca n
cl ick on New Project in the S tart Page.] A N ew Project d ialog box will appea r.
25. G ive a n ame to the project, such as MyProgram, and then click on the OK button .
26. Place three text boxes on the form. (If you use the double-click technique, move the tex t
boxes so that they do not ove rlap.) N o tice that they have the names Tex tBox l , Tex tBox2 ,
and TextBox3.
27. Run the program. No tice that the curso r is in Tex tBox l. We say th at Tex tBox l has the
focus. (This mea ns that Tex tBox l is the currently selected object and an y keyboard act ions
will be se nt di rectly to th is object.) A n y tex t typed will display in th at tex t box.
28. Press Tab once. N ow, Tex tBox2 has the focus. When you type, the characters appea r in
Tex tBox2.
28 • Chapter 2 Visual Ba ic, ontro ls, and Events
29. Pres Tab severa l times, and then press Shift+ T ab a few times. With Tab, the focu cycles
through the objects on the form in the o rd er they were created. With S hift+ T a b, the foc us
cycles in the reverse ord er.
30. End the program yo u created.
31. We would now like to return to the first progra m. C lick o n Open Project from the File menu .
An Open Project dialog box will appear stating that "You must choose to e ither save or d is-
card changes in the current project before opening a project." There is no need to save this
program, so click on the Discard button. Then a second Open Project dia log box will
appear.
32. Navigate to the fo lder correspo nding to the program you saved ea rlier, double-cli ck on the
fo ld er, and double-cli ck on the file with ex tension sln. You h ave now re loaded the first pro-
gram.
Note: As an a lternat ive to using the Open Project dialog box in Steps 31 and 32 to return
to the first program, click on the Start Page tab at the top of the Documen t window, and
click on the program in the Rece nt Projects part of the S tart Page.
33. If you do not see the Form Des igner for the program, do uble-click on Fo rm1.vb in the Solu -
tion Explorer.
34. Click on Close Project in the File menu to close the program.
A Button Walkthrough
1. C lick on the New Project button to sta rt a new program. (Give a name, such as ButtonPro g,
to the program , and click o n the OK button.)
2. Doub le-cl ick on the Button ico n in the Too lbox to place a button o n the form. (The But-
ton icon is the second icon in the Co mmon Co ntrols group of the Too lbox.)
3. Move the butto n to the center of the form.
4. Act ivate the Properties window, highlight the Text property, type "Please Push Me", and
press Enter. See Fig. 2.12. The button is too small.
Properties • 0 X
a... Forml
Butlonl 5y 5tem . \~ i ndo w s . F or m~ . B utton
11
~~ .... · .n ..... ·~
Tag
g Please Push
0 ··. u ...... (j TE:Xt: Pl!ea<Se Push Me
TatAiign M icl el l eC enter
Text
The tE:Xt: assoc iated with the control.
5. C lick on the button to se lect it, and then widen it to acco mmodate the phrase "Please Push
Me" on one li ne.
6. Run the program, and cl ick on th butt n. Th butt n appea r to move in and then out. In
Section 2.3, we will write code that is executed when a button is cl icked o n .
7. End the program and se lec t the button.
2.2 Visual Basic Controls • 29
8. From the Properties window, edit the Text setting by inserting an ampersand(&) before the
first letter, P. Press the Enter key, and notice that the first letter P on the button is now
underlined. See Fig. 2.13 . Pressing A lt+ P while the program is running causes the same
event to occur as does cl icking the button. H owever, the button will not appear to move in
and out. Here, P is referred to as the access key for the button. (The access key is always
spec ified as the character following the ampersand.)
9. C li ck on Close Project in the File menu to close the program.
1.1 .§] -/
Tag
----------------------
£lease F'ush Me
&P~ease PlUsh rli~ ~ n
TextAiign Middl eCenter
lfext:
Th e text ass ociated ~lith th e c: o ntro I.
A Label Walkthrough
1. C lick on the New Project button to begin a new program. Fee l free to keep the default
name, such as WindowsApp licationl .
2. Double-click on the label icon to place a labe l on the form. (The label ico n is a large letter
A.) Move the labe l to the center of the form.
3. A ctivate the Properties wind ow, highlight the Tex t property, type "Enter Your Phone Num-
ber:", and press Enter. (S uch a label is placed next to a text box into which the user wil l
type a phone number.) Notice that the label widened to acco mmodate the text. This hap-
pened because the AutoS ize property of the label is se t to True by default.
4. C hange the AutoS ize property to False. Pre s Enter. Notice that the label now has eigh t siz-
ing handles when selected.
5. Make the labe l narrower and longer until the words occupy two li nes.
6. Activate the Properties wind ow, and click on the down arrow to the right of the se tting for
the TextAlign property. Experiment by clicking on the various rectangles and observing
their effects. The co mbination of sizing and alignment permits you to design a labe l eas ily.
7. Run the program. Nothing happens, even if you click on the labe l. Labels just sit there. The
use r cannot change what a labe l displays unless yo u write code to make the change.
8. End the program.
9. C lick on Close Project in the File menu to close the program.
2. Place a list box on the form. (The list box icon is the ninth icon in the Common
Controls
gro up of the Toolbox. )
a Text
3. Press F4 to activate the Propertie s window and notice that the list box does not have
property. The word ListBox 1 is actu ally the se tt ing for the Name property.
4. Also place a tex t box, a button, and a labe l on the form.
5. C lick on the Object box just be low the t itle bar of the Properties window. The
name of the
that
form and the names of the four control are displayed . If you click on one of the names,
obj ect wi ll become se lected and its propertie s displayed in the Properties window.
6. Run the program . Notice that the word ListBox l has disappeared, but the words Buttonl
will
and Labell are still visible. The list box is comp letely blank. In subsequ ent sections, we
write code to place information into the li t box.
7. End the program and then click on Close Project in the File menu.
fo rm frm frmPayroll
button btn btnComp ute Tota l
label lbl lblAddress
list box lst lstO utput
text box txt txtC ity
g in
To change the name of the form, change the base name of the file Forml.v b appearin
the Solu tion Explorer
the Solution Exp lorer. To make the change, right-clic k on Forml. vb in
as frm-
window, click on Rename in the context menu that appea rs, type in a new name (such
keeps the
Payroll. vb), and press the Enter key. Importa nt: Make sure that the new filename
extensio n "vb".
prop-
The name of a control is changed from the control's Properties window. (The Name
controls and
erty is always the third property in the alphabet ized list of properties.) N ames of
r but
forms must begin with a letter and ca n include numbers and und erscore ( _ ) characte
cannot include punctuation marks or spaces.
I.
The N ame and Text properties of a button are both initially set to somethin g like Button
other property, and
H oweve r, changing one of these properties does not affect the se tting of the
property
similarly for th e N ame and Text properties of forms, tex t boxes, and labe ls. The Text
of a form specifies the words appearin g in the for m's title bar.
Fonts
New
The default font for controls is Microsoft Sans Serif. Two other useful fonts are Courier
and Wingdings.
2.2 Vi ual Basic Controls • 31
Courier New is a fixed-w idth font; that is, each ch aracter h a the same width. With such a
fon t, the letter i occupi es the same space as the letter m. Fi xed-width fo nts are used with tables
wh en info rmation is to be aligned in columns.
The Wingd ings font consists of assorted small pictures and symbols, each correspond ing to
a ch aracter on the keyboa rd. Fo r instance if o ne of the character %, (, 1, or J is typed in to th e
Text etting of a control whose Fo nt is Wingd ings, the contro l will display a be ll, phone, open
fo lder, or smiling face, respectively.
To view the character set for a Windows fo nt, click on the Windows Start button in the
Wind ows task ba r and successively click on A ll Programs, A ccessories, System Tools, and Cha r-
acter Map. A rectangular array of characte rs wi ll appear. After selecting th e fo nt, click on any
ite m to enlarge it. You can inse rt the keyboa rd character for the item in to the C lipboa rd by
pressing the Select button and then the Copy button. To place th e character into the Tex t prop-
erty of a contro l hav ing that font, just move the cursor to the Settings box for the Tex t property
fo r that co ntrol and press C trl + V.
Auto Hide
T h e Auto Hid e featu re allows yo u to make more room for th e Document window of the screen
by hiding windows (such as the Toolbox, Solu tio n Exp lo rer, or Properties window). Let's illus-
trate the featu re with a wa lkth rough using the Toolbox wind ow. W e start by discuss ing the sit-
uat ion where the feature is disabled.
1. If the Toolbox window is currently visible and the pushpin icon in the wind ow title is ver-
tical, th en the A uto Hide fea ture is disabled. (If the Toolbox window is not v isible, cl ick on
Toolbox in the m nu bar's View menu . If the pushpin icon is horizo ntal, then click on the
icon to make it ve rtical.) When the Auto Hid e feature i di ab led, the Toolbox window
stays fixed and is a lways ready fo r use.
2. C lick the mouse cur or somewhere outside the Toolbox window and no te that the Too lbox
window stays fixed.
3. C lick o n the pushpin ico n to make it ho rizo nta l. The Auto Hide feature i now enabled.
4. Move the mouse cursor somewhere outside the Too lbox windo w and no te that the window
!ides into a tab o n the left ide of the screen. The name and icon of the Too lbox window
appea r o n the tab.
5. H over the mo use curso r ove r the tab. The window slides into view and is ready for use.
Note: W e recommend that you keep the Toolbox, Solu ti on Exp lorer, and Prope rties win-
dows disp layed unless you are crea ting a program with a ve ry large form and need extra
pace.
other and fro m t he sides of t he fo rm . Snap lines are ho rizo ntal and vert ical line segments that Pos iti o ning
and a ligning
help you a lign co ntro ls. The Format menu is used to align contro ls, ce nter controls ho rizon- controls
ta lly and ve rtically in a fo rm , and make a group of selected control the sa me size.
appear.
3. Drag the button toward the upper-rig ht corner of the form until two short line segments
See Fig. 2.14(a). The button is now a comfortable distance from the two sides of the form.
y line
4. Place a second button be low the first button and drag it upward until a proximit
le distance apa rt.
appea rs between the two buttons. The buttons are now a comfo rtab
5. Res ize and pos it ion the two buttons as shown in Fig. 2.1 4(b) .
See
6. Drag Button2 upward until a blu e line appea r a lo ng the botto ms of the two buttons.
s are now
Fig. 2.14(c). This blue line is ca lled a snap line. The bottoms of the two button
aligned.
the
7. Continu e dragg ing Button2 upward until a purple snap line appears just underne ath
The midd les of the two buttons are now
words Buttonl and Butto n2. See Fig. 2. 14(d).
tell us
aligned. If we were to continue dragging Button2 upward , a blue snap line would
when the tops were aligned . Step 10 shows another way to align the controls .
I Button1 J ·'
+ - Proxim .ity Button 1
line
Button2
(a) (b)
I I J J
I Button 1
l I Button2 J Snap
line
l
Button 1
J
j
Button2
t I
(c) (d)
the mouse
8. C lick on Buttonl and then ho ld down th e C trl key and click on Button2. After
button is relea ed, both butto n will be selected.
a group
Note: This process (called selection of multiple controls ) can be repeated to select
of any number of controls.
set the
9. With the two buttons still selected, press F4 to open the Prope rti es window. Then
ltered for both
ForeColo r property to Blue. N otice that the ForeColo r property has been a
in
buttons at the same time. Actua ll y, any property that is co mm on to eve ry control
selec ted multiple controls can be se t simultan eously for the entire group.
10. With the two buttons still se lected, open the Format menu in the Menu
bar, h ove r over
Align, and click on Tops. The tops of the two buttons are now a ligned. Precisely , Buttonl
(the first button se lected) will stay fixed, and Butto n2 will move up so that its top is align ed
with the top of Buttonl.
The most common uses of the ubmenus of the Format menu are as fo llows:
Align: A lign middles or correspo nding sid es of a group of selec ted contro ls.
Make Same Size: Make the width and/or he ight of a group of se lected contro ls the sa me.
2.2 Vi ual Basic Controls • 33
Horizontal Spacing: Eq ualize the ho rizontal spac ing between a group of three or mo re selected
controls arranged in a row.
Vertical Spacing: Equalize the vertical spac ing betwee n a group of three or more selected con -
tro ls arranged in a column.
Center in Form: Center a se lected co ntrol e ither horizo ntally or ve rtica ll y in a fo rm.
When multiple con trols ar selected with the C trl key, the first control selected (called the
primary control of the group) will h ave white sizing h andles, while th other contro ls will have
black sizing h and les. A ll alignment and sizing statements initiated from the Format menu wdl
keep the primary control fixed and will a lign (or size ) the other controls with respect to the pri-
mary con tro l.
Afte r multip le contro ls h ave been selected, they ca n be dragged as a group and deleted as a
group. Exe rc ises 35 and 36 show how the arrow keys can be u ed to move and size a contro l.
The arrow keys also can be u ed to move and size multiple contro l as a group.
A gro up of co ntro ls a lso can be se lec ted by cli cking the mouse o utside the contro ls, drag-
ging it across the con tro ls, and releas ing it. The Select A ll command fro m the Edit menu (o r
t he key comb inatio n C trl + A) ca uses all the co ntro ls on the form to be s lected. Alth ough
these meth ods are easy to apply, th ey do no t allow the programm er to des ign ate the primary
control.
Comments
1. W hile you a re wo rking on a program, t he program res ides in memo ry. Remov ing a program
fro m me mo ry is referred to as closing the program. A program is automat ically closed when
you begin a new program. A lso, it can be closed directly with the Close Pmject command
fro m the File menu.
2. Three useful properties that h ave not b en discussed are the following:
(a) BackColo r: This property specifies the background colo r for th e fo rm o r a contro l.
(b) Visible: Setting the Visible property to False ca uses an obj ect to disappear when the
program is run. The obj ect can be made to rea ppear with code.
(c) Enabled: Setting the Enabled property of a co ntro l to Fa lse restricts its use. It appears
grayed and canno t rece ive the focus. Co ntrols sometimes are disa bled temporarily if
they do no t apply to the current state of the program.
3. Most properties ca n be et or altered with code as the program is running instead of be ing
prese t from the Properties window. For instance, a butto n ca n be made to d isappea r with a
line such as Buttonl. Visible = False . The deta il are presented in Section 2.3.
4. If you inadve rtently double-click on a fo rm, a window conta ining text wil l appear. (The
first line is Public C lass Forml.) This is the Code Editor, which is discussed in the nex t
34 • Chapter 2 Visual Bas ic, Contro ls, and Events
section. Press C trl + Z to undo the addition of this new code. To return to the Form
Des igner, click on the tab at the top of the Documen t window labeled "Forml. vb [Design] ."
5. We have seen two ways to place a control onto a form. Another way is to ju t click on the
con trol in the Toolbox and then click on the location in the form where you would like to
place the contro l. A lternative ly, you can just drag the control from the Toolbox to the loca-
tion in the form.
6. Figure 2.9 shows a small down-a rrow button on the right side of the Tex t property setting
box . When yo u click on that button, a rectangula r box appears. The se tting for the Tex t
property ca n be typed into this box instead of into the Settings box. This method of spec i-
fy ing the setting is especially usefu l when you want the button to have a multiline caption.
1. What is the difference between the Tex t and the N ame properties of a button ?
2. The first two group names in the Toolbox are All Windows Forms and Common Controls.
How many groups are there?
EXERCISES 2.2
1. C rea te a form with two buttons, run the program, and click on each button. Do you notice
anything different about a button after it has been clicked ?
2. While a program is running, a contro l is said to lo e focus wh en the focu moves from that
contro l to another control. Give three ways the use r can cause a control to lose focu .
In Exercises 3 through 24, carry out the task.
3. Place "C HEC KIN G A CCOUNT " in the title bar of a form.
4. C reate a tex t box containin g the words "PLAY IT, SAM" in blue letters.
5. C reate a tex t box with a ye llow background.
6. C reate a text box named txtGreetin g and containing the word "HELLO" in large italic letters.
7. C rea te a label containin g the sentence "After all is said and done, more is aid than done."
The sen tence should occupy three lines, and each line should be centered horizonta lly in
the label.
8. C rea te a read-only tex t box co ntaining the words "Visual Basic" in bo ld white letters on
a
red background.
9. C rea te a text box named txtLanguage and containin g the words "Visual Bas ic 2010"
in
Courier N ew font.
10. C reate a ye llow button named btnPush and containing the word "PUSH ".
11. C rea te a white button containin g the word "PUSH" in large italic letters.
12. C reate a button containin g the word "PUSH" in bold letters with the letter P underline
d.
13. C reate a button containin g the word "PUSH" with the letter H as the access key.
14. C reate a label containin g the word "ALIAS" in white on a blue backgroun d .
15. C reate a label named lblAKA and containin g the ce ntered italicized word "A LIAS".
16. Place "BALANC E SHEET" in the title bar of a form having a ye llow backgroun d .
17. C reate a label containing "VISUAL" on the fir t lin and "BA IC" n the s cond line.
Each word should be right-justified.
2.2 Visual Bas ic Controls • 35
18. C reate a form n amed frmHello whose t itle bar reads "H ello World".
19. C reate a label conta ini ng a picture of a d iskette. (Hint : U se the W ingd ings character < .)
Make the diskette as large as po sible.
20. C reate a labe l containing the bold word "ALI AS" in the Co urier N ew font.
21. C reate a list box with a ye llow background.
22. C reate a list box that will be invisible when the program is run.
23. C reate a form named frm Yellow with a ye llow backgro und .
24. C reate a button containing a picture of a red bell. (H int: U se the W ingd ings charac ter %. )
Make the bell as large as possible.
I n Exercises 25 through 30, create the interface shown in that figure. (These exercises give
you practice creating controls and assigning properties. The interfaces do not necessarily
correspond to actual programs.)
25. 26.
D ... Dynami c Duo GJI @J ~~ D::; Ent er Name ~~ @J ![}[]
Batman arne:
H obitn Enter
27. 28.
aJ Fill the Blan • ~~ @J I[]!] ll Sim il arit> •
29. 30.
ll,. Um le:'5 •d·•..- ice ~~ B I[};[]
The three most important
things in life are
OJ Be kind
OJ Be kind
[I] Be kind
Henrl James advice t o
his nephe•N
31. C reate a rep lica of your bank check on a form . Words common to all checks, such as "PAY
T O THE O RDER OF", should be contained in labe ls. Items spec ific to your checks, such as
yo ur name at the top left, should be contained in tex t boxe . Make the check on the screen
resemble your personal check as much as possible. Note: Omit the account number.
32. C reate a replica of your campus ID on a form. Words that are on all student IDs, such as the
name of the college, should be conta ined in labe l . Informat ion specific to yo ur ID, such as
36 • Chapter 2 Visual Bas ic, Contro ls, and Even ts
your name and student ID number, should be contained in tex t boxes. S imulate yo ur pic-
ture with a tex t box co ntaining a smiling face-a size 24 Wingdings J.
33. Consider the form shown in Exe rcise 25. A ssume the Batman button was add ed to the form
before the Robin button. What is the tab index of the Robin button ?
34. Consider the form shown in Exercise 26. Assume the first contro l added to the form was
the label. What is the tab index of the label?
The following hands-on exercises develop additional technique s for manipulat ing and access-
ing controls placed on a form.
35. Place a tex t box on a form and se lect the text box. What is the effect of press ing the va ri-
ous arrow keys?
VideoNote
36. Place a text box on a fo rm and select the tex t box. What is the effect of pressing the va ri-
Moving a textbox
ous arrow keys while holding down the Shift key?
(Homework)
37. Repeat Exerci e 36 fo r selected multiple contro ls.
38. Repea t Exercise 35 for selected multiple controls.
39. Place a labe l and a list box on a fo rm and change their font sizes to 12 at the same time.
40. Place a button in the ce nter of a form and select it. Hold down the C trl key and press an
arrow key. Repeat this process for each of the other arrow keys. Describe what happens.
41 . Place a label and a tex t box on a form with the label to the left of and above the text box.
Select the label. Hold down the C trl key and press the down- arrow key twice. With the
C trl key still pressed, press the right- arrow key. Describe what happens.
42. Place two button on a form with one button to the right of and below the other button .
Select the lower button, hold down the C trl key, and press the left-arrow key. With the Ctrl
key still pressed, press the up-arrow key. Describe the effect of pressing the two arrow keys.
43. Experimen t with the A lign command on the Format menu to determine the difference
between the center and the middle of a contro l.
44. Place four large buttons vertically on a form. U se the Format menu to make them the same
size and to make the spac ing between them uniform.
45. Place a label and a tex t box on a form as in Exercise 26, and then lower the label slightly
and lower the text box until it is about one inch lowe r than the label. U se the mouse to
slowly raise the text box to the top of the form. Three snap lines will appear along the way:
a blue snap line, a purple snap line, and finally another blue snap line. What is the signifi-
cance of each snap line?
46. Place a tex t box on a form, select the text box , and open its Properties window. Double-click
on the name (not the Settings box) of the ReadOnly property. Double-click aga in. What is
the effect of double-cli cking on a property whose possible settings are True and False?
47 . Place a button on a form, select the button, and open it Properties window. Double-click
on the name (not the Settings box ) of the ForeColor property. Double-click repeated ly.
Describe what is happening.
to the button
1. The text is the words appea ring on the burton , whereas the name is the des ignation used to refer
have the same va lue, such as Button 1. H owever, each ca n be changed independen tly of
in code. In itia lly, they
the other.
Toolbox after
2. T he Toolbox in the Exp ress Edition of Vis ual Bas ic conta ins 11 groups. Figure 2. 15 shows th e
editions of Visual Bas ic the Toolbox co ntains 12 groups.
each group has been collapsed. Note: In the other
2.3 Visual Basic Events
• 37
Toolbox
All Windows Forms
Common Controls
Conta iners
Menus & Too lbars
Data
Compone nts
Printing
Dialogs
WPF Interoperabili
Visu al Basic PowerPacks
G~e~ l ,
1. Create the in terface; that is, generate, pos ition, and size the objects.
2. Set properties; th at is, co nfigure the appea rance of the objects.
3. Write the code that executes when eve nts occur.
Section 2.2 covered Steps 1 and 2; th i section is devoted to Step 3. Code consist of state
ments
that carry out tasks. Writing code in Visual Bas ic is a sisted by an autoco mpletion system
ca lled
lntelliSe nse that redu ces the amount of memoriza tion needed and helps prevent errors.
In this
section, w limit ourselves to statemen ts that change properties of a control or the form
wh ile a
program is runn ing.
Propert ies of co ntro ls are changed in code with statemen ts of the form
where controlN ame is the na me of the co ntro l, jJroperty is one of the properties of
th co n-
tro l, and setting is a va lid setting for that prope rty. Such stateme nts a re ca lled assignm
ent
stateme nts. They ass ign va lues to prope rties. H ere are three examp les of as
ignment
statemen ts:
1. The statemen t
txtBox. Text = "Hello"
where the three dots (that is, the ellips is) represe nt
System .Even tArgs
ByVal sende r As System . Objec t , ByVal e As
FIGURE 2.16 The interface for the event procedu re walkth rough.
1. C reate the interface in Fig. 2.16 in the Form Designer. The Name
properties of the form,
tex t boxes, and button should be set as shown in the Object column
. The Tex t property of
the form shou ld be se t to Demon stratio n, and the Text property of
the button should be set
to C hange Color to Red . N o properties need be se t for the text boxes.
2. C lick the right mouse button an ywhere on the Form Design er, and
click on View Code. The
Form Designer lDE is replaced by the Code Editor IDE (also known
as the C ode view or the
Code window). See Fig. 2.17.
~ My Proj ect
En d Class
::::J frmDemo.vb
11
End Sub
btnRe d_C li ck. This proced ure is
The first line is the heade r for the eve nt proced ure named
the butto n is clicke d, the code
invoke d by the event btnRe d.Clic k. That is, whene ver
betwee n the two lines just shown will be execu ted.
5. Type the line
txtFir st.Fo reCol or Color .Red
bet First
.) tct5econcl
.---- .---- -
Comm on All
.
This fea ture of lntelli Sense is referred to as Compl ete Word
1
2.3 Visua l Basic Eve nts
• 41
Anch or
App _ndT i GetCh a rln d exF romP os iti on
...zJ Aut o( ompl Cust on,So ur c GetChildAtP oi nt ='
....J Au oC ompl t Mod
GetC ontain erC o ntro I
....J Aut oCo mpl t So urc
GetF irstC h a rln d exF rom Lin e
Bad -Co lo r GetFi rstC h a rln d exOfCu rrent li n e
Bo rd rS I Getli n eFrom Ch a rln d ex
Brtn gToFront GetP osition From Ch a rln d ex
Ca nF oc u ~ HasChildren
Ca nS I ct
Height
Co mm o n All Com mon All
ct txtFirst.
7. Retu rn to the Form Des igne r and sele
s win dow. The
the toolbar at the top of the Prop ertie
8. C lick on the Events butt on ( f ) in desc ribes the
displaye d, and the Des crip tion pan e
63 even ts as ocia ted with text boxes are ts. Only a few
alarmed by the large num ber of even
currentl y sele cted eve nt. (Do n't be
to the Leav e even t. See Fig. 2.2 1.
even t are used in this boo k.) Scro ll
Properties
txt f irst Syst em. Wind ows. Form s. TextBox
KeyPress
KeyUp
Layo ut
Leave EJ!_j
Location Ch anged
MarginCh anged
Modifi edCh ang ed -- -- --~
leav e
e
Occurs when th e control is no long er th
activ e co ntrol of t he form .
ow.
FIGURE 2.21 Even ts displayed in the Properties wind
End Sub
( ... ) Han dles txtF irst .Le ave
Priv ate Sub txtF irst _ Lea ve
.Bla ck
txtF irst .Fo reC olo r = Col or
End Sub
.Te xtC han ged
ang ed( ... ) Han dles txtF irst
Priv ate Sub txtF irst _ Tex tCh
.Blu e
txtF irst .Fo reC olo r = Col or
End Sub
End Cla ss
rma tio n abo ut
ove r the curso r ove r the word "ForeCo lo r". Visual Bas ic now disp lays info
10. H Bas ic.
trates ano ther help feat ure of Visual
the foregro und colo r prop erty. Thi s illus
11. Run the prog ram by press ing FS.
llo" h as been typed.
box. In Fig. 2. 22, the blue word "He
12. Typ e ome thin g into the first tex t typi ng- that is, whe n -
whe never it is read y to acce pt
(Re call that a text box has the focu s
ever it contain a blinking cur r.)
me blac k. Wh en
C lick on the seco nd text box . The con tent of the first text box will beco
13. the even t Leav e
first text box lost the focu ; that is,
the seco nd text box was click ed, the
2.3 Vi ual Bas ic Event
• 43
btnO ne_C lick is the name of the eve nt proced ure, and
btnOn e.C lick ident ifies the event t hat
invok es the proce dure. The n ame ca n be changed
at will. Fo r instan ce, the heade r ca n be
chang ed to
Opening a Program
be
p le cont ains a program. These programs can
Beg in ning with the next chap ter, each exam s xiv- xv of the
boo k. See the discussion on page
dow n load ed from the Pearson website for this ic env i-
program tored on a disk into the Visual Bas
Preface for deta il . Th process of load ing a 7-2-3
ram. Let 's ope n the dow n load ed prog ram
ronm ent i refe rred to as open ing the prog then displ ays U.S.
to e nte r a fi rst n ame , and
from C hapt e r 7. Tha t prog ram allows you
Pres iden ts hav ing that first nam e.
~ My Proje ct
[> bin
fm1Pr esid ents.v b
I Display Presidents
l
President James Madison
President James Monroe
President James Polk
President James Buchanan
I
President James Garfield
President James Carter
--
The program just executed uses a tex t fil e named USPres. txt. To view the text fil e, open the
folder bin, open the subfo lder Debug, and click on USPres. txt. (lf the bin folder is not visib le,
click o n the Show All Files button. If USPres.txt is not listed in the Debug ubfo ld er, click the
Refresh butto n and reopen the folders. After read ing C hapter 7, you will und erstand why tex t
files are placed in the Debug subfold er of the bin fo lder.) The first line of the fil e gives th e name
of the first president; th e second line gives the name of the second president, and so on. To
close the text fil e, click on the close button ( X ) on the USPres.txt tab.
Comments
1. The Visual Basic ed ito r automatica lly indents the statements inside procedures. ln thi
book, we indent by two spaces. To instru ct yo ur ed ito r to indent by two spaces, se lect
O fJtions from the Tools menu, and unch ck the "Show a ll settings" box in the Options win-
dow that appears. Expand "Tex t Editor Basic" o r "Text Editor", click o n "Editor", enter 2
into the "Indent size:" box, and click on OK.
2. The event controlName. Leave is raised when the spec ified co ntro l loses the focus. Its coun-
terpa rt is the eve nt concrolName.Enter which is raised when the spec ifi ed co n trol ge ts the
foc us. A related state ment is
controlNarn e.Focus()
object.Tex t = setting
the exp ress ion fo r setting must be surround ed by quotatio n marks. (Fo r instance, lblName.
T ext = "Name".) For prope rties where the proper setting is o ne of the words True o r Fa lse,
th ese words should not be surround ed by quotation marks.
5. Names of ex isting event procedures assoc iated with an object are not automat icall y
changed when you rename the object. Yo u must change them yourself. H owever, the event
46 • Chapter 2 Visual Basic, Controls, and Events
-
that invokes the procedur e (and all other reference s to the control) wi ll change automati
cally. For exa mp le, suppose an event procedur e is
Private Sub btnOne_ Cl i ck( . . . ) Handles btnOne . Click
btn One .Text = "Press Me"
End Sub
you
and , in the Form Designer, you change the name of btnOne to btnTwo. Then, when
return to the Code Editor, the procedure will be
There w ere buil d erro rs. Would you li ke to continu e and run th e last
successfu l buil d?
_es_
' - - -Y ___,] l____N_o_ _J
0 Do not show this di alog aga in
8. Each contro l ha a favored event, called the default event, whose event procedure template
can be generated from the Form Designer by double-clicking on the control. Table 2.2
shows
is the
some contro ls and their defau lt vents. The most common event appear ing in th is book
The
C lick event for a button. The TextC hanged eve nt for a text box was used in this section.
ed in Section 4.4, and the Load event
Selected lndexCh anged event for a list box is introduc
book.
for a form is introd uced in Section 7.1. The C lick event for a label i never used in this
form Load
button C lick
labe l C lick
list box ele tedlndexChang d
text box TextChanged
2.3 Visual Ba ic Events • 47
9. Fo nt properties, such as the name, sty le, and size, are usually spec ified at des ign t ime. The
setting of the properties ca n be displayed in code with statements such as
l stBox.I tems.Add(txtB ox.Font.Name )
lstBox.Items . Add ( txtBox.Font.B old )
l stBox. Items.Add ( txtBox.Font . Size)
H oweve r, a font's name, style , and size properties cannot be altered in code with statements
of the form
t xtBox . Font.Name "Courier New"
tx tBox . Font.Bold True
t xtBox . Font . Size 16
10. When you make changes to a program, asterisks appear as superscripts on the tabs labeled
"frmN ame.vb [des ign]" and "frmN ame.vb" to indicate that so me part of the program has
not been saved. The asterisks disappea r when the program is saved o r run.
Note: lf the program has been saved to disk, all fi les for the program wi ll be automat ica lly
upd ated on the disk whenever the program is saved o r run.
11. You ca n eas ily change the size of the fo nt used in the current program's ode Edito r. Just
ho ld down the C trl key and move the mo use's scroll wheel.
12. Notes on IntelliSe nse:
(a) Whenever an item in an lntell iSense drop-down list is se lected, a too ltip describ ing the
item appea rs to the right of the item.
(b) From the situation in Fig. 2. 18, we can display txtFirst by double-click ing on the high lighted
item, pressing the Tab key, or pr ss ing the Enter key. Another option is to press the period
key. In this case, both the name txtFirst and the dot following it will be displayed. Note: The
period key option works only if the selected item is always fo llowed by a dot in code.
(c) Inte ll iSense drop-down lists have tabs labe led Common and All. When the All tab is
selected, every possible co ntinu at ion cho ice appea rs in t he list. W hen the Common tab
i selected, on ly the most freq uen tly used co nt inuat ion cho ices appear.
(d) Occasionally, the lntell iSense drop-down list will cover some of yo ur program. If you
ho ld down the t rl key, the drop-down list wi ll become transparent and allow you to
see the cove red- up code.
1. Describe the event that invokes the fo llow ing event procedure.
Private Sub btnCompute_ Click() Handles txtBox.Leave
t xtBox. Text = "Hello world"
End Sub
2. Give a statement that wi ll prevent the use r from typ ing into txtBox.
EXERCISES 2.3
I n Exercises 1 through 6, desc ribe the contents of the text box after the button is click ed.
1. Priv ate Sub btnOutput Click( ... ) Handles btnOutput.Cl ick
tx t Box.Text = "Hello"
End Sub
48 • Chapter 2 Visual Bas ic, Contro ls, and Eve nts
In Exercises 7 through 10, assume that the three objects on the form were created in the
order txtFirst, txtSecond , and lblOne. Determin e the output displayed in lblOne when the
program is run and the Tab key is pressed. Note: Initially, txtFirst has the focus.
7. Private Sub txtFirst Leave( ... ) Handles txtFirst. Leave
lblOne.F oreColor = Color.Gre en
lblOne.T ext = "Hello"
End Sub
In Exercises 17 through 28, write a line (or lines ) of code to carry out the task.
17. Display "E.T. phone ho me." in lblTwo.
18. Display "Play it, Sa m. " in lblTwo.
19. Display "The stuff that dreams are made of." in red letters in txtBox .
20. Disp lay "Life is like a box of c hoco la tes." in txtBox with blu e lette rs o n a go ld back-
gro und.
21. Disable txtBox.
22. C hange the words in the form's title bar to "H e llo World."
23. Make lb1Two disappear.
24. C hange the co lo r of the letters in 1b1Name to red.
25. Enab le the disabled button btnO utco me.
26. Give the focus to btnCo mpute.
27. G ive the focus to txtBoxTwo.
28. C h ange the backgroun d color of the fo rm to Wh ite.
29. Describe the Enter event in yo ur own wo rds.
30. Describe the Leave event in your own wo rds.
31. The label co ntro l has an event called DoubleC lick that is ra ised by doub le-cl icking the left
mouse button. Write a simple program to test this vent. Determine whether yo u can ra ise
the DoubleClick eve nt without also ra ising the C lick eve nt.
32. W rite a simple program to demonstra te that a button 's C lick eve nt is ra ised when you press
the Enter key whi le the button has the focus.
In Exercises 33 t hrough 38, th e interface and initial properties are specified. Write a pro-
gram to carry o ut the stated task.
33. When one of the three buttons is pressed, the words on the button are d isp layed in the text
box with the stated al ignm ent. Note: Re ly on lnte lliSense to provid you with the proper
ettings for the TextAlign property.
50 • Chapter 2 Visual Bas ic , Contro ls, a nd Eve nts
[ Right Justify
37. When the use r moves the focus to one of the three small text boxes at the bottom of the
fo rm , an approp riate saying i displayed in the large text box. Use the say ings "llike li,~e, it's
something to do."; "The future isn 't what it u ed to b ."; and "Tell the truth and run.
38. The user can d isable or enable the text box by clicking on the appropriate butto n . After the
user clicks the Enab le button, the tex t box should rece ive the focus.
BE J
EJE J •
FIGURE 2.26 Form for Exe rcise 39. FIGURE 2.27 Form for Exercise 40.
40. S imulate a traffic light with three small squ are tex t boxes placed vertically on a form. See
Fig. 2.2 7. Initially, the bottom tex t box is so lid green and the other text boxes are da rk gray.
When the Tab key is pressed, the midd le text box turns ye llow and the bottom text box turns
dark gray. The next time Tab is pressed, the top text box turns red and the midd le text box
turns dark gray. Subsequent press ing of the Tab key cycles through the three colors. Hint: First
place the bottom text box on the form, then the middle text box, and finally the top text box.
41. Use the sa me form and properties as in Ex rc ise 34, with the captio ns fo r the buttons
rep laced with Vanish and Reappea r. C li cking a button sho uld prod uce the stated r sult.
42. A form contains two text boxes and one large label between them with no preset caption.
When the first text box rece ives the focus, the labe l reads "Enter your fu ll name." When the sec-
ond text box rece ives the focus, the label reads "Enter your phon number, including area code. "
52 • Chapter 2 Visual Basic, Contro ls, and Eve nts
43. The form contains a single read-only tex t box and two buttons. When the user clicks on
one of the buttons, th e se ntence "You just clicked on a button. " is displayed in the tex t box.
The program should consist of a single event procedure.
44. The fo rm contains two tex t boxes into which the use r types information . When the u er
cl icks on one of the tex t boxes, it beco mes blank and its contents are displayed in the other
tex t box . Note: A tex t box can be cleared with the statement txtBox. Clear () or the state-
tnen t txtBox. Text = ""
1. T he event is raised when txtBox loses the foc us since txtBox .Leave is the event fo llow ing the keyword Hand les.
T he name of the eve nt procedure, btnCo mpute_C lick, ca n be an ything; it plays no role in dete rmining the
act ion that raises the eve n t.
2. Th ree poss ibi lities are
txtBox.Enable d = False
txtBox.ReadO nly = True
txtBox.Visib le = False
CHAPTER 2 SUMMARY
1. The Vi ual Ba ic Form Designer displays a form that can hold a collection of controls for
which various properties can be set. Some exa mples of contro ls are tex t boxes, labels, bu t-
tons, and list boxes. Some useful properties are Tex t (se ts the tex t displayed in a contro l) ,
N ame (used to give a meaningful name to a control) , Font.N ame (selects the name of the
font u eel), Font.S ize (sets the size of th e tex t displayed), Font.Bold (displays boldface text),
Font.ltalic (displays italics text) , BackColor (se ts the background color) , ForeColor (sets
the color of the text) , ReadO nly (determines whether tex t ca n be typed into a tex t box
when the program is running), Tex tAlign (sets the type of alignment for the tex t in a con-
tro l), Enabled (determines whether a contro l can respond to user interaction), and Visible
(dete rmines whether an obj ect can be een or is hidden) .
2. A n event procedure is invoked when something happens to a specified obj ect. Some events
are object.Click (object is clicked) , object.Tex tC hanged (a change occurred in the value of
the obj ect's Tex t property), object. Leave (object loses the focus), and object. Enter (object
rece ives th e focus). Note: The statement object.Focus() moves the focus to the specified
object.
3. lntelliSense prov ides a host of features that help you write code.
4. Tab order, the ord er in which the user moves the focus fro m one contro l to another by press-
ing the Tab key while the program is running, can be set from the Properties window.
Variables, Input,
and Output
3.1 Numbers 54
• Arithmetic Operations • Variables • Incrementing the Value of a Variable • Built-In
Functions: Math .Sqrt, Int, Math.Round • The Integer Data Type • Multiple
Declarations • Two Integer-Valued Operators • Parentheses • Three Types of Errors
• The Error List Window
3.2 Strings 68
• Variables and Strings • Option Exp licit and Option Strict • Using Text Boxes for
Input and O utput • Auto Correction • Concatenation • String Properties and
Methods: Length Property and ToUpper, ToLower, Trim, Ind exOf, and S ubstring
Methods • The Empty String • Initial Value of a String • Widening and Narrowing
• Internal Documentation • Line Continuation • Scope of a Variable
3.3 Input and Output 85
• Formatting O utput with Format Functions • Using a Masked Text Box for Input
• Dates as Input and Output • Getting Input from an Input Dialog Box • Using a
Message Dialog Box for O utput • Named Constants • Sending O utput to the Printer
Summary 98
53
54 • Chapter 3 Variab les , lnput, and O utput
3.1 Numbers
Much of the data processed by computers consist of numbers. In co mputerese, numbers are
called numeric literals. This section discusses the operations that are pe rfo rmed with numbers
and th e ways numbers are displayed.
Arithmetic Operations
The fiv e stand ard a rithm e tic o pe rati o ns in Visua l Bas ic are additio n, ubtractio n, multi pli-
ca tion , di v isio n , and ex po n entia tio n . Additio n , subtrac tio n, and di v isio n are den oted in
Visua l Bas ic by th e stand ard sy mbo ls+, -, and/, respect ive ly. H oweve r, the n o ta tio ns for
multi plicatio n and expon enti ati o n differ fro m the c usto ma ry mathema ti ca l n o tatio n s as
fo llo ws:
(The asterisk [*] is the upper ch aracter of the 8 key. The care t [A] is the upper ch aracter of th e 6
key. )
O ne way to show a number on the screen is to d isplay it in a list box. If n is a number, th en
the instruction
lstBox.Items . Add(n)
displays the number n as the las t item in the list box. Add is called a method. (G enera lly, a
meth od is a process that performs a task for a particular o bj ect.) If the parentheses contain a
combination of numbers and arithmetic operations, the Add method ca rri es out the ope rations
and displays the result. Another im portant method is Clear. The statement
lstBox.Items.Cle a r()
Example 1 The fo llowing program applies each of the fi ve arithmetic operations. Pre-
ceding th e program are the fo rm des ign and a table ha wing the names of the obj ects on t he
fo rm and the se ttings, if any, for properties of these obj ects. This form des ign is a lso u' ed in t he
discuss ion and exa mples in the rema inder of this section .
The word "Run" in the phras ing [Run ... ] indicates that the Start Debugging button o r FS
shou ld be pressed to execute the program. N oti ce that in the output 3 / 2 is displayed in dec imal
fo rm. Visual Bas ic never displays numbers a fracti ons. In the evaluation of 2 * (3 + 4 ), th e
operation inside the parentheses is calculated first.
Note: All programs appearing in exa mples and case studies are provid ed on th e companion
website for this book. See the discuss ion on page xv for deta ils.
3.1 N um be rs • 55
Compute
a... 3 -l -1 l = I @) 1
-S':'C..- 1
5
1
6
1.5
9
1-4
Compute
Variables
In applied mathe matics prob le ms, qua nt ities are referred to by n ames. Fo r insta nce, conside r
th e fo llowing high sch oo l alge bra proble m: "If a ca r trave ls a t 50 miles per h our, how fa r wi ll it
t rave l in 14 ho urs? Also, h ow many h ours are required to travel 4 10 m iles?" The so lu t ion to this
proble m uses the well-known fo rmula
[Run, and then click on the button. T he following is displayed in the list box.]
700
8. 2
S kip the second, third , and fo urth lines of the event proced ure for now. We wi ll return to
them soon. T he sixth line sets the speed to 50, and the seventh line sets the time elapsed to 14.
The e ighth line mu ltiplies the va lue fo r the speed by the va lue fo r the time e lap eel and sets the
distance to this product. The nex t line d isplays the an wer to the distance-t raveled question.
The three lines before the End S ub statement answer the time-requ ired qu estion in a similar
manner.
The names speed, timeElapsed, and distance, which hold va lues , are referred to as variables.
Consider the variable timeElapse d. In the seventh line, its value was se t to 14. In the e leventh
line, its va lue was changed as the result of a computat ion. On the other hand, the variable speed
had the same value, 50, th roughout the program.
In ge neral, a va riable is a name that is used to refer to an item of data. The va lue ass igned
to the variable may change during the execut ion of the program. In Visual Basic, variab le
VideoNotc names must begin with a letter or an und erscore, and can consist o nly of letters, digits, and
Numbers und ersco res. (The shortest variab le n ames co nsist of a single lette r.) Visual Basic does not
distingui h between uppercase and lowe rcase letters used in va riab le names. So me examp les
of variab le names are total, numberOfCars, taxRate_2010, and n . As a co nv entio n , we write
variable names in lowe rcase letters except for the first lette rs of each addit io na l word (as in
gracleOnF irstExam). This convent ion is called camel casing.
If var is a variable and n is a numeric literal, then the statement
v ar = n
assigns the number n to th e var iab le var. S uch a state ment is an oth er xa mp le of an assignmen t
statement .
A variab le is declared to be of a certa in type depending o n the sort of data that can be
ass igned to it. The most ve rsa t ile type for hold ing numbers is called Double. A variable308 of type
Double can hold who le, fract ional, or mixed numbers between about -1.8 · 10 and
308
1.8 · 10 . Dim sta tements (also called declaratio n statement s) declare the names and types of
the va riab les to be used in the program. The second, th ird, and fourth lines of this event proce-
dure declare three variab les of type Doub le and give them t he names speed, timeElapsed , and
distance. Variab les must be declared before va lues ca n be assigned to them.
In general, a statement of the form
declares a va riab le named varName to be of type Double. Actua lly, the Dim state ment causes
the comput r to se t a ide a locat io n in me mo ry refe renced by varName. S ince varName i a
3.1 Numbers • 57
numeric va riab le, the Dim state ment ini tially places t he number ze ro in that memo ry loca-
ti o n. (We say that zero is the initial value o r default value of th e variable. ) Each subsequent
ass ignmen t statement h av ing varName to the left of the equ al sign wi ll change the valu e of the
numbe r.
Th e init ia l va lu e ca n be se t to a va lu e o t he r tha n zero. To spec ify a no nzero initia l
va lu e, fo llo w t h e declaratio n state ment with a n equ a l sign fo llowed by the initia l va lu e .
The sta te men t
declares the specified variab le as a va riable of type Double and gives it th e ini tial value 50.
The statement
looks into thi s memo ry locat io n fo rth current valu e of the variable and d isplays t hat valu e in
the list box.
In te lliSe nse prov id es ass istance with bo th declaration and ass ignment statemen ts. Con-
sid er the pa ir of statemen t
In the first statement, Intel! iSe nse will sugges t the wo rd "A " after you type "Dim interestRate ",
and will suggest the word "Double" after you type "Do u" . In the second statement, lntelliSense
will sugge t the word "interestRat e" after you type "inte".
A co mbination of li terals, variab les, and arithmetic operations that ca n be eva lu ated to
yie ld a number is called a numeric express ion. Express io ns are eva luated by replac ing each
vari ab le by its va lu e and ca rrying out the ari thmetic. Some examples of exp ress ions are
2 * di tance + 7, n + 1, and (a+ b) / 3.
Example 2 The fo llowing program di plays the default va lue of a variable and the valu e
of an express io n:
[Run , and then click on the button . T he fo llowing is di splayed in the list box .]
0
3
25
var = expression
58 • Chapter 3 Va ri ables, Input, and O utput
first evaluates the express ion on the right and then ass igns its va lue to the vari able on the left.
For instance, the event procedure in Example 2 can be written as
The expression a* (2 + b) is evaluated to 25, and then this valu e is ass igned to the vari able c.
var = var + 1
is meaningful. It first eva luates the ex press ion on the right (that is, it adds 1 to the value of the
vari able var) and then ass igns this sum to the variable var. The effect is to increase the va lue of
the variab le var by 1. In terms of memory loca tions, the statement retrieves the va lue of var
from var's memory location , uses it to compute var + 1, and then places the sum back into var's
memory location. This type of calculatio n is so common that Visual Bas ic provides a special
operator to ca rry it out. The statement var = var + 1 can be replaced with the statement
var += 1
var += n
The terms insid e the paren theses ca n be numbers (as shown) , numeric variab lls, or numeric
express ions. Exp ress ions are first eva luated to produ ce the mput.
Example 3 The following program eva lu ates each of the fu nctions fo r a pec ific inp ut
given by the va lu e of the variable n:
[Ru n, and then click on the Compute button . The fo ll owing is displayed in the list box.]
2.6
6
6.8
Example 4 The fo llowing program eva lu ates each of the preceding funct ions within an
express ion:
[Run, and then click on the butto n. The fo llowing is disp layed in the list box.]
4
8
0.667
and can be ass igned onl y who le numbers from about -2 billion to 2 billio n. Intege r var iables
are co mmo n ly used for counting.
60 • Chapter 3 Va riab les, Input, a nd O utput
Multiple Declarations
nt. Fo r in tance,
Severa l variables of the sa me type can be decla red with a single Dim stateme
single stateme nt
the two Dim sta tements in Exa mp le 2 can be rep laced by the
Dim a, b As Do ub l e
Example 5 The follow ing program convert s 41 inch es to 3 feet and 5 inches.
.C lick
Private Sub b t nCompu t e _ Cli c k( ... ) Handle s btnCom pute
Dim totalin c hes , fe e t , inches As Intege r
t otalinc hes = 41
feet = to t alinc hes \ 1 2
i n c hes = t otalinc he s Mod 12
l stResu l t s.Items .Add ( feet )
l stResu l t s . I t ems .Add(in c hes)
End Sub
box.]
[Run, and then click on the button. The follow ing is displaye d in the list
3
5
Parentheses
ion. When there are
Parenth eses should be used when needed to clarify the meanin g of an express
the order expone ntiation , multipli ca-
no parentheses, the arithme tic operatio ns are petform ed in
i on. In the event of a
tion and ord inary division, intege r division, Mod, and add it ion and subtract
parenth ese liberally,
tie, the leftmost ope ration is carried out first. See Table 3. 1. Note: If you use
you will not have to rely on the precedence table for arithmetic operations. For instance, write
(2*3) + 4i nstead of 2 * 3 + 4.Write (2 i\ 3) + 4instead of 2 A3 + 4.
Parentheses ca nnot be used to ind icate mul tiplicat ion , as is common ly done in algebra. For
instance, the expression x(y + z) is not va lid. It must be written as x * (y + z).
Also, a ye llow arrow wi ll appear at the left side of the li ne of code that ca used the error. A t that
po int, you should end the program.
A third type of error is called a logic error. Such an erro r occurs when a program does not
perform th e way it was intended. For instance , the line
a v erage = firstNum + secondNum I 2
is syn tac tically correct. H oweve r, an incorrect value will be generated, since the correct way to
calculate the average is
a v erage = ( fi r stNum + second Num) I 2
Logic errors are th e most difficult type to find. Append ix D d iscusses debugging too ls that ca n
be used to detec t and correct logic erro rs.
Example 6 The following program co ntains three errors. Note: Line 1 co nta ~ns the Pub-
lic C lass statement and line 2 is a blank line. T herefore, the Private Sub statement is in line 3
and the Dim statemen t is in line 4.
[Run, click on the button, and click on the No button in the error di a log box that appears. ]
·~X
Error List
3 Errors f 0 tVarning s i) 0 Mes,sage
Comments
1. Declaring variables at the beginning of each event procedure i regarded as good programming
practice, because it makes programs ea ier to read and helps prevent certain types of error .
2. Keywords (reserved words) cannot be u ed as names of variables. Fo r in tance, the state ments
Dim private as Double and Dim sub As Double are not valid.
3. Names given to variables are sometimes referred to as identifiers.
4. In math courses, literals are referred to as constants. H owever, the word "constant" has a special
meaning in programm ing languages.
5. Numeric literals used in express ions or ass igned to variab les must not contain commas, dollar
signs, or percent signs. A lso, mix ed numbers, uch as 8 1/2, are not allowed.
6. A lthough requesting the square root of a negative number does not terminate the execution
of the program, it can produce unexpecte d resu lts. For instance, the statement
lstBox.It ems.Add (Math.Sq rt(-1))
8. When n is halfway between two success ive who le numbers (such as 1.5 , 2.5, 3.5, and 4.5 ),
then it round to the neares t even number. For instance, Math. Round (2.5) is 2 and
Math.Rou nd (3.5) i 4.
9. In scientific notatio n, numbers are written in the form b · lOr, where b is a number of mag-
nitude from 1 up to (but not includ ing) 10, and r is an integer. Visual Basic di plays very
large number in scientific notation, where b · lOr is written as bEr. (The letter E is an
abbrev iation for exponent.) For instance, when the state ment lstBox. Items .Add ( 123 *
10 A15) is executed, 1. 23 E+ 17 is displayed in the list box.
10. If the tota l number of items added to a list box exceeds the number of item that can bed is-
played, a vertical croll bar i aut matica lly added to the li t box.
11. When you first enter a stateme nt such a Dim n As Double, a green sq uigg le will appear
under the variable name and the Error List window wi ll record a warning. The squ igg le
3.1 Nu mbers • 63
merely indicates that the variable has not yet been ass igned a va lue.
If the squiggle i still
presen t after the en tire event proced ure has been entered, this will
te ll you that the va ri ab le
was never used and that the declara t ion statement should be remove
d.
1. Evalua te 2 + 3 * 4.
2. Explain the d iffe rence betwee n the ass ignmen t statemen t
varl = var2
and the ass ignmen t statement
var2 = varl
3. Co mplete the tab le by filling in the va lue of each va riable after each
li ne is execut ed.
a b c
Privat e Sub btnEv aluate Click ( ... ) Handle s btnEv
aluate .Click
Dim a, b, c As Double
0 0 0
a = 3
3 0 0
b = 4
3 4 0
c = a + b
a = c * a
ls tResu lts .I tems.A dd(a - b)
b = b * b
End Sub
y = 3 * X
X - y + 5
lstRe sults .Item s.Cle ar()
lstRe sults .Item s.Ad d(x + 4)
y - y + 1
End Sub
30.
bal inter withD r
61. The fo llowing steps calculate the price of an item after a 30% reducti on:
(a) Declare all variables as type Double .
(b) Ass ign the value 19.95 to the variable JJrice.
(c) Ass ign the va lue 30 to the variable discountPercent.
the variab le
(d) A ssign the value of (discountPercent divided by 100) times price to
markdown.
(e) Decrease price by markdown.
(f) Display the value of price (rounded to two decima l places ) in a list box.
of units of goods
62. The followin g steps ca lculate a company's break-e ven po int, the number
the compan y must manufacture and sell in order to break even :
(e) A sign the value fi xedCos ts divided by (the difference of price PerUnit and costPerUnit)
to the variable breai<EvenPoint .
(f) D i play the va lue of the variable breakEvenPoint in a list box.
63. The follow ing steps calculate the balance after three years when $ 100 is depos ited in a sav-
ings acco unt at 5% interest co mpounded annu ally:
(a) Declare all variables as type Double.
(b) A sign the value 100 to the variable balance.
(c) Increase the va riable balance by 5% of its va lu e.
(d) Increase the variable balance by 5% of its value.
(e) Increase the va riable balance by 5% of its value.
(f) D i play th va lu e of balance (rounded to two dec ima l places ) in a list box.
64. The follow ing steps calcu late th e balance at the end of three year when $ 100 is depos it d
at the beginning of each yea r in a sav ings account at 5% interest co mpounded annu ally:
(a)Declare all va riab le as type Do uble.
(b)Ass ign the value 100 to the variable balance .
(c)Increase the variable balance by So/o of its va lu , and add 100.
(d)Increase th e va riable balance by 5% of its va lue, and add 100.
(e)Increase the variab le balance by So/o of its va lue.
(f)Disp lay the va lue of balance (round ed to two dec ima l places ) in a list box.
65. The fo llowing steps calculate the balance after 10 years when $ 100 is depos ited in a savings
account at 5% interest compound ed annu a lly:
(a) Declare a ll va riab les as typ Double.
(b) As ign the va lue 100 to t he variable balance .
(c) Multiply the variable balance by 1.05 ra ised to the l Oth power.
(d) D isp lay the va lue of balance (round ed to two dec imal places ) in a list box.
66. The fo llow ing steps calculate the percentage profit from the sa le of a stock:
(a) Declare all va riables as type Double.
(b) Ass ign the va lue 10 to the variable fJurchase Price.
(c) Ass ign the va lu e 15 to the va riable sellingPrice .
(d) A ss ign , to the vari able percentPro fit , 100 times th va lu e of the difference between
sellingPrice and purchase Price d ivided by fJurchasePri ce .
(e) Display th e va lue of the variable percentProfit in a list box.
In Exercises 67 through 72, write a program to solve the problem and display the answer in
a list box. The program should use variables for each of the quantities .
67. S uppose each acre of farmland produces 18 tons of co rn. H o w man y tons of corn can
be
prod uced on a 30-acre fa rm ?
68. S uppose a ball is thrown stra ight up in the air with an initial ve locity of 50 feet per second
and an ini tial he igh t of 5 feet. H ow high will the ba ll be after 3 seco nds?
Note: The he ight after t econds i given by the ex pres ion - 16t 2 + v t + h , where v is
0 0 0
the initia l velocity and h0 is the initia l he ight.
69. lf a ca r left Washingt on , D.C., at 2 o'clock and arrived in N ew Yo rk at 7 o'clock, what
was
its ave rage speed ? Note: New Yo rk is 233 miles from Washingt on.
70. A motorist wants to determine her gas mileage. At 23,3 52 miles (on the odo meter)
the
ta nk is fi lled. A t 23,695 miles the tank i fill ed aga in with 14 ga llons. H ow many miles pe r
ga llo n did the ca r average between the two fillings?
68 • Chapter 3 Variables, Input, and O utp ut
a b c
3.2 Strings
strings. Senten ces,
The most commo n types of data processed by Visua l Bas ic are numbers and
, and social security
phra es, words, letters of the alphabe t, name , telepho ne number s, addresse
e of ch aracters that is
numbers are all exampl es of strings. Formall y, a string literal is a sequenc
d in text boxes and
treated as a single item. S tring litera ls can be ass igned to vari ables, displaye
nation (d enoted by&).
list boxes, and combin ed by an operatio n called concate
ass igns the string literal xy . . . z to the variabl e and the statement
or
l 'i( l...;a...J
Optio ns
_-Jl [
..___o_ K Ca ncel
Show all settings
and
and
Example 2 The fo llow ing progra m add s two numb ers suppl ied by
the user.
Second
number: 55
Compute Sum
Sum : 100
Auto Correction
The A u to Corre ction featur e of lntelliSe nse sugges ts
correc tions when erro rs occur and allows
yo u to se lect a correc tion to be app lied to the code.
When an inva lid statem ent is entered, a
blue squigg ly erro r line appea rs under th e incorr ect
part of the statem ent. If the squigg ly line
has a short red lin e segme nt at its right end, the A uto
Corre ction featur e is ava ilable fo r the
error. Whe n you h over the curso r ove r the sq uigg ly line,
a sma ll Error Co rrectio n Optio ns box
(~ ) appea rs. C lickin g on the small box produ ces an Au
to Corre ction helpe r box that descri bes
the error and makes a suggestion fo r fixing it. Figure 3.2
shows a typ ical A uto Corre ction h elper
box for a data-t ype-c on vers io n error. If you click on
the line begin ning "Replace," the change
will be made for you.
72 • Chap ter 3 Varia b les, In put, a nd O utput
Concatenation
g cons isting of the strin g jo ined together. The
Two strin gs can be comb ined to form a new strin
is repre sented by an am per and ( &) . For
jo ining ope ratio n is called conc atena tion and
inat ion of tr ings and ampe rsands that can be
insta nce, "good" & "bye" is "goodbye". A comb
essio n. The ass ignm ent state ment and the Add
evalu ated to fo rm a strin g is called a strin g expr
them or d isplay ing them .
meth od evalu ate exp ressio ns before ass igning
The statement
will appenJ the value of strVar2 to the end of the current value of strVar. The same result ca n
be acco mplished with the statement
String Properties and Methods: length Property and ToUpper, Tolower, Trim,
lndexOf, and Substring Methods
We h ave seen that controls, such as tex t and list boxes, have propertie and methods. A control
placed o n a form is an exa mple of an obj ect. A string is also an obj ect, and, like a control, has
both properties and meth ods that are specified by following the string with a period and the
n ame of the property or method. The Length property gives th e number of characters in a
tring. Th e ToUpper and ToLower meth ods co nvert a string to uppercase and lowercase char-
acte r . The Trim method de letes a ll lead ing and trailing spaces from a string. The Substring
method ex tracts a seq uence of consecutiv e ch aracters fro m a string. The Ind exOf method
ee1 rche for the first occurrenc e of one string in ano ther and gives the pos ition at which the
first occurrenc e is fou nJ .
If str is a string, then
str.Leng th
str.ToUp per
str.ToLow er
str.Trim
is the string with all spaces removed from the front and back of th e string. Fo r instance,
In Visual Bas ic, the position of a character in a string is identified with one of the numbers
0, 1, 2, 3, ... . (In this textbook we will see several instances of enum erati on beginning with 0
instead of 1.) A substring of a string is a sequ ence of consecutiv e ch arac ters from the string. For
instance, consider the string "Just a mo ment". The substrings "Jus", "mom", and "nt" beg in at
positions 0, 7, and 11 , respective !y.
If str is a tring, then
str.Subst ring(m, n)
is the substring of str consisting of 11 characters beginning with the character in pos ition m of str.
If the co mma and the number 11 are omitted , then th e substring starts at pos itio n m and contin-
ues until the end of str. The value of
str.Index 0f(str2)
74 • Chapter 3 Va ri ab les, In put, and O utput
str2, n) , where n
The Index Of method has a useful exte nsion. The va lue of str. IndexO f (
n n or greater. For
is an integer, is the position of the first occurre nce of str2 in str in po itio
instance , the va lue of "Missi ssippi" . IndexO f ( "ss", 3) is 5.
s also can be
Like th e num eric function s di scussed before, string properti es and method
app lied to variables and exp ress ions.
Example 5 The fo llow ing program uses variab les and expressions with th e propert y and
method s just discussed .
lick
Private Sub btnEva luate Click( . .. ) Handle s btnEva luate.C
Dim str1, str2, str3 As String
str1 = "Quick as "
str2 = "a wink"
lstRes ults.Ite ms.Cle ar()
lstResu lts.Item s.Add( str1.Su bstring (O, 7))
lstResu lts.Item s.Add( str1.In dexOf( "c" ))
lstResu lts.Item s.Add( str1.Su bstring (O, 3))
lstRes ults.Ite ms.Ad d((str1 & str2) .Subst ring(6, 6))
lstRes ults.It ems.A dd((str l & str2) .ToUpp er)
lstResu 1ts.Ite ms.Ad d(str1. Trim & str2)
str3 = str2.Su bstring (str2.L ength 4)
lstResu 1ts.Item s.Add( "The averag e " & str3 & " lasts .1 second ." )
End Sub
box.]
[Run, and then click on the button. The fo llow ing is di played in the list
Quick a
3
Qui
as a w
QUICK AS A WINK
Quick asa wink
The averag e wink lasts .1 second .
Example 6 The follo wing program parses a name. The fifth line locates the pos ition,
n charact ers, and
call it n, of the space separati ng the two names. The first nam e will contain
the last name wi ll cons ist of all charact er to the right of the nth charact er.
lick
Private Sub btnAna 1yze_ Click( ... ) Handle s btnAna lyze.C
Dim fullNam e, firstNa me, lastNam e As String
Dim m, n As Intege r
fullNam e = txtNam e.Text
3.2 trings • 75
t of the form
is va lid . However, a narr owin g tate men
intV ar = dblV ar
Dim m As Inte ge r
m 2 3
m = 6 I 2
o r iden tify-
use va riables of type Integer fo r coun ting
In orde r to avo id such erro rs, we prim arily
ing pos ition s.
Internal Documentation
nt of the pro-
io n of com men ts that spec ify the inte
Prog ram doc ume ntat io n is the inclus l port ions of the
the tas ks perf orm ed by indi v idua
gram, the purp ose of the va riabl es, and S uch a state -
t, beg in the line with an apos trop he.
prog ram. To crea te a co mm ent state men is exec uted .
is co mpl ete ly ign o red whe n the prog ram
men t appe a rs gree n on t he sc ree n and addi ng an
. A line of code can be doc ume nted by
Com me nts are so met imes ca lled rem arks ne. The Com men t
rma t io n , aft er the e nd of the li
apos trop he, fo llowed by the desi red info used to com -
butt o n ( "l ) o n the Too lba r ca n be
Out butt on ( ·=:: ) a nd th e Unc omm ent
of code .
men t and unco mm ent selec ted bloc ks
line Continuation
Tho u ands of char acte rs can be typed in
a line of code. lf you use a state men t with
acte rs than can fit in the window, Visu more ch ar-
al Basic scro lls the Cod e Edit or towa rd
need ed. However, mos t programmers pref the righ t as
er havi ng lines that are no longe r than
the Cod e Editor. A long state men t can the widt h of
be split acros two or more lines by endi
(exc ept the last) with an und ersco re ch ng each line
arac ter ( _ ) prec eded by a space. For insta
nce, the line
Dim quo tati on As Stri ng= "Goo
d code is its own bes t doc ume
ntat ion. "
can be writ ten as
Dim quo tati on As Stri ng "Goo d code is its own " &
"be st doc ume ntat ion. "
( Push Me
Comments
ng the mo use
rmin e the type of a variab le by letti
1. From the Cod e Edit or, you can dete Thi s feat ure of
unti l a too lt ip giving the type appe ars.
poin ter hov e r ove r the vari able name
lnte ll iSen se is ca lled Qui ck Info .
mm ers use a pre-
Va riab le nam es shou ld desc ribe the role of the var iable. A lso, so me progra
2. wou ld use nam es
type of a vari ab le. For examp le, they
fix, such as dbl o r str, to iden tify the t need ed in Visu al Basic
Thi s nam ing con ven tio n is no
like dbll nterestRate and strFirstN ame. Mic rosoft.
t 1, and is no longer reco mm nde d by
for the reason men t ioned in Com men
ber into a text box
use r friend ly. If the use r types a num
3. The func tion s C lnt and C Ob! are the va lues of
or inse rts com mas as sepa rato rs,
and precedes it with a doll ar sign llar sign and /or
lnt( txtB ox.T ex t) and CD bl(tx tBox .Tex t) wi ll be the num ber with the do
C
com mas rem oved.
es use r type spaces
adin g data from a tex t box . Som etim
4. The Trim met hod is useful wh n r hav oc elsewhe re in
s are rem oved, they can cause
at the end of the input. Unles the pace
the program.
For inst ance, th e
tr for cast ing a va lue to a strin g valu e.
5. The re are seve ra l a ltern atives to CS
state men t
strV ar = CSt r(db lVa r)
3.2 Strings • 79
(a) These funct ions make state ments less clutte red,
and therefore eas ier for begin ning pro-
gram mers to read.
(b) Whe n an inco rrect conv ersio n is detec ted by
the Code Ed ito r, the Aut9 Correction
helper box recommend s and imple ments the use of
the CStr, CDb l, and C lnt function .
34. The following steps comp ute the pr ice of ketch up:
(a) Decla re all variables used in steps (b)- (d).
(b) Ass ign "ketc hup" to the va riab le item.
(c) Assig n 1.80 to the variab le regularPrice.
(d) Ass ign .27 to the va riab le discount.
"
(e) D isp lay the phrase "1.53 is the sa le price of ketch up.
t:
35. The following steps display a copyright sta temen
(a) Decla re the variab le used in step (b).
(b) Ass ign "Pren tice H all, Inc." to the vari able publish
er.
(c) Display the phras e "(c) Prent ice H all , Inc."
Compute Distance
Compute THR
The distance of the storm is 0.25 miles . Your T H R is 161 beats per minute .
Sample outpu t of Exercise 39. FIGURE 3.4 Sampl e outpu t of Exerc ise 40.
FIGURE 3.3
0.6 pounds were lost . The Yankees won 56.66 7 percent of their
games .
FIGURE 3.5 Sam ple outp ut of FIGURE 3.6 Sam ple outp ut of
Exer cise 41.
Exer cise 42.
42. Wri te code to read the nam e of a
base ball team, the num ber of gam es won
of ga mes los t, and disp , and the num ber
lay the nam e of the team and the pe rce
ple run is show n in Fig. 3.6. ntage of gam es won . A sa m-
verage
score :
5
Dim x As Dou ble = "23" Repl ace "'2 "' with 'CDbl("23")'.
ext) '.
dblV ar txtB ox.T ext Repl ace 'txtBox.Text' with 'COb !( txtB ox.T
Replace '2 & 3' with 'CDb l(2 & 3)'.
dblV ar = 2 & 3
3.3 Input and Outpu t
• 85
FUNCTION
STRING VALUE
Forma tNumb er(1 + Math .Sqrt( 2), 3)
2.414
Forma tCurre ncy(-1 000)
($1,00 0.00)
Form atPerc ent(". 05")
5.00%
9L_ == ==
(a) (b)
l 'Y 1- .n. J
Inpu Mask
Preview:
[ OK l[ Cance l )
Toda y
c Bi rth Data
l= I[§J I. --"'2. .I
Compute Data
ente r 4/6/1992
[Ru n, clic k on the button, ente r Emm
a Smith into the first inpu t dialog box, and
into the seco nd inpu t dia log box.]
Title Consolation
OK
Named Constants
prog ram xecu -
a prog ram uses a spec ia l con stan t whose value doe n ot cha nge duri ng
Ofte n nam e of a mas ter
imu m wage, the sales tax rate, and the
tion . So me exampl es mig h t be the min
3.3 Input and O utput
• 91
whe re 100
va lues of x and y are spec ified in poin ts,
page of the begi nning of the string. (The po ints from the left
c inde nt all text by abou t 25
poin ts are abou t one inch .) Visual Basi left side
will be prin ted x + 25 po ints from the
side of the page. The begi nnin g of the tring wi ll be
. Two diffe rent ways of spec ifyin g the font
and y poin ts from the top ide of the page
give n in the example that follows.
5. Place the state men t
Prin tDoc ume nt1 . Prin t()
t will
on's C lick eve nt procedur e. (Thi s state men
in anot her eve nt proced ure, such as a butt
be prin ted.)
ca use all of the tex t spec ified in step 4 to
ts are as follows. The state men t
Some exa mp les of DrawStri ng state men
150)
Me .Fon t, Bru shes .Dar kB1 ue, 100,
gr.D raw Stri ng( "HELLO WORLD" ,
inch es from
g the form's font in dark blue lette rs 1.25
prin ts the words HELLO WO RLD usin men ts
the top of the page. The pa ir of state
the left side of the page and 1.5 inch es from
r New" , 12, Fon tSty le .Bol d)
Dim font As New Fon t ( "Co urie 150)
fon t, Bru shes .Dar kBlu e, 100 ,
gr.D rawS t ring ( "HELLO WORLD" ,
bold Co urier N ew font.
produce the same outpu t usin g a 12-po int s you
Prin tPre view Dial og cont rol, whic h allow
Visual Bas ic prov ides a control, called the step :
end it to the prin ter. Just fo llow two
to ee how outp ut will look befo re you
cont ro l in the All Windows Forms or Prin
ting grou p
1. Double-click on the Prin tPrev iewDialog 1 in the
with the defau lt name Prin tPrev iewDialog
of the Too lbox. (Th e cont rol will appear
Designer.)
co mpo nent tray at the bott o m of the Form
2. Place the pair of state men ts
Prin tPre view Dial og1 .Do cum ent
= Prin tDoc ume nt1
wDi alog ()
Prin tPre view Dia log1 .Sho
tatem ents
button's C lick even t procedu re. These
in anot her eve nt proced ure, such as a di splayed
ume ntl _PrintPage even t proced ure to be
ca use the text spec ified in the Prin tDoc ow's
nt procedu re is invo ked . The prev iew wind
in a "Print prev iew" window whe n the eve
too lba r co ntains a mag nifying-g la s butt
on ( p T)
that allows you to zoom in on the text.
Comments
1. A va ria tion of the DateD iff functi on discu sed ea rlie
r is DateD iff (Date inter val . Year,
d1, d2) whi ch gives the numb er of yea rs (so
rt o f) betwe en the two da tes. It is of limite d
va lue, since it only uses the year pa rts of the two dates
in its co mp uta tion.
2. The sectio n "Use the Printe r" in A ppe ndix B shows
h ow to print a progra m and a fo rm .
EXERCISES 3.3
t produ ced by the lines of code.
In Exerc ises 1 throu gh 4 8, deter mine the outpu
1. txtOu t put.T ext Form atNu mber (l234 .56, 0)
16. txtO utpu t . Text Form atCu rrenc y(32 * (10 A 2))
29. txtO utpu t.Tex t "The likel ihoo d of Head s is " &
Form atPe rcen t(l I 2, 0)
, 4)
30. tx t Outp ut.Te xt "Pi = " & Form atNu mber (3.14 1592 6536
64. Pop up a message dia log box with "Taking R isks Prove rb" in the title bar and th e message
"You can 't steal second base and keep o ne foot on first."
In Exercises 65 and 66, write an event procedure with th e header P r ivate Sub bt n com -
and h aving one, two, or th ree lines for each
pute cl i ck ( ... ) Handle s b t nComput e . Click,
step.-Lines that display data should use the given va riable names.
65. The following steps calcu late the percent increase in the cost of a typical grocery basket of goods:
(a) Decla re all variab les used in the steps that follow.
(b) Assign 200 to the variab le begOfYearCost.
(c) Req uest the cost at the end of the yea r with an input dialog box, and a sign it to the
va riable endOfYearCost.
(d) Ass ign (endOfYearCost- begOfYearCost) / begOfYearCost to the variab le JJercentlncrease .
(e) Display a sentence giv ing the percent increase for the year.
(Test the program with a $2 15 end -of-yea r cost. )
66. The following steps calculate the amo unt of money ea rned in a wa lk-a-tha n:
(a) Declare a ll var iab les used in the teps that follow.
(b) Request the amou nt pledged per mile fro m an input dia log box, and ass ign it to the
variab le pledge.
(c) Request the number of miles walked from an input dia log box, and ass ign it to the vari-
ab le miles.
(d) Disp lay a sentence giving the amo unt to be paid.
(Tes t the program with a pledge of $2.00 per mile and a 15-mile walk.)
67. Write a program that requests a year in a masked tex t box and then displays th e nu mber of
days in the year. Hint: Use the A ddYears method and the DateDiff functio n.
68. Write a program that calculates the number of days since the Declaration of Independence
was ratified (7/4/1776).
69. Write a program that reques ts a date in a masked text box, and then displays the day of the
wee k (such as S und ay, Mo nday, ... ) for that date.
70. Write a program that req uests a date as input and then displays the day of the week (such as
S und ay, Monday, . .. ) for that date ten years hence.
71. Write a program that reques ts a mo nth and a yea r as input and then displays the number of
days in that month. Hint: Use the AddMonths method.
72. Write a program that req uests the use r's da te of bi rth and th en disp lays the da y of the
week (such as S und ay, Mo nd ay, . . . ) o n which th ey will h ave (or h ad) the ir 21 st
birthday.
73. Design a form with two text boxes labeled "Name" and "Phone number". Then wr ite an
eve nt procedure that shows a message d ia log box stating "Be sure to include the area code!"
when the second text box receive the foc us.
74. Write a program to calcu late the amount of a se rver's tip given the amo unt of the bill and the
percentage tip obta ined via input dialog boxes. T he output should be a complete sentence
that reiterates the inputs and gives the resulting tip, as shown in Fig. 3.14 on the nex t page.
75. When P dollars a re depos ited in a sav ings acco unt at interest ra ter co mpo und ed a nnu -
a lly, the ba lance aft er n yea rs is P ( 1 + r)". W rite a program to req ues t the principal P VideoNote
Mortgage
and the inte res t ra ter as input, a nd co mp ute the ba lance after 10 yea rs, as sh own in
ca lcu lator
Fig. 3. 15 on the next page. (H omework)
98 • Chapter 3 Variab les, Input, and O utpu t
Principal:
Compute Balance
Enter Data
76. Write a program to print the list of Interne t lingo in Fig. 3 .16.
PLS Please % of
TAFN That's all for now Rank Countr y WW Users
HHOK Ha, ha - only kidding 1 USA 16.0%
FWIW For what its worth 2 China 11.9%
IMO In my opinion 3 Japan 6.5%
FIGURE 3.16 Output of Exercise 76. FIGURE 3.17 Output of Exercise 77.
age of worldwide
77. Write a program to print the top three ranking counties by the percent
Interne t u er they contain as shown in Fig. 3.17.
CHAPTER 3 SUMMARY
numbers, strings,
1. Three types of literals that can be stored and processed by Visual Basic are
and dates.
the content of a
2. Many Visual Bas ic tasks are carried out by method s such as C lear (erases
ts a string to
text box or list box), Add (places an item into a list box), ToUppe r (conver
Trim (remove s lead ing and trailing
uppercase), Tol ower (converts a string to lowercase ),
and gives its pos i-
spaces from a string), lndexO f (searches for a specified substrin g in a string
from a string).
tion if found), and Substrin g (produces a sequence of consecutive charact ers
ion is&, con-
3. The arithmetic operations are +, -, *,/,A,\ , and Mod. The only string operat
, variab les, function s, and operat ions
catenat ion. An expression is a combin ation of literal
that can be evaluat ed.
letter or an under-
4. A variable is a name used to refer to data. Variable names must begin with a
score and may contain letters, digits, and underscores. Dim stateme nts declare variables,
Summ ary
• 99
12. The Date data type fac ilitates comp utatio ns invo lving
dates.
13. An input dialog box is a windo w that pops up and
displays a message fo r the user to respon d
to in a tex t box. The respo nse is ass igned to a
variable.
14. A message dialog box is a wind ow that pops up
to display a message to the user.
15. Named constants sto re va lu es that canno t change durin
g the execu tion of a progra m. They
are decla red with Cans t statem ents.
l= 1-£1 -~J
ll _. Calcu lator l = I @) l,...tJ J a ~ A -1 Auto Repai r
@)
21 D 77
Cost of parts
and supplies :
84.55 Bill
J
21 ll 77
w
= 1 617
Custo mer
Labo r cost
Paz:ts cost
Tota l cost
John oe
$ 1 22.50
$88 . 78
$211 . 28
Yards : 20
( Determine Composition of Change ) The metric length is
8 kilometers
Feet : 2 65 meters
Quarters : 3 Dimes :
73.5 centim eters .
Inches : 4
Nickels : Cents : 3
meters into a whole number of kilomet ers and meters. The number of centime
ters should
be d i played to on e dec imal place. The needed formulas are as foll ows:
Location : Milwaukee . WI
Meals and entertainment : 19 .10
Lodging : 675.35
Taxi fares : 45
FIGURE 3.22 Form with sample data for Program ming Proj ect 5.
FIGURE 3.23 Output for sample run of Program ming Proj ect 5.
De cis ion s
103
104 • Chap ter 4 Dec isio ns
ANSI Values
riter porti on of the keyb oa rd ca n produ ce two
Each of the 4 7 diffe rent keys in the cente r typew ba r
ng 1 for the character prod uced by the space
chara cte rs, fo r a tota l of 94 characters . Addi m 32 to 126.
chara cters are numb ers rang ing fro
makes 95 characters. Associate d with these A.
lu es of the chara cte rs, are give n in Appe nd ix
These va lu es, calle d the A N SI (or ASC II) va
Table 4.1 shows a few of them .
Chr (n)
I va lue n. If str is any stri ng, th en
is the strin g cons isting of the character with ANS
As c ( s t r )
tx t Bo x. Tex t = Chr (6 5)
state ment
displays the lette r A in the tex t box, and the
txtB ox.T ext = 32 & Chr( 176) & " Fah renh eit"
disp lays 32° Fahrenh eit in the text box.
The quot atio n-m a rk char acte r ( • ) can
be plac ed in to a strin g by usin g C hr(3
4 ). Fo r exam -
ple, after the sta tem ent
tx tBo x.Te xt = "Ge orge " & Chr( 34) & "Bab e"
& Chr( 34) & " Ruth "
is exec uted , the text box cont ains
Geo rge "Bab e" Ruth
Relational Operators
The relat iona l operator less than ( <)
can be app lied to num bers, strings, and
ber a is sa id to be less than th e num date s. The num -
ber b if a lies to the left of b on the Vidco Notc
insta nce, 2 < 5, -5 < -2, and 0 < num ber line. For
3.5. Relati onal
The strin g a i sa id to be less than the anJ logical
strin g b if a prec ede b a lpha bet ica lly whe
ANS I tab le to a lpha betiz e the ir valu n usin g the operators
es. For insta nce, "cat " < "dog", "car
"cat " < "cat a log". Digits prec ede uppe t" < "cat", and
rcase lette rs, whic h prec ede lowerca e lerte
ar com pared work ing from left to righ rs. Two strin gs
t , char acte r by char acte r, to dete rmin e
prec ede the other. The refore, "9W " < wh ich one shou ld
"bat ", "Do g" < "cat ", and "Sales-9 9"
The date dl is sa id to be less than < "Sa les-r etail ".
the date d2 if dl prec ede d2 chro no
insta nce, # 12/7 /194 1 ;;- < #6/6 / 1944#. log ica lly. For
Tab le 4.3 shows the d iffe rent re latio nal
operato rs and thei r mea nings.
lt!1:J!IIM Relational operators .
Visual Basic Num eric String Date
Nota tion Meaning Meaning Meaning
equa l to identical to sa me as
<> not equa l to different from
< different than
less than precedes alphabet ica ll y
> precede chro nolog ica ll y
greater than foll ows alphabeticall y
<= foll ow chro nologica ll y
less than or equa l to precedes alphabetically precedes chro nologica lly
or is identi ca l to or is the same a
>= greater than or equa l to fo ll ows alphabetica lly fo llows chro nologica ll y
or is iden tica l to or is the same as
SOlUTION
(a) True. The no tatio n <= mea ns
"less than or equa l to." Tha t is, the cond it io n i tru e
vide d e ithe r of the two c ircum stan ces pro-
ho lds. The seco nd o ne (equal to) ho lds.
(b) False. The nota tion < mea ns "stri
ctly less than " and no num ber ca n be
itse lf. stric tly less than
106 • Cha pter 4 Dec ision s
To de term ine
s, num eri c ope rato rs, and func tio ns.
Con ditio ns also ca n in vo lve vari able ress ion s and then
first eva luat e the num eric or strin g exp
whe ther a con d ition is tru e o r false,
e o r false.
dec ide if the resul ting asse rtion is tru
(a) (a + b) < 2 * a
(b) (c.Length - b) = (a/2 )
(c) c < ("good" & d )
SOLUTION
ditio n is true.
valu e of a + b is 7 and the valu e of 2 *a is 8. Because 7 < 8, the con
(a) The
- b is 2, the sam e as (a / 2) .
(b) True , beca use the va lu e of c.Le ngth
the AN SI tabl e.
e" is fal e, beca use "h" follows "g" in
(c) The co ndit ion "hello" < "goo dby
logical Operators
e con side red so far.
more complex con ditio ns than thos
Prog ram min g situ atio ns ofte n require variable, n , is stric tly
to stat e that t he va lue of a num eric
Fo r insta nce, supp ose we would like
ic con ditio n is
betw een 2 and 5. The proper Visual Bas
con dl Or cond 2
ditio n
) is tru e. O therwise , it is fa lse. The con
is tru e if eith er condl or cond 2 (or both
Not con dl
l is true.
is true if cond l i false, and is fa lse if cond
4.1 Relationa l and Logical Operators
• l07
Example 3 Supp ose the nume ric varia ble n has value 4 and the
string variable answ has
value "Y". Dete rmine whet her each of th follow ing
cond itions is true or fa l e.
(a) (2 < n) And (n < 6)
(b) (2 < n) Or (n = 6)
(c) Not (n < 6)
(d) (answ = "Y") Or (answ = "y")
(e) (answ = "Y") And (answ = "y")
(f) Not ( answ = "y")
(g) ((2 < n) And (n = 5 + 1)) Or (answ ="N o")
(h) (( n = 2) And (n = 7)) Or (an w = "Y")
(i) (n = 2) And ((n = 7) Or (answ = "Y"))
SOLUTION
(a) True, because the cond ition (2 < 4) and ( 4 < 6) are both true.
(b) True, because the co nditio n (2 < 4 ) is true. The fact that the cond ition ( 4 = 6) is fa lse
does not affect the conclusion. The only requireme
nt is that at least one of the two cond i-
tions be true.
(c) False, because ( 4 < 6) is true.
(d) True, because the first co nditio n become ("Y"
= "Y") when the va lue of answ is substi-
tuted for answ .
(e) False, because the second cond ition is false.
Actu ally, th is comp ound cond ition is fa lse fo r
eve ry va lue of answ.
(f) T ru e, because ( "Y" = " y") ts
· £1a lse.
(g) False. In th is logica l expression, the comp
ou nd cond ition ( (2 < n) And ( n = 5 + 1))
and the simple cond ition (answ = "No" ) are joine
d by th logica l opera to r Or. Beca use
both these cond itions are false, the tota l cond ition
is false.
(h) True, because the secon d Or clause is tru e.
(i) False. Co mparing (h) and ( i) shows the
necessity of using paren theses to specify the
inten ded gro uping .
Dim x As Integ er = 5
txtBo x.Te xt = CStr ((3 + x) < 7)
strin g
with ing. To gene ralize, if strVar2 is anot her
is true if and only if the valu e of strVar ends
variable, then the exp ression
(1)
- strV ar2. Len gth) = strV ar2
strV ar.S ubS trin g(st rVa r.len gth
A Boolean-Valued Function
box or
e if a va lue inpu t by the user, say in a text
The lsNu meri c func tion is used to dete rmin
mpu tatio ns. The value of
inpu t d ialog box, can be used in num eric co
Comments
1. A cond ition in vo lvin g num eric vari
ables is diffe rent from an algebraic truth
(a + b) < 2 *a, cons . The assertion
idered in Example 2, is not a va lid alge braic
for all va lues of a and b. W hen enco unte truth beca use it isn't tru e
red in a Vi ual Basic prog ram, however,
considered true if it i corr ect for the curr it will be
ent va lues of the varia bles.
2. Con ditio ns evaluate to eith er True
or False . Th ese two valu es ofte n are ca lled
trut h valu es of the cond ition. the possible
3. A cond ition such a 2 < n < 5 shou
ld neve r be used, beca use Visual Bas ic will
ate it as inte nded. The corr ect cond ition not evalu-
is (2 < n ) And (n < 5).
4. A com mon erro r is to replace the cond
ition Not (n < m) by the condit ion (n
corr ect rep lace men t is ( n > = m). > m). The
. Ass ume a = 2
whether the con ditio n is true or false
In Exe rcises 7 th rough 18, dete rmin e
and b = 3.
7. 3*a =2 *b
8. (5- a)* b < 7
9. b <= 3
10. a/\b = b/\a
11. a/\ (5 - 2) > 7
12. 3E- 02 < .01 *a
13. (a < b) Or (b < a)
14. (a *a < b) Or Not (a* a <a )
15. Not (( a< b) And (a < (b +a) ))
)
16. Not (a < b) Or Not (a < (b +a)
( b < a) And ( 2 * a < b))
17. ( (a = b) And (a * a < b * b) ) Or (
a< b) Or (b =a + 1))
18. ((a = b) Or Not (b <a )) And ((
.
e whether the con ditio n is true or false
In Exercises 19 through 3 0, dete rmin
19. "9W" < > "9w"
20. "Inspector" < "gadget"
21. "Ca r" < "Train"
22. "]" >= "]"
23. "99" > "ninety-nine"
24. "B" > " ?"
")
25. ("Duck" < "pig") And ("p ig" < "big
26. "Duck" < "Duck" & "Duck"
"))
27. N ot ( ("B" = "b") Or ("Big" < "big
28. # 7/4/177 6# >= # 7/4/ 1776#
29. #6/17/1775# <= # 7/4/177 6#
30. (7 < 34) And ("7" > "3 4")
are equi vale nt -
e whether or not the two con ditio ns
In Exercises 31 thro ugh 40, dete rmin ables appearin g
se for exac tly the sam e valu es of the vari
that is, whether they will be true or fal
in them.
31. a < = b; (a < b) Or (a = b)
32. Not (a < b); a > b
33. (a= b) And (a< b); a< > b
b) And (a <> c)
34. Not ((a = b) Or (a= c)) ; (a< >
35. (a < b) And ((a > d) Or (a> e));
And (a > e) )
( (a < b) And (a > d )) Or ( (a < b)
<> b) Or (a <> b +c)
36. Not (( a= b +c) Or (a= b)) ; (a
a > b)O r( a >c ))
37. (a< b + c)O r( a = b + c);N ot((
(a= b)
38. Not (a >= b); (a< = b) Or N ot
(a = b)
39. Not (a >= b); (a <= b) And Not
(a = b) Or ((b =c ) And (a= c))
40. (a = b) And ((b =c ) Or (a= c));
4.1 Relati onal and Logical O perato rs
• lll
4.2 If Blocks
a cert ain cond i-
on a course of actio n base d on whe ther
An If bloc k a llows a program to d cide
tion is t rue or false .
If Block
A bloc k of the form :
Video Note
If hloc ks If con diti on Then
acti on 1
Else
acti on 2
End If
Each actio n
cause the program to take action 1 if cond
ition is tru e and action 2 if condition is fa l e.
n cont inue s
ents . Afte r an actio n is take n, exec utio
consists of one or more Visual Basic tatem char t for an If block.
cont ains the pseudocode and flow
with the line after the If block. Figure 4.1
No Yes
k.
FIGURE 4.1 Pseu doco de and flow char t for an If bloc
II ~
Maximum l = I @l !;. ~- .I
OBJECT PROPERTY
aj A Quiz [EJ [@ ][ID SETTING
frmQ uiz Tex t A Qu iz
How many gallons does a lblQ uest io n A utoS ize Fa lse
ten-ga llon hat hold?
Tex t How man y ga llons does a
Evalu ate Answer ten-ga llo n hat ho ld ?
txtA nswe r
btnEva lu ate Tex t Eva luate Answ ~ r
txtSo lution Read O n ly True
on the button. ]
[Run , type 10 into the tex t box, and cl ick
in the
Thi impo rtan t type of If bloc k appea rs
The Else pa rt of an If bloc k can be omitted.
nex t exa mp le.
g-j Qu otati o n l= @)
is (Y/ N)? N
Do you know what the game of skittles
De mit ion
OK
[Press OK.]
Display Quotation
lick
k( • .. ) Han dles btn inte rpr et.C
Priv ate Sub btn inte rpr et_ Clic
'Int erp ret a wea ther bea con
Dim col or, mod e As Stri ng
col or = mtb Col or.T ext
mod e = mtb Mod e.Te xt
If mod e = "S" The n
If col or = "B" The n
VIEW"
t xtFo rec ast. Tex t = "CLEAR
Els e 'col or - "R"
txtF ore cas t.Te xt = "RA IN AHEAD"
End If
•mod e = 'F
11
Els e
If col or = "B" The n
txtF ore cas t.Te xt = "CLOUDS DUE"
Els e 'col or = "R"
II SNOW AHEAD II
txtF ore cas t.Te xt
End If
End If
End Sub
t boxe , and click on the butt on.]
[Run , type R and S into the mas ked tex
Mode (S or 5
( Interpret Beacon I
RAIN .HEA.D
[Run, type 9500 and 8000 in to the text boxes, and click on the button
.]
Costs : 95
Revenue : 8
Elself Clauses
A n ex tension of th e If block allows for more than two possible alterna
tives with the inclusion
of Elself clauses . A typical block of th is type is
If c onditi on 1 Then
a c tion 1
Elseif condi tion 2 Then
a c tion 2
Elseif condi tion 3 Then
a c t i on 3
Else
a c t i on 4
End If
Visual Bas ic ea rches fo r the first true condit ion, carries out its action
, and then skips to the
statement fo llowing End If. If none of the condit ions are true, then
Else's action is carried out.
Execution then contin ues with the statement following the block.
In genera l, an If block can
contai n any numbe r of Else If clauses. As before, the Else clause is
option al.
Example 6 The fo llowing program redoes Exa mp le 1 so that the progra m reports
if the
two numbe rs are equal.
Privat e Sub btnFin dLarg er_ Click( .. . ) Handle s btnFin
dLarg er.Cli ck
Dim numl, num2 As Double
numl CDbl (txtFir stNum . Text)
num2 = CDbl (txtSec ondNu m.Tex t)
11 8 • C hapter 4 Dec isions
[Run, type 7 into both tex t boxes, and press the butto n.]
Rrst numbe r: 7
Second numbe r: 7
[Run , type 12345 .67 and 543.2 1 into the top two text boxes and click
on the button.]
a .. R:CA. 1 axes
The fo llowing exa mple illustrates the fact that when an If block
contains Else lf clauses,
Visua l Ba ic executes the act ion correspo nd ing to the first condit ion
that is sa tisfi ed and ignores
all subseq uent cla uses-e ven if they also sa ti fy the conditi on.
Example 8 The fo llowing program assumes that the use r wi ll gradu ate (that
is, has a
GPA of 2 or more) and dete rmines if the user wi ll gradu ate with honors
.
Privat e Sub btnDe termin e_ Click( . .. ) Handle s btnDe
termin e . Click
Dim gpa As Double = CDbl ( txtGPA . Text )
Dim honors As String
If gpa >= 3 . 9 Then
honor s= " summa cum laude. "
Elseif gpa >= 3. 6 Then
honor s= "magn a cum laude. "
Elseif gpa >= 3 .3 Then
honors = " cum laude. "
Elseif gpa >= 2 Then
honors = " "
End If
txtOut pu t.Text "You gradua ted" & honors
End Sub
120 • Chapt er 4 Dec isions
[ Determine Honors J
can be sh o rte n ed to
If boolV al Then
ca n be sh o rte n ed to
d.Clic k
Priva te Sub btnAd d_ Click ( . . . ) Handl es btnAd
tNum . Text) And IsNum eric(tx tSeco ndNum .Text) Then
If IsNum eric(t xtFirs
+ CDbl (txtSe condN um.Te xt))
t x tSum. Text = CStr (CDbl (txtFi rstNu m.Tex t)
Elsei f Not IsNum eric ( txtFir stNum .Text) Then
If Not IsNum eric(tx tSeco ndNum .Text ) Then
has an impro per entry ." )
Messa geBox . Show( "Each text box is empty or
4.2 l f Blocks
• l 21
Else
Mess ageB ox .Show ( "The first text box
is empt y or has an impr oper entry ."
)
End If
Else
Mess ageB ox . Show ( "The secon d text box
is empt y or has an impr oper entry ."
)
End If
End Sub
~~ ~ Addit ion = @) ~ I
Rrst number: J
Second numbe r: two l··· ~ ,j
' lj
( OK ]
Comments
1. Care shou ld be taken to make If blocks easy to
und erstand. Fo r instan ce, in Fig. 4.2, the
block on the left is d ifficu lt to fo llow and shoul
d be rep laced by the clearer block on th e
righ t.
End If
End Sub
2. Impr ove the bloc k
If a < b Then
If c < 5 Then
txtB ox.T ext "hel lo"
End If
End If
EXERCISES 4.2
butt on
outp ut displayed in the text box whe n the
In Exer cises 1 thro ugh 12, dete rmin e the
is click ed.
) Han dles btnD ispl ay.C lick
1. Priv ate Sub btnD ispl ay_ Clic k( ...
Dim num As Dou ble = 4
If num < = 9 Then
txtO utpu t.Te xt "Les s than ten. "
Else
If num = 4 Then
txtO utpu t.Te xt "Equ al to four ."
End If
End If
End Sub
Han dles btnD ispl ay.C lick
2. Pr ivat e Sub btnD ispl ay_ Clic k( ... )
Dim gpa As Dou ble = 3 . 49
txtO utpu t.Cl ear( )
If gpa >= 3.5 Then
txtO utpu t.Te xt = "Hon ors "
End If
txtO utpu t.Te xt &= "Stu dent "
End Sub
) Han dles btnD ispl ay.C lick
3. Priv ate Sub btnD ispl ay_ Clic k( ...
Dim a As Dou ble = 5
txtO utpu t.Cl ear( )
If ( 3 * a - 4) < 9 Then
txtO utpu t.Te xt "Rem embe r, "
End If
txtO utpu t.Te xt &= "tom orro w is anot her day. "
End Sub
4.2 If Blocks • 123
10. Pr i vate Sub btnD i splay_ Click( ... ) Handles btnDispl ay.Click
Dim num As Double = 5
If num < 0 Then
txtOutpu t.Text nnegn
Else
If num = 0 Then
txtOutpu t.Text "zero"
Else
txtOutpu t .Text "positive "
End If
End If
End Sub
12. Pr i vate Sub btnCompu te_ Click( ... ) Handles btnComp ute.Click
))
Dim dateOfBi rth As Date= CDate(In putBox(" Enter your date of birth."
4.2 If Blocks • 125
a = 5
End If
18. If (j 7) Then
b = 1
Else
If (j <> 7) Then
b = 2
End If
End If
d?"
Tex as and Cal i forn ia com bine
19. mes sage = "Is Alas ka bigg er than
answ er = Inpu tBox (me ssag e)
"Y") Then
If (ans wer .Sub strin g ( O, 1) =
answ er = "YES "
End If
"y") Then
If (ans wer .Sub strin g(O , 1)
answ er = "YES "
End If
If (ans wer = "YES ") Then
txtO utpu t.Te xt "Co rrec t"
Else
txtO utpu t.Te xt "Wro ng"
End If
) is the Stat ue of Lib erty ?"
20. mes sage = "How tall (in feet
fee t= CDb l(Inp utBo x(m essa ge))
If (fee t <= 141) Then
lstO utpu t. Item s .Add ("No pe")
End If
If (fee t > 141) Then
If (fee t < 161) Then
lstO utpu t. Item s .Add ("Cl ose" )
Else
1st0 utpu t . Item s .Add ("No pe")
End If
End If torc h.")
ue is 151 feet from base to
1st0 utpu t.Ite ms. Add ( " The stat
shou ld be
h to tip the serv er in a resta uran t. The tip
21. Wri te a program to dete rmin e how muc
15% of the chec k, with a mini mum of $1.
ls and 60
l for ord ers of less than a half-dozen bage
22. A bage l shop charges 75 cents per bage ests the num -
or more. Wri te a program that requ
ce nts per bage l for ord ers of a half-dozen bage l
l cost . (Test the program for orde rs of four
ber of bage ls orde red and disp lays the tota
and a dozen bagels.)
rs of 100
for sma ll orders or at 20 cents each for orde
23. A store sells widgets at 25 cents each and disp lays the tota l
num ber of widgets orde red
or more. Write a prog ram that requests the
5 and 200 widgets.)
cost . (Test the program for purchases of for each
for the first 100 cop ie and 3 cents per copy
24. A copy cent er charges 5 ce nts per copy and disp lay
ests the num ber of copies as inpu t
addi tion al copy. Wri te a program that requ
quan titie 25 and 125.)
the tota l cost . (Tes t the program with the
should
the first Ronald McD onald ?" The program
25. W rite a quiz program to ask "Wh o was y othe r answ er.
Scot t" and "N ice try." for an
d isp lay "Co rrec t." if the answer is "Willard
4.2 If Blocks • 127
26. S uppose a program has a button with the caption "Quit". S uppose also that the N
ame prop-
erty of this button is bmQuit. Write a btnQuit_ Click event procedur e that gives the
user a
second chance before ending the program. The procedur e should use an input
box to
reque t that the user confirm that the program should be terminated , and then end the
pro-
gram only if the user respo nds in the affirmati ve.
27. Write a program that requests three scores as input and d isp lays the ave rage
of the two
highest sco res.
28. Write a program to hand le a sav ings-acco unt withdraw al. The program should request
the
current balance and the amo unt of the withdrawal as input and then disp lay the new
ba l-
ance . If the withdraw a l is greate r th an the original balance, the program sh ould
display
"Withdr awal denied." If the new balance is less than $ 150, the message "Balance
below
$ 150." also should be displayed.
29. A superma rket sells app les for $1.70 per pound. Write a cashier's program that requests
the
number of pounds and the amo unt of cash tendered as input and displays the change
from
the transacti on. If the cash is n ot eno ugh, the message "I need $x.xx more." should
be d is-
played, where $x.xx is the differenc e between the total cost and the cash. (Tes t the program
with six pounds and $20, and four pounds and $ 10.)
30. Write a program that req uests a word (with lowercase letters ) as input and
trans lates the
word into pig lat in. The rules fo r trans lating a word in to pig latin are as fo llows:
(a) If the word begin with a group of consona nts, move them to the end of
the word and
add ay. For instance, chifJ becomes ipchay.
(b) If the word begins with a vowe l, add way to the end of the word. For instance,
else
becomes elseway.
31. Fede ra l law requ ires that ho urly employees be paid "time-and- a- ha lf" fo r work
in exce of
40 hours in a week. For example, if a person's ho urly wage is $8 and he works 60 hours
in a
week, hi s gross pay should be
(40 X 8) + (1.5 X 8 X (60- 40)) = $560
Write a program that request as input the num ber of hours a person works in a given
week
and his hourly wage, and then disp lays his gross pay.
32. The cu rrent calendar, called the Gregoria n cale nd ar, was introd uced in 1582.
Every yea r
divisib le by four was declared to be a leap yea r, with the excep tion of the yea rs ending
in 00
(that is, those d ivisible by 100) and not divis ible by 400. For instance, the yea rs 1600
and
2000 are leap years, but 1700, 1800, and 1900 are not. Write a program that requests
a yea r
as input and states whether it i a leap yea r. The program should not use any variables
of
type Date. (Test the program on the yea rs 2008, 2009, 1900, and 2000.)
33. Create a form with a text box and two buttons captioned Bogart and Raines.
When Bogart
is first pressed, the se ntence "I came to Casablan ca for t he waters." is d isplayed in the
text
box. The next time Bogart i pressed, the sentence "I was misinformed." is disp layed.
When
Ra ines is pressed, the se ntence "But we' re in the middle of the dese rt." is disp layed. Run
the
program and then press Bogart, Raines, and Bogart to ob tain a dia logue.
34. Write a program that allows the user to use a button to toggle the co lo r of
the text in a text
box between black and red.
35. Write a program that allows the u er ten tries to answer the question , "Which
U.S. Presiden t
was born on July 4 ?" After three inco rrect guesses, the program sh ould d isplay the
hint,
"He once said, 'If yo u don't say anything, you won't be ca lled upon to repeat it ."' in
ames-
sage box. After eve n incorrec t guesses, the program sho uld give the hint, "His ni ckname
was 'Silent Ca l. "' The number of guesses sho uld be displayed in a text box. (See Fig.
4.3.)
Note: Calvin Coolidge was born on July 4, 1872 .
128 • Chapte r 4 Decisions
ll ~ Hide and Seek ~~ ~ lrn::J frmHid eSeek Text Hide and Seek
lblLanguage Text VB 20 10
1000 .
03 )4
(1 + ~ = 1000. 1.0075
4
= $ 1,030.3 4.
APY ~ (l +: r-
for a stated interes t rate r co mpoun ded m times per year is defined
by
1
4.2 If Blocks
• 129
Bank 1 Bank 2
Annual rate of interest : 17 J.SB
Number of compo unding periods : 2 5 Determine
Best Bank
APY: 3.7 o.
·'• 3.7 n
Best bank : Bank
Yes
20000?
Set tax =
.02 *Income Yes No
income :s
50000?
4.2
Solu tion s to Practice Problems
a
shing pos itio n in a horse race into
Exa mp le 1 Th e foll owing program con ve rts the fini n, Vis ual Bas ic
.../ from txtP os itio
iab le position is ass igned a va lue
descriptive phrase. Aft er the var t valu e and execut es the succeed-
firs t Cas e clau se who se valu e list con tains tha
sea rches for the ing Cas e Else
the valu e of position is grea ter tha n 5, the n the stat ement fo llow
ing stat em ent . If
is exe cut ed.
PROPERTY SETTING
OBJECT
ll
Rnishing position
(1. . 3. . ..):
Evaluate Position
Place
Example 2 In the fo llowing var iation of Example 1, the va lue lists specify ranges
of val-
ues. The first va lue list provides anothe r way to stipula te the numbe
rs 1, 2, and 3. The second
value list covers all numbe rs from 4 on .
Privat e Sub btnEv aluate _ Click( . . . ) Handle s btnEv
aluate .Click
e~~r.be f~ ~ r g pos~t~ons ~n a ~orse rae
Dim positi on As Intege r
positi on= Cint (txtPo sition .Text)
Selec t Case positi on
Case 1 To 3
txtOut come. Text "In the money. Congr atulat ions."
Case Is >= 4
txtOut come. Text "Not in the money ."
End Selec t
End Sub
[Run, type 2 into the text box, and click on the button .]
ll .J
Finishing position
(1. . 3... .):
Evaluate Position
1. a litera l;
2. a variab le;
3. an express ion;
4. an inequ ality sign preceded by Is and followed
by a litera l, var iable, or expression;
txtOu tput
Text
ReadO nly
Days in Month
True
Evaluate
selector
Yes
Action 1
Yes
Action 2
Yes
Action n
Perform
action of
last resort