0% found this document useful (0 votes)
2K views736 pages

An Introduction To Programming Using Visual Basic 2010

Uploaded by

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

An Introduction To Programming Using Visual Basic 2010

Uploaded by

Josue Molina
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 736

EIGHTH EDITION

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.

To redeem your access code:


1. Go to www.pearsonhighered.comfschneider.
2. Select your textbook.
3. Click on the VideoNotes and Solutions Manual links.

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

Environm ent and Editor


Alt Toggle focus between Document window and Menu bar
Air/File/Sa ve All Save the current program
A Ir/File/Clos e Project Close the current program
Air/Windo w/Reset Window Layout Reset to the IDE's default layout
Air/File/Ex it Exit Visual Basic
Air/Projec t/Add Existing Item Import an existing form into program
Air/Projec t/Add New Item Add a text file or form to program
Air/View/C ode Display the Code Editor for the current program
A It/View/De signer Display the Form Designer for the current program
Air/View/O ther Windows/S olution Explorer Display the Solution Explorer
Alt/View/F ull Screen Enlarge Visual Basic IDE screen
Alr+F4 End running program
Ctri+A Select everything in the current document
Ctri+C Place selected text into C lipboard
Crrl+F Find
Crrl+H Replace
Crri+N Start a new program
Ctrl+O Open a program stored on disk
Crrl+P Print a copy of the current program
Crri+V Replace selected text with contents of Clipboard
Crrl+Z Undu last change
Ctrl+Shift+ Enter Terminate entry of a 4uery
F4 Display the properties window
FS Run the current program
FB Execute the next line of code while debugging
Shift+F8 Execute the next line of code while debugging, but do not
follow execution through any procedure calls
F9 Toggle a breakpoint
be C lose a menu or dialog box
Double-clic k on Properties window title bar Undock Properties window for easier usc (Right-clic k on
title bar and click on Dock tu redock Properties window)

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

VISUAL BASIC® 201 0


with Microsoft® Visual Studio® 2010 Express Editions DVD

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.

ucatio n. Upper Saddle River,


Copyright © 2011, 2006, 2003, 1999, 1998, 1997, 1995 by Pearson Higher Ed
This publicatio n is protected
New Jersey, 07458. A ll rights rese rved. Manufactu red in the United States of A merica.
prio r to an y prohibited rep rod uctio n, sto rage in a
by Copy ri ght and perm is ·ion sho uld be obtained from the publisher
by any means, electroni c, mechani ca l, photocopy ing, reco rding, or
retri eva l system, or transm iss ion in any form or
(s) usc mate ri als from this work, please submit a written request to Pea rson Higher
likew ise. To obtai n permission to

Education, Permi ssions Departmen t, I Lake Street, Upper Saddle Ri ve r, NJ 07 45 8.

Visual Basic is a registered trademark of Microsoft orporat ion.

These efforts include the


The author and publisher of this hook have used the ir best efforts in preparing this book.
of the th eori es and programs to dete rmine the ir effective ness. The auth or and
developme nt, resea rch, and testing
make no warranty of any kind, exp ressed or impli ed, with regard to these programs or the document ation
publisher
able in any event for inc idental or con eq uentia l damages
con ta ined in this book. The author and publisher sha ll nor he li
in connectio n with, or ari si ng out of, the furnishing, performan ce, or use of these programs.

Library of Congress Cataloging -in-Public ation Data


Schne ider, David l.
A n introductio n to programm ing using Visual Basic 20 10 : with Mi crosoft"
Vis ual Studi o® 2010 Express Editions DVD/ David l. Schn e ider.- 8th ed.
p. em.
Includes index.
ISBN 978-0-13-2 12856-8
l. Microsoft Visual BAS IC. 2. BASIC (Co mputer program language) l. Titl e.
QA76 .73.B3S33362 2010
006. 7'882---dc 22
200905436 1

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 2 Visual Basic Controls and Events


Visual Bas ic Contro ls 23
Positioning and A ligning Contro ls 31
Mov ing a Textbox (Representative Examp le of Homework Exercise 35) 36
Eve nt Procedures 37

Chapter 3 Variables, Input, and Output


N um bers 56
Strings 68
Widening and Narrowing, Scope 75
Formatting O utput 85
Mortgage Ca lcul ator (Representative Exa mpl e of Homework Exercise 75) 97

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 5 General Procedures


Function Proced ures 160
Sub Procedures 175
Debugging Procedures 195
Hardware Store (Representat ive Example of Homework Exe rcise 3) 215
Chapter 6 Repetition
Do Loops 218
Sieve of Eratosthenes (Representative Exa mple of Homework Exe rcise 28) 227
For ... Next Loop 230
List Boxe and Loop 243

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 8 Text Files


Managing Tex t Fil es 352
StreamReaders and S tream Writers 366
XML 382
DNA Seq uence Data (Representative Example of Programming Project 5) 399

Chapter 9 Additional Controls and Objects


List Boxes and Combo Boxes 404
Additional Contro ls 41 0
Blackjack (Representative Example of Homework Exercise 54) 424
Multiple-form Programs 425
G raphics 43 7
v
vi • G uide to VideoNotes

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

Chapter 11 Object-Oriented Programm ing


C la ses and Objects 492
Arrays of Objects 507
Inheritance 518
Student Reg istrati on (Repre entat ive Example of Homework Exe rc ise 20 ) 534

Chapter 12 Web Applications


Programm ing fo r the Web 540
Mu ltiple Web Pages 551
Disp lay ing Information in a Grid 564
Web-Based Ri chard' Catering (Repre entati ve Example of Progra mming Project 2) 572
Guide to Application Topics
Business and Economics
Ad mi ssion fee, 14 7, 555, 557 Gather bi lling inform ation , 436
A irlin e rese rvat ions, 345, 452 Generate an order form, 215
A mo un t of stock purchase, 66 Gross pay, 127,206
Ana lyze a Loan case stud y, 332 Growth of pizza cha ins, 569, 570
Analyze fue l economy, 348 Hea lth club fees, 559
Ana lyze sa les data, 327 Income tax, 128, 155
An nuity, 67, 174, 229, 241 In ventory contro l, 33 1,45 1,53 4
APY, 128 ISBN numbers, 346
Automated directo ry ass ista nce, 34 7 Itemi zed bill, 100, 154, 21 4
A uto mobil e depreciat ion, 240 Lifet ime ea rnings, 241
Bank acco unt, 536 Loa n ana lys is, 435
Bond rates, 549 Ma il -ord er co mpan y, 487
Break-even analys is, 66, 141 Mainta in a membership list, 451
Busine s travel expe nses, 10 1 Manage telephone directori es , 398
Calculate a tip, 97, 126, 188, 552, 553 Marginal cost and revenue, 141
Calculate week ly pay, 164, 506, 560 Membership fee, 153
Car loan, 229, 241 Minimum wage, 44 7
Cas h awa rd, 142 Monetary units of countries , 470, 474
Cash register, 506, 516, 5 34 Mo rtgage, 155, 200, 229
C hange fro m a sa le, 12 7 Pay raise, 200
C hecking acco unt transacti o ns, 435, 536 Pay ro ll , 206, 43 1, 53 4
Co mpare interest rates, 128 Perce ntage increase in cost, 97
Compa re two sa lary options, 24 3 Percentage profit, 67
Co mpo und interest, 67, 97, 128, 155, 165 , 174, 222, Pos tage costs, 174
228,229,241 , 435 Pri ce-to-ea rnings rat io, 83
Computers in the workp lace, 327 Profit,66, 83 , 11 6,174
Co nsum er pri ce index, 229 Recording C hecks and Depos its case stud y, 388
Cost of a computer system, 151, 559 Restaurant order, 156, 517
Co tofbenefitsp lan , 148, 149,55 7 Reve nue, 141,569,570
Cost of purchases, 167 Ru le of"72" , 252
C redit ca rd acco unt, 200, 436 Sa les commiss ion , 84
Crop prod uct io n, 67, 242 Sa les tax, 95, 41 2,549
C urrency exchange rates, 47 5 av ingsaccount, 127, 174
Deprec iati on, 240, 253 Sav ings plan, 229
Discount price, 66, 82 S impl e inte rest, 241
Discount rate, 549 S imul ate a lottery, 411
Disp lay economic data in a ba r chart, 443, 444 , 447 S ubscriber data, 364
Display economic data in a pi e chart, 440, 44 7, 449 S upply and demand , 242
Display sa les data, 242 Tab ulate sa les amounts, 327, 381
Div idend yie ld, 55 0 Tax return, 153
Do ubli ng time of an in vestme nt, 95, 228 To ta l cost, 126
Emp loyee paycheck rece ipt, 5 17 Tota l income, 427
Enro llm ent in a pens ion plan, 157 To ta l sa laries pa id , 329
Estate tax, 96 Un ive r a l Product Code, 399
FI CA tax, 11 8, 206, 507 Weekl y pay, 43 1
Fi xed cost, 141 Weekly Payroll case stud y, 206
Future va lu e, 165 Withho lding tax, 207, 517

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

Sports and Games


Baseball, 3 15, 3 16, 388, 397, 400, 45 3, 4 76, 4 77 Go lf, 292, 329
Blackjack, 537 Pick up sticks, 216
ice,42, 506,5 16,517 Poker, 345,423, 512
Football , 249,265,293 Triathlo n, 2
CONTENTS

Guide to VideoNotes v

Guide to Application Topics vii

Preface xiii

Acknowledgments xix

Using this Book for a Short or Condensed Course xxi

Chapter 1 An Introductio n to Computers


and Problem Solving 1
1.1 An Introduction to Computers 2

1.2 Windows, Folders, and Files 4

1.3 Program Development Cycle 6

1.4 Programming Tools 8

Chapter 2 Visual Basic Controls and Events 17


2.1 An Introduction to Visual Basic 2010 18

2.2 Visual Basic Controls 20

2.3 Visual Basic Events 37

Summary 53

Chapter 3 Variables, Input, and Output 53


3.1 Numbers 54

3.2 Strings 68

3.3 Input and Output 85

Summary 98

Programming Projects 100

ix
X
• Co ntents

Chapte r 4 Decisio ns 103


4.1 Relational and logical Operators 104
4.2 If Blocks 112
4.3 Select Case Blocks 130
4.4 Input via User Selection 143

Summary 154
Programming Projects 154

Chapte r 5 Genera l Proced ures 159


5.1 Function Procedures 160
5.2 Sub Procedures, Part I 175
5.3 Sub Procedures, Part II 190
5.4 Modular Design 202
5.5 A Case Study: Weekly Payroll 206

Summary 214
Programming Projects 214

Chapte r 6 Repetit ion 217


6.1 Do Loops 218
6.2 For... Next loops 230
6.3 list Boxes and loops 243

Summary 251
Programming Projects 251

Chapte r 7 Arrays 257


7.1 Creating and Accessing Arrays 258
Contents • XI

7.2 Using LINQ with Arrays 281

7.3 Arrays of Structures 294

7.4 Two-Dimensional Arrays 319

7.5 A Case Study: Analyze a Loan 332

Summary 340

Programming Projects 341

Chapter 8 Text Files 349


8.1 Managing Text Files 350

8.2 StreamReaders, StreamWriters, Structured Exception Handling 366

8 .3 XML 382

8.4 A Case Study: Recording Checks and Deposits 388

Summary 396

Programming Projects 397

Chapter 9 Additional Controls and Objects 401


9.1 list Boxes and Combo Boxes 402

9.2 Eight Additional Controls and Objects 410

9.3 Multiple-Form Programs 425

9.4 Graphics 437

Summary 450

Programming Projects 451

Chapter 10 Databases 457


10.1 An Introduction to Databases 458

10.2 Editing and Designing Databases 479


X II
• Content

Summary 486

Programming Projects 487

Chapter 11 Object.-O riented Program ming 491


11.1 Classes and Objects 492

11.2 Working with Objects 507

11.3 Inheritance 518

Summary 535

Programming Projects 536

Chapter 12 Web Applicati ons 539


12.1 Programming for the Web, Part I 540

12.2 Programming for the Web, Part II 550

12.3 Using Databases in Web Programs 560

Summary 571

Programming Projects 572

Appendic es 575
Appendix A ANSI Values 575

Appendix B How To 577

Appendix C Folders and Files 589

Appendix D Visual Basic Debugging Tools 591

Answers to Selected Odd .. Numbere d Exercises 60 1

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.

Unique and Distingu ishing Feature s


Microsoft® Visual Studio® 2010 Express editions DVD. The tex tbook comes with a
Visual Studio 20 10 Express Edition DVD. It contains several Microsoft products including
Visual Bas ic 20 10, SQL Serve r 20 10, and Visual Web Developer.

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

How to Acce ss Instr uctor and Stud ent Reso urce


Mate rials
Instruc tor Resour ces
the publish er's
The fo llow ing protecte d instru ctor resource mater ials are ava ilab le o n
rd informa-
webs ite at www.pe arso nhigh ered.co m/schne ide r. For use rname and passwo
t ion, please co ntact you r loca l Pearson Represe ntative .
• Comp uterized Test Gene rator
• PowerP oint Lecture Slides
pdf format. The
• Instruct or Solution s Manual: A comple te solution s manual is ava ilable in
captu res of
manual contain s the code for eve ry program ming exercise along with screen
the output.
• A ll the progra ms in the book
• Links to onlin e prem ium content
• VideoN otes
• Studen t Solutio ns Manual

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.

What's New in the Eighth Edition


New Sections

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

3. A sec tion on XML h as bee n add ed to C hapter 8. (LINQ techniqu es developed


ea rlier are applied to XML files.)
4. A ch apter on Web applications h as been add ed. (The three sections in thi s chap-
ter cover th e use of Visual Web Developer to crea te Web programs. Topics in-
clude tables, hyperlinks, pos tbac ks, validation controls, and databases . Data
ex trac ted fro m data bases are d i played in both grids and the new-to-VB20 10
C hart con tro ls. )

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

New Materials for Instructors

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

New Materials for Students

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.

Dav id I. Schne ider


d [email protected]

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.

Chapter 1 An Introduction to Computers and Problem Solving


1.1 An Introduction to Computers
1.2 Windows, Folders, and Files
Chapter 2 Visual Basic Controls and Events
2.1 An Introduction to Visual Basic 2010
2.2 Visual Bas ic Contro ls
2.3 Visual Bas ic Events
Chapter 3 Variables, Input, and Output
3.1 Numbers
3. 2 Strings
3.3 Input and O utput
Chapter 4 Decisions
4.1 Relational and Logical Operators
4.2 If Blocks
4.3 Select Case Blocks
4.4 Input via U ser Selection
Chapter 5 General Procedures 1
5.1 Function Procedures
5.2 S ub Procedures, Part I
Chapter 6 Repetition
6.1 Do Loops
6.2 For. ..Next Loops
Chapter 7 Arrays
7.1 C reating and A ccess ing Arrays
7.2 U sing LINQ with Arrays
Chapter 8 Text Files 2
8.1 Managing Tex t Files
or 8. 2 StreamReader , Stream W ri ters, Structured Exception H andling

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

VISUAL BA SIC ® 201 0


with Microsoft® Visual Studio® 20 10 Express Editions DVD

EIGH TH EDIT ION


An Introduction to
Computers and Problem
Solving
1.1 An Introduction to Computers 2

1.2 Windows, Folders, and Files 4


+ Windows and Its Little Windows + Mouse Act ions + Files and Folders
1.3 Program Development Cycle 6
+ Performing a Task on the Compute r + Program Planning
1.4 Programming Tools 8
• Flowcharts • Pseudocode + Hierarchy Chart + Decision Structure + Direction of
Numbered NYC Streets A lgorithm + Repetition Structure + C lass Average A lgorithm

1
2 • Chapter 1 An Introd uct io n to Comput ers and Problem So lving

1.1 An Introduction to Computers


problem o lving using
An Introduction to Programming Using Visual Basic 20 10 is a book about
(he reafter shorten ed to Visua l
comput ers. The program ming language used is Visual Basic 2010
es. The exa mples
Basic), but the principl es taught app ly to man y mode rn program ming languag
rea l world. H ere are
and exerc ises present a samplin g of the ways that comput ers are used in the
some question s that you might have about comp uters and program ming.

Questio n: How do we communicate with the comJJuter?


At the lowest level,
Answer : Many languages are used to commu nicate with the comput er.
micropr oce sor but is awkwar d for
there is machine language, which i und ers tood directly by the
instruct io ns to which
hum ans. Visual Basic is an examp le of a higher-level language. It consists of
peop le can re late, such as C lick, If, and Do.

Questio n: What is a comp iler?


as Visua l Basic into
Answer : A comp iler is a program that translat e a high -leve l language such
certain types of errors
machin e language. The Visual Basic compile r detects (and po ints out)
during the translat ion process.

Questio n: What is a GUI?


Both Windows and
Answer : GUI (pronou nced GOO-e e) stands for "graphi cal user interfac e."
objects such as buttons
Visual Bas ic use a graphic al user interface; that is, they employ graphic
commo n before 1990
and menus to interact with the use r. Non-G UI text-bas ed programs were
but are now quite rare.

Questio n: How do we get comJJuters to perform complica ted tasks?


exp ressed in a com-
Answer : Tasks are broken down into a sequenc e of instructions that ca n be
Bas ic.) This sequenc e of instruct ion is called
puter language. (Thi text uses the language Visual
truction s to mil lions of instruct ions.
a program. Programs can range in size from two or three in
are stored in the com-
Instruct ions are typed on the keyboa rd or read in from a file on a disk and
the program.
puter's memory. The process of executi ng the instruct ions i called running

Questio n: Are there certain features that aU programs have in common?


give desired infor-
Answer : Most programs do three things: take in data, manipu late them, and
input data might be
mation. These operatio ns are referred to as input, processing, and output. The
the comput er user in
held in a portion of the program, res ide on a disk drive, or be provide d by
The processing of the
response to requests made by the comput er whi le the program is running.
fract ion of a second to many hours .
input data occurs inside the co mputer and can take from a
o r recorde d on a disk.
The output data are e ither disp layed on the monitor, printed on the printer,
of input data is the
As a simple exa mple, cons ider a program that comput es sales tax. An item
by a certa in percent -
cost of the thing purchased. The processing consists of multiply ing the cost
, the amount of sales tax to be paid.
age. An item of output data is the resulting product

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.

Question: What is meant by JJroblem solving?


Answer: Problems are solved by carefully reading them to determine what data are given and
what outpu ts are requested. Then a step-by-step proced ure is devised to process the given data
and prod uce the requested output. This procedure is called an algorithm.

Question: How did Visual Basic 20 10 evolve?


Answer: In the early 1960s, two mathemat ics professors at Dartmouth College developed
BA IC to prov ide their students with an easily learned language that could tackle complicated
programmin g projects. As the popula rity of BA IC grew, refinements we re introd uced that per-
mitted structured programming, which increased the reliability of programs. Visual Basic 1.0 is
a vers ion of BASIC deve loped in 199 1 by the Mic rosoft Co rporation to allow ea y, visua l-
o riented developmen t of Windows applications. Visual Bas ic 2010 is a language similar to the
original Visua l Basic, but more powerfu l.
Question: Are there any prerequisites to learning Visual Basic 20 10?
Answer: S ince Visua l Basic is used to wr ite W indows applications, you hould be fa miliar with
Windows and understand how fo lders and fi les are managed with Windows. The key concep ts
are presented succ inctly in Section 1. 2 and d iscussed in detai l in Appe ndix C.
Question: Wi ll it matter whether 1 use Windows XP, Windows Vista, or Windows 7 as the operating
system?
Answer: Visual Basic runs fine with all three versions of Windows. H owever, the windows will
vary in appearance. Figures 1.1(a) and l.l(b) show the appearance of a typ ical window pro-
duced in Visual Basic with W indows XP and Windows Vista. With Wind ows 7, the appearance
of windows depends on the Windows 7 product edition (such as Starter, Home Bas ic, Home
Premium, etc.), the hardware on your system, and your own personal preferences. If you are
using Windows 7 Starter or Windows 7 Home Bas ic, most likely yo ur windows will look like the
one in Fig. l.l( c). W ith higher-end versions of Window 7 and recen t hardware , your windows
most likely will have an appearance imilar to Fig. 1.1( b), known as Aero. In this book, all win-
dows have the Aero appearance. No matter which operating system and appearance is used, the
size and placement of the items inside the wind ow should be the same.

ll U.N. (E][][l[I D

Displa_y Nations b_y Di:.plcr;' Nations l Display t•.Jations trl


Population Population Populath-n

China China [D-1ina io

India India India


United States United States United States __j

! Indonesia Indonesia Indonesia


Brazil Bra~ I Brazil '
Pakistan Pakistan Pakistan
Bangladesh Bangladesh Bangladesh
t~igeria v Nigeria Nigeria ~

(a) Windows XP (b) Windows Vi sta (c) Windows 7


FIGURE 1.1 A Visual Basic window.
4 • Chapter 1 A n Introdu ction to Compu te rs and Problem Solving

1.2 Windows, Folders, and Files


This prelimina ry section presents some terms used in this book.

Windows and Its little Windows


Windows gets its name from the way it organizes the scree n into rectangula r regions. When yo u
run a program, the program runs inside a bordered rectangula r box . Unfortuna tely Windows
jargon calls these windows, o there's only a lowercase "w" to distinguish them from the operat-
ing sys tem called Windows. Figure 1. 2 shows the window that res ults from running one of the
programs in this book. ln Vi ual Bas ic term inology, such a window i also called a form .

Minimize Maximize button Close


Title bar
button button

Natural bom citizen? y ear U.S. resident ?

o Yes g Yes

No No

Date of Birth: 1976

You are eligible to run for president in 12.

FIGURE 1.2 A Visual Basic window.

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.

Files and Folders


(A detailed di cu sion f files and folder ca n be found in Appendix C. )
Disk: A hard disk, a diskette, a USB flash drive, a C D, or a DVD. Each disk drive is identified by
a letter followed by a colon.
1.2 Windows, Fo lders, and Files • 5

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:

C:\Program s\Ch07\Tex t_ Files_ for_ Exercises\ USPres.tx t

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 Vista and Windows 7

1. C lick on the Sta rt button.


2. Windows Vista: Type "Folde r Op tions" in to the "Start Search" box and press th e Enter
key. (A Folders Op tions d ialog box will appea r.)
Windows 7: Type "Fo lder Options" into the "Search programs and file " box. (A Con tro l
Panel box will ap pear.) C lick on Folder O ptions. (A Folders Options dialog box will appear.)
3. C lick on the View tab in the Folder O ptions dialog box. (With Wind ows 7, the dialog box
in Fig. 1.3 will appear. A similar di alog box will appea r with Windows Vista.)
4. If there is a check mark in the box nex t to "Hide ex tensions for known fil e types," click on
the box to remove the check mark.
5. C lick on the OK button to close the Folder O ptions dialog box .

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

@eiieraij ~Se arch J


~--~-----------------------------.
Folder views
You can appr,rthe view (such as Details or Icons) that
r: : : ~'Ouare using for this folder to all folders of this type .

p1 .oF ers Reset Folders

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

FIGURE 1.3 Folder Options dialog box.

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.

1.3 Program Development Cycle


(such as
We learned in Section 1.1 that hardware refers to the machine ry in a co mputer sy tern
instructi ons, ca lled a
th e monitor, keyboa rd, and CPU ) and software refers to a collectio n of
tasks on
program , that d irects the h ardware. Programs are written to solve problem s or perform
r can
a compute r. Program mers translate the solut ions or tasks into a language the compute
that the comp uter will do only what
und erstand . As we write programs , we must keep in mind
ugh with our in tructions .
we instruct it to do. Because of this, we must b very careful and thoro
Note: A program is also known as a project, applicati on, or sol ution.

Performing a Task on the Computer


should
The first step in writing instructions to ca rry out a task is to determin e wh at the output
the data, or
be--th at is, exactly what the task should produce. The second step is to identify
1.3 Program Developmen t Cycle • 7

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:

How fas t is a car mov ing if it travels 50 miles in 2 hours?

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

A pictorial represe ntat ion of this problem-solving process is

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.

1. Analyze: Define the problem.


Be sure you unde rstand what the program should do-that is, what the output sh ould be.
Have a clea r idea of what data (or in put) are given and the relationship between the input
and the desired outpu t.
2. Design: Plan the solution to th e problem.
Find a logical sequence of precise steps that solve the problem. Such a sequence of steps is
called an algorithm. Every detail, including obvious step , should appear in the algorithm. In
8 • Chapter 1 An Introd uction to Compute rs and Problem So lving

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.

1.4 Programming Tools


algo-
This sectio n discusses so me spec ific a lgorithm s and describes three tools used to convert
rithms into compute r program : flowch arts, pse udocode, and hierarch y charts.
r you
You use algorithm s every day to make decisions and petform tasks. For instance, wheneve
of thumb is to use
mail a letter, you must decide how much postage to put on the envelope. One rule
determin e
one stamp for every five sheets of paper or fraction thereof. Suppose a fri end a ks you to
sh the task.
the number of stamps to place on an envelope. The following algorithm will accompli
(input)
1. Request the number of shee ts of paper; cal l it beets.
2. Div ide Sheets by 5. ( jJrocess ing)
(process ing)
3. Round the quotient up to the nex t highest who le number; call it Stamps.
( outjJut)
4. Rep ly with the number Stamps.
data,
The precedin g algorithm takes the number of sheets (Sheets) as input, processes the
for a
and produces the number of sta mp needed ( tamps) as o utput. W e can test the algorithm
letter with 16 sheet of paper.
1.4 Programming Tools • 9

1. R equ est th e number of sh ee ts of pape r; S h ee ts 16.


2. Di v iding 5 into 16 gives 3 .2.
3. Ro unding 3.2 up to 4 gives S ta m ps 4.
4. R ep ly wit h th e an we r, 4 sta mps.

This prob le m -so lving exa mp le ca n be p ictu red by

Input Processing Output


(16) (formu las) (4)

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.

Symbol Name Meaning


FLowLine Used to con nect symbols and ind icate the
fl ow of logic.

(~_) T erminaL Used to represe n t the hcgi nni ng (S tart ) or


the end (End ) of a task.

0 In/JUt/Ou tput Used fo r inpu t and outpu t opcrm ions, such


as read ing and di sp lay ing. T he data to be read
or displayed arc desc ribed ins ide.

D Processin g Used fo r ari thm et ic and data-ma nipulat io n


ope rat ions. The instruct ions arc Iis ted
inside the sy mbol.

0 D ecision Used for any logic o r comparis on ope rat ions.


Un like the input/o utput and processin g
sy mbo ls, whi ch have one entry a nd o ne ex it
fl owline, th e dec ision sy mbol has one ent ry
and two ex it paths. The path chosen depends
on whether th e answer to a que -rion is "yes"
or "no."

0 Connector Used to jo in d iffe rent flow li nes.

Annotati on Used to prov ide addi t iona l info rmat io n


about anoth er fl owchart sy mbo l.
10 • Chapte r 1 A n Introdu cti on to Compu ters a nd Prob lem So lving

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

FIGURE 1.4 Flowch art for the postage -stamp problem .

has bee n adopte d by the


The table of the flowch art symbo ls shown on the prev io u page
the flowch art fo r the
Ameri can N ational S tand ards Institu te (AN SI) . Figure 1.4 shows
postage-stamp problem .
pro vid es a picto ria l rep-
The ma in ad vantage of using a fl owcha rt to plan a task is that it
W e n clea rl y see eve ry step
ca
rese ntatio n of the tas k, wh ich makes the log ic eas ier to fo llo w.
is that when a progra m is
and how each is connec ted to th e n ex t. The majo r disad va ntage
them difficu lt to fo llo w and
ve ry la rge, the fl o wcha rts may contin ue fo r many pages, makin g
modify.

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

The follow ing is pse udoco de for the postage-stamp proble


m:
Progr am: Deter mine the prope r numb er of stamp
s for a letter
Read Shee ts (input)
Set the numb er of stamp to Sheet s / 5 (process ing)
Roun d the numb er of stamp up to the next whole numb ( fJroces sing)
er
Display the numb er of stamp s ( outfJut)
P eudoc ode has evera l advan tages. It is comp act and
probably will not ex tend for many
pages as fl owch arts co mmonly do. Also, the plan looks
like the code to be writte n and o is pre-
fe rred by many progra mm ers.

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

Set stamps = Round stamps


sheets I 5 up to next whole
number
FIGURE 1.5 Hiera rchy chart for the postag e-stam p proble m.

The main benefit of hierarchy charts is in th initia l plann


ing of a program. We break down
the major parts of a progra m so we ca n see what must
be done in general. From this po int, we
ca n then refine each module into more detail ed plans
using flowc harts or pse ud ocode. Thi
proces is ca lled the divid e-and -conq uer metho d.

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?

If condi tio n is tru e Then


Process
Process step (s) l Process
step(s) 1
Else step(s) 2
Proce ss step(s ) 2
End If

ture.
FIGURE 1.6 Pseud ocod e and flowc hart for a decis ion struc

is exec uted. This stru cture i calle d a decis ion


exec uted. If the answer is "no," then anot her
and flowc hart for a dec i ion struc ture.
struc ture . Figur e 1.6 cont ains the pseud ocod e
to solve the follo wing prob lem.
Sequ ence and decision stru ctures are both used

Direction of Numbered NYC Streets Algorithm


stree t in N ew York , decid e the direc tion of the
Problem: G ive n a stree t numb er of a one- way
stree t, eithe r eastbound or west bound .
tion of a one-way stree t in N ew York: Eve n-
Disc ussio n: There is a simple ru le to tell the direc
num bered stree ts run eastb ound.
Inpu t: Stree t numb er.

Start

No Yes
street
even?

Display
Display
Eastbound
Westbound

End

stree ts probl em.


FIGURE 1.7 Flow chart for the numb ered New York City
1.4 Programmi ng Tools • 13

Program: Determine the di rection of a numbered NYC street.


Get street
lf street is even Then
Display Eastbound
Else
Display Westbou nd
End lf
FIGURE 1.8 Pseudocod e for the numbered N ew York City streets problem.

Street
direction
program

Get Decide whether Display


street street number direction
number is even or odd

FIGURE 1.9 Hierarchy chart for the numbered New York City streets problem.

Processing: Decide if the street number is d ivisible by 2.


Output: "Eastboun d" or "Westbound".
Figures 1. 7 through 1.9 how the flowchart, pseudocode, and hierarchy chart for the num-
bered New York C ity 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

Do Wh ile conditi on is tru e


Process step(s)
Loop
Process
step(s)

FIGURE 1.10 P seudocode and flowchart for a loop.


14 • Chapter 1 An Introductio n to Compu te rs and Problem So lving

Class Average Algorithm


Problem: Ca lcu late and report the average grade for a class.

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

Initialize counter and


cou nter and ---- sum start at 0
sum to 0

read next
grade

Increment add 1 to counter


counter

Add grade accumu late


to sum sum of grades

Set averag e find the average


to sum/counter

display the
answer

FIGURE 1.11 Flowchart for the class average problem.


1.4 Progra mming Too l • l5

Program : Calcula te a nd repo rt the ave rage grade of a class .


Initialize Counter a nd Sum to 0
Do While there is more da ta
G et the n ex t Grade
Incre ment the Counte r
Add the Grade to the S um
Loop
Co mpute Ave rage = S um/Coun ter
Display Ave rage

FIGURE 1.12 Pseudoco de for the class average problem.

Class
average
problem

Get Compute sum and Calculate Display


grade number of grades average average

FIGURE 1.13 Hierarch y chart for the 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

2.1 An Introduction to Visual Basic 2010 18


• Why Windows and Why Visual Bas ic? • How You Develop a Visua l Basic Program
• The Different Versions of Visual Bas ic
2.2 Visual Basic Controls 20
• tarting a N ew Visua l Basic Program • A Text Box Walkthrough • A Button
Walkthro ugh • A Labe l W alkthro ugh • A List Box Wa lkth ro ugh • The N ame
Property • Two H elp Wa lkth roughs • Fonts • A uto Hide • Position ing and
Aligning Contro ls • Setting Tab Order
2.3 Visual Basic Events 37
• An Event Proced ure Walkthro ugh • Properties and Event Procedures of the Form
• The H eader of an Event Procedur • Open ing a Program
Summary 53

17
18 • Chapter 2 Visua l Basic, Controls, and Events

2.1 An Introduction to Visual Basic 2010


Visual Basic 20 10 is the latest generat io n of Visual Bas ic, a language used by man y software
deve lopers. Vi ual Basic was des igned to make user-friend ly programs ea ier to deve lop. Prior to
the creatio n of Vi sua l Bas ic, deve loping a fr iendly use r interface u ua lly req uired a programm er
to u e a language such as Cor C++, often requir ing hundreds of lines of code ju t to get a win-
dow to appea r on th e creen . N ow t he same program can be created in much less time with
fewer instructio ns.

Why Windows and Why Visual Basic?


What people ca ll graphica l user interfaces , o r G U is (pronounc ed "goo ies"), have revo lu t ion -
ized the computer industry. Instead of th e confusing tex t ual prompts that ea rlier use rs once aw,
today's use rs are presented with such dev ices a icons, buttons, and drop-d own lists that respo nd
to mo use clicks. Acco mpan ying the revo luti on in how programs look was a revo lu t ion in how
they fee l. Consider a program that req uests info rmation fo r a database. Figure 2.1 shows h ow a
program written before the advent of G U is got its informat io n . The program req uests the ix
pieces of data o ne at a time, with no oppo rtun ity to go back and alter previously entered infor-
mation. Then the screen clea rs and the six inpu ts are aga in requ es ted one at a time.

Enter name (Enter EOD to terminate ): Mr. President


Enter Address: 1600 P ennsylvan ia Avenue
Enter City: Washingt on
Enter State: DC
Enter Zip code: 20500
Enter Phone Number: 202-456- 1414

FIGURE 2.1 Input screen of a pre-Visual Basic program to fill a database.

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

Name : Mr. President

Address : 15 Penmr11vania Avenue

~· Vu'ashington

State : DC

Phone:

1Nrite to Database ] [ Exit

FIGURE 2.2 Input screen of a Visual Basic program to fill a database.


2.1 An lntroduc tion to Visual Basic 20 10
• 19

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!

How You Develop a Visual Basic Program


A key elemen t of plannin g a Visual Basic program is decid ing what the
user sees-in other
words, designin g the user interface. What data wi ll he or she be enterin g?
H ow large a window
should the program use? Where wil l you place the buttons the use r cl ick
o n to activate act io ns
in the program? Will the program have places to enter text (text boxes)
and places to disp lay
output ? What kind of warning boxes (message boxes) sho uld the program
use? ln Vi ua l Basic,
the respons ive objects a program designe r places on windows are ca lled
controls . Two features
make Vi ual Basic differen t from traditio nal program ming tools:

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:

1. Design the appeara nce of the window that the user ee .


2. Determ ine the events that the controls on the window sho uld respo nd
to.
3. Write the event procedu res for those events.

Now here is what happen s when the program is running:

1. Visual Ba ic mon itors the control s in the window to detect any


event that a control can
recogni ze (mou e movem ents, clicks, keystrokes, and so o n) .
2. When Vi ual Ba ic detects an event, it exa mines the program to see
if you've written an
eve nt procedu re for that event.
3. If you have written an eve nt procedu re, Visual Bas ic execute s the instruct
io ns that make up
that event procedu re and goes back to Step 1.
4. If you have not written an eve nt procedu re, Visua l Basic ignores the eve
nt and goes back to
Step 1.
20 • Chapt er 2 Visual Bas ic, Contro ls, and Eve nts

U sually, an event must happe n


These steps cycle cont inuous ly unt il the progra m ends.
ms are reactiv e mo re than active -
before Visual Bas ic wi ll do anythi ng. Eve nt-drive n progra
and that makes them more use r friend ly.

The Different Versions of Visual Basic


versio n 2.0 in 1992, versio n 3 .0 in
Visual Bas ic 1.0 first appea red in 199 1. It was followed by
n 6.0 in 1998. VB.NE T, initia lly
1993, versio n 4.0 in 1995 , versio n 5.0 in 1997, and versio
with the earlier versio ns of Visual
re leased in Februa ry 2002, was not backward compa tible
develo pers, such as tru e inheri tan ce.
Bas ic. It incorp o rated many fe atures reques ted by softw are
ic 2008 , re leased in N ovemb er 2007 ,
Visua l Bas ic 2005 , re leased in N ovemb er 2005 , Vi ual Bas
ntly impro ved versio ns of VB.NE T.
and Visual Bas ic 2010, re leased in A pril 201 0 are sign ifica

2.2 Visual Basic Controls


a form) with boxes into which
Visual Basic progra ms display a Windo ws-style screen (called
s that they click to in it iate action s.
users type (and in which users edit) inform ation and button
n, we exam in e forms and fo ur of
The boxes and button s are referre d to as contro ls. In this sectio
the most useful Visual Bas ic contro ls.

Starting a New Visual Basic Program


own fo lder. Before writ ing yo ur first
Each progra m is saved (as severa l file and subfo ld ers) in its
to ho ld yo ur progra ms.
progra m, you should use W indows Explo rer to crea te a fo lder

Tool bar

BasK: 2010 Expr.,..

Get Started te WS
I(}J New ProJ~ct .•
Welcome
t65 Op~n ProJed ...

I -..,.-, Welcome to Visual Basic 2010 Express


·- The tradrbon continues! Vi.suaiBa~c 2010 Express h~ps
r- =
d~lopers qutckly create o.citmg int~actrve
appltcatlons for
t:
Windows Wrth the new Visual Baste 2010 Express deveopmen
;;;! 3-2-1 rrMronment., •mproved performanc~ and lots of new f9tur~
;;;! 3-2-2 ~ mov1ng from great id9 to gre:at application has. newt been
lumtng
easier. Ktck off your learntng at the B~ann~ D~oper
;;;! 3-2-3 Center. or find the Ia~ and coolS projeCts on Co<hng4Fun
.

•.lil 3-2-4 Begtnne:r o~eloper learnang Cent~


'iii 3-1-1 Cod•ng4Fun
More on Visual Baste 2010 Express
;;;! 3-1-2
•;;l 3-1-3
Quickly Create Your first Application
fj13-1-4
;;;! 3-1-5
¥];13-1-6

What's New in Visual Basic 2010 Express

FIGURE 2.3 Visual Basic opening screen.


2.2 Visual Bas ic Controls • 21

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

~ l'lPF Application Visual Basic

~
ve WPF Browser Application Visual Basic

Console Application Visual Basic


~}'a

FIGURE 2.4 The Visual Basic New Proj ect dialog box.
22 • Chapter 2 Visual Basic, Controls, and Events

Start Page Form Designer Document Properties Solution Explorer


tab tab window window window

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

Too lbox "" fl. X


All Nind ows Fo rms ...
'----'-t--- Pushpi n
Group names
,. Common Co nt ro l ~
Pointer
0 Button
~ Ch eckBox

Ch eckedListB ox
A

~ :.......-

~ 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

FIGURE 2.6 The Toolbox's common controls.

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

in the text box. Visual Ba, ic


co ntrols
Buttons: The user clicks a button to in itiate an act ion.
List boxes : In the first part of the book, we usc list boxes to disp lay output. Later, we use list
boxes to make selec ti ons.

A Text Box Walkthrough


1. Double-cl ick on the text box icon in the Common Controls group of the Too lbox. A rectan-
gle with two small squares, call ed sizing handles , appea rs at the upper left co rner of the
fo rm. (You can alter th e width of the tex t box by d ragging one of its sizing h andles.) Move
the mouse arrow to any po int of the text box other than a sizing handle, ho ld down the left
mo use button, and drag the text box to the cente r of the fo rm. See Fig. 2. 7. (Note: Ta k
button are used to set certa in prope rties of controls.)

· ·· = ffi4- Tasks button

C = :J
Sizing handles

FIGURE 2. 7 A text box with sizing handles.


24 • Chapter 2 Visua l Bas ic, Controls, and Eve nts

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

BorderStyl e Fixed3D Ri ghtl oleft No


Curs,or !Beam Scroi!Bar< Non e
Font Microsoft Sans Seri Sh ortcutsEnabled True
ForeColor • WindowText Size 100.20
Line. Strin g [] Array Tablndex 0
Rightl ol eft No TabStop True
Scroll Ba r< Non e Tag

B l eft
TextAiign Left TextAiign Description
Text Text pane
The text associated with the control. The text associated with the control.

Categorized view Alphabetic view

FIGURE 2.8 Text box Propertie s window.


2.2 Visual Bas ic Contro ls • 25

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.

FIGURE 2.9 Setting the Text property to David.

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

Font : Font st}1e : Size :

Microsoft Sans Serif Regular 8 I OK

Microsoft Sans Ser' .. "" [ Cancel


Minya Nouvel e l=_
Hw-1.
::\Iodern X o. ~0 Bold ObliquE
~onotype Corsn,oa

Effects Sample

[ ] Strikeout
A.aBbYyZz
[ ] Underline

Script:
Westem

FIGURE 2.11 The Font dialog box.

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

FIGURE 2.12 Setting the Text property.

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.

D_. Fo rml Prop ertie::-


Bl!ltt~D<nl System . l~li n do ws..Forms..Button ...

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.

FIGURE 2.13 D esignating P as an access key.

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.

A List Box Walkthrough


1. C lick on the N ew Proj ect button to begin a new program. Fee l free to keep the default
name, such as WindowsApplica tionl.
30 • Chapter 2 Visual Basic, Control , and Events

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.

The Name Property


the name
The form and each control on it has a N ame property. By default, the form is give n
l and TextBox 2. These names can (and
Forml and controls are given names such as TextBox
form or contro l. Also, it
should) be changed to descriptive ones that refl ect the purpose of the
identifies
is good programming practice to have each name begin with a three-let ter prefix that
the type of the obj ect. See Table 2.1.

IM:J!fJM Some three-letter prefixes.


Object Prefix Example

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.

Positioning and Aligning Controls


Visua l Bas ic prov ides seve ra l tools for pos itioning and aligning con tro ls on a fo rm. Proximity
lines are short line segments th at help you place controls a co mfo rtab le distance from eac h Vid eo Note

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.

A Positioning and Aligning Walkthroug h


1. Begin a new program.
2. Pl ace a button nea r the center of the fo rm.
32 • Chapter 2 Visual Basic, Controls, and Even ts

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 .

•:;' Form! [Elf®] ~ • Forml

I Button1 J ·'
+ - Proxim .ity Button 1
line

Button2

(a) (b)

• Forml r;;-1[@] 1!![] • Forml GJ[]il ~

I I J J
I Button 1
l I Button2 J Snap
line
l
Button 1
J
j
Button2

t I

(c) (d)

FIGURE 2.14 Positioni ng controls.

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.

Setting Tab Order


Each time the Tab key is pressed while a program is running, the foc us moves from one control
to another. The tab ord er for the contro ls is dete rmined by the se ttings of the ir Tablndex prop-
erti e . Init ia lly, co ntrols rece ive the focus in the order they were placed on the fo rm. The first
con tro l placed on the fo rm h as a Tablndex se tting of 0, the second contro l has a se tting of 1,
and so on . The tab o rd er ca n be changed by renumberin g the contro ls' Tablndex settings.
Whether or no t a control ca n rece ive the foc us by tabb ing is determined by the setting of
its TabStop property. By defa ult, this setting is True for buttons, tex t boxes, and list boxes, and
False for labe ls. In this book we always use these default settings. Note: Even tho ugh labe ls do
not receive the focus while tabbing, they are till ass igned a tab index.

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.

Practice Problems 2.2

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

So ar and cathed rals a r""


I'm the king of th=-
mu ch th """ r.a m -"' - fi r.<~:t w bu il d
th "'m . th ""'n , """ pray.
A Quot e by lecnardb DiCaprio
A.Ouote

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.

Solutions to Practice Problems 2.2

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 ,

FIGURE 2.15 Toolbox gro up names.

2.3 Visual Basic Events


When a Visual Bas ic program runs, the form and its contro ls appear on th e screen.
Norma ll y, VideoNore
nothing happe ns until the user takes an action, such as clicking a contro l or pressing
a key. We Evenr
call such an action an event. The programm er writes code that reacts to an event by
perform- procedure>
ing so me function a lity.
The three steps in crea ting a Visual Bas ic program are as fo llows:

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

controlN ame.pro perty = setting

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"

disp lays the word Hello in the text box.


2. The statemen t

btnButt on .Vi sible = True


makes the button visible.
38 • Chapter 2 Visua l Basic, Contro ls, and Eve nts

3. The statem ent


txtBo x.For eColo r = Color . Red
to red.
sets the color of the charac ters in the text box named txtBox
btnBu tton" is differe nt from
Most events are assoc iated with contro ls. The event "click on
btnBu tton. C lick and lstBox .C lick.
the event "click on lstBox". These two events are specifi ed
n in a block of code called an
The statements to be execu ted when an eve nt occur are writte
proced ure (called the heade r) has
event proced ure or event handle r. The first line of an event
the form
As System . Objec t ,
Priva te Sub object Name_ event ( ByVal sende r
ByVal e As System .Even tArgs ) Handl es objec tNam e.even t

pa rentheses in this book, for the


S ince we do not make any use of the lengthy text inside the
it will automaticall y appea r in our
sake of readab ility we rep lace it with an ellipsis. Howeve r,
nt proced ure. The structu re of an
progra ms each time Visual Bas ic creates the heade r for an eve
event proced ure is
objec tNam e.even t
Priva te Sub object Name_ event ( . .. ) Handl es
s tatem ent s
End Sub

where the three dots (that is, the ellips is) represe nt
System .Even tArgs
ByVal sende r As System . Objec t , ByVal e As

and "End" have specia l mean-


Words such as "Private," "ByVa l," "As," "Sub," "H and les,"
ed words . The Code Ed itor auto-
ings in Visual Basic and are referred to as keywo rds or reserv
the word in blue. The word "Sub"
matica lly capita lizes the first letter of a keywo rd and displays
the first line identifies the object
in the fir t line signals the beginn ing of the procedure, and
s the termin ati on of the event pro-
and the eve nt occurring to that object. The last line signal
two lines. These tatem ents are
cedure. The statements to be execu ted appea r between these
word "Priva te" indica tes that the
referred to as the body of the event procedure. (Note: The
ll not conce rn us unt il much later
event proced ure ca nnot be invo ked by anoth er form. This wi
object and the event happe ning to
in the book. The ex pressio n fo llowin g H andles ident ifies the
lt name of the proced ure and can
that obj ect. The ex pressio n "obj ectNam e_ event " is the defau
na me. The word "Sub" is an abbre-
be changed if de ired. ln this book, we always use the default
viatio n of Subroutine.) For instan ce, the event procedure
btnBu tton.C lick
Priva te Sub btnBu tton_ Click ( ... ) Handl es
txtBo x.For eColo r = Color .Red
End Sub

the button is cl icked. The click-


changes th e co lor of th e words in the tex t box to red wh en
procedu re is said to handl e the
ing of the button i said to raise the eve nt, and the eve nt
eve nt.

An Event Procedure Walkthrough


button , wi ll be used to demon strate
The form in Fig. 2. 16, which contains two text boxes and a
event proced ures will be used to
what event proced ures are and how they are crea ted. Three
The event proc dures are named
alte r the appea rance of a ph rase appearing in a t xt box.
txtFirst_ TextC hanged, btnRed_C lick, and txtFirst_Leave.
2.3 Visual Basic Events • 39

OBJECT PROPERTY SETTING


a ... Demon stration ~~ @J \~ frmDem o Text Demon stration
txtFirst
txtSeco nJ
btnRcd Text C hange C olor to Red

Change Color to Red

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.

Code Editor Form Designer


tab tab

Visual Basic 2010 Express

Too ls Window Help

- Public Class -~'rmDemo

~ My Proj ect
En d Class
::::J frmDemo.vb

11

FIGURE 2.17 The Visual Basic IDE in Code Editor mode.

The tab labe led frmDemo.vb correspond to the Code Editor. C


lick on the tab labeled
frmDe mo. vb [Design], when you want to return to the Form Design
er. We will place our
program code betwee n the two lines shown . Let's refer to this region
as the progra m region .
Figure 2.17 shows that the Code Editor IDE has a Toolbox , Solutio n
Explorer, and Prop-
erti e window that support Au to Hide. The Solutio n Explorer window
for the Code Editor
40 • Chapte r 2 Visual Basic, Contro ls, and Eve nts

Ed ito r's Toolb ox has just o ne


functi ons exactl y like the one for the Form Des igner. The Code
can be copied into a progra m
group, G eneral, that is used to store code fragme nts which
be used in this textbo ok.
when need d. The Code Editor's Properties windo w will not
to the Fo rm Des igner. (Yo u a lso
3. C lick o n the tab labe led "frmDemo.v b [Des ign]" to return
can invoke the Fo rm Design er by clickin g Designer in the
View menu , or by right-clickin g
the Code Edi to r and clickin g View Designer.)
but now t he fo llowin g two lines of
4. Doubl e-click o n the button . The Code Edi tor reappe a rs,
r is locate d on the blank line
code have been add ed to the progra m reg ion and the curso
betwe en them.
d.Clic k
Priva te Sub btnRe d_ Click ( ... ) Handl es btnRe

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

at the cursor locatio n .


Each time you type a letter
This statem ent beg ins with the name of a contro l, txtFirst.
ible co mplet ions fo r the name. '
of the name, lntelliSense drops down a list contai ning poss
letters that yo u have typed.
A s you contin ue typing , the list is shorte ned to match the
. A t this po in t, you have the
Figure 2. 18 shows the list after the letters tx have been typed
follow ing three option s on how to contin ue:
t e m. Obje
Pr i vate Sub b t nRed_ Cli ck (ByVa l se n de r As Sys

bet First
.) tct5econcl
.---- .---- -
Comm on All

FIGURE 2.18 Drop-d own list produc ed by lntelliS ense.

i. Doubl e-click on txtFirst in the list.


or the Enter key.
ii. Keep the curso r on txtFirst, and th en press the Tab key
iii . Directly type in the remain ing six lette rs of txtFirst.
down a list conta ining
After you type the dot (.) follow ing txtFirst, lntelli Se nse drops
ed by properties icon (
a ).
properties of text boxes. See Fig. 2. 19(a). Each property is preced
later. Methods are preced ed by
[The list also contains items called methods, which we will discuss
).J
A t this point, you ca n scroll up the list and double-click on ForeC olor
a method icon (
you can keep typing. Afte r you
to automat ically enter that property. See Fig. 2.1 9(b). O r,
At that point, you can press
have typed "For" , the list shorte ns to the single wo rd ForeC olor.
Fo reColo r.
the Tab key or the Enter key, or keep typing to obtain the word
th e list of colors sh own in
After you type in the equal ign , lnte lliSe nse drops down
double-click ing o n it, or typ ing
Fig. 2.20. You h ave the optio n of scrolling to Color.Red and
Colo r.Red into the statement.

.
This fea ture of lntelli Sense is referred to as Compl ete Word
1
2.3 Visua l Basic Eve nts
• 41

Acc eptsR t urn


Ace r sTa b
--
~ Ace ss tbdt •O bi c
Acc e ~s t bl D sc rtptt o n

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

FIGURE 2.19 Drop -dow n list prod uced by lntelliSen se.

Priv ate Sub b t nRed _Cl i ck( ByV al


se n der As Sys t em. ~bj e c1
t x t F i r s t. Fo r e Co l o r

~ Color .Aii ceB iue


~ Co lor.A ntiqu e IVhite
.:..) Color.Aqua
..:..J Co lor.Aquam ari ne
.:..J Co lor.Azure
.:..J Co lor.Beige
~ Color .Bisque
.:..J Co lor. Black
..:..J Co lor.B ia nchedAim ond
..:.] Co lor.Biue
.:..J Co lor.Biue violet
.:..J Color. Brow n
.:..J Co lor.Burly\' oocl
.:..J Color. CacletBiue

FIGURE 2.20 Drop -dow n list of color s prod uced by lntel


liSen se.

6. Retu rn to the Form Des igne r and double-cl


ick on the first tex t box. The Cod e Ed itor
pears, and the first and last lines of the eve reap-
nt procedur e txtF irst_ Text C hanged appear
program regio n. This proced ure is raise d by in the
the even t txtFirst.Tex tC hanged- that is, whe
ever there is a chan ge in the text displayed n-
in the tex t box txtF irst. Type the line that
the Fore Colo r prope rty of txtFirst to Blue . sets
The even t procedur e will now appea r as follo
ws:
Priv ate Sub txtF irst _ Text Chan
ged{ . . . ) Han dle s txtF irst. Tex tCha
txtF irst. For eCo lor = Colo r .Blu nged
e
End Sub
nts
42 • Cha pter 2 Visual Basic, Con tro ls, and Eve

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

··- 1i· g) 'Y

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

whe n the focus is


(Th e even t txtFirst.Lea ve is raise d
9. Double-click on the Leav e even t. even t proced ure
The head er and last line of the
moved away from the tex t box.) ts the Fore Color
irst_ Leav e will be disp laye d. In this procedur e, type the line that se
txtF
e Edit or will now look as follo ws:
property of txtFirst to Black. The Cod

Pub lic Cla ss frmD emo


) Han dles btnR ed.C lick
Priv ate Sub btnR ed_ Clic k( ...
txtF i rst. For eCo lor = Col or
.Red

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

11_. Demo nstrati o n l = I @) l...,£s--=J


HelloI

Olange Color to Red

FIGURE 2.22 Text box contai ning input.

happe ned to txtFirst. Thus, the event proced ure txtFir


st_Le ave was invoked, and th e code
inside the proced ure was executed.
14. C lick on th e butto n. This in vokes the event proce
dure btnRe d_Cli ck, which changes the
color of the words in txtFirst to Red.
15. C lick on the first text box, and type the wo rd "Frien
d " after the wo rd "H e llo". As soon as
typing begins, the text in the text box is changed and
the TextC h anged eve nt is ra ised.
This event causes the color of the conte nt of the tex
t box to becom e blu e.
16. You can r peat S teps 12 throu gh 15 as many t imes
as you like. When yo u are finish ed, end
the progr am by clicki ng on the Stop Debugging butto n
on the Toolb ar, clicki ng on the form 's
C lose butto n, or pressing A lt + F4.
Note: After view ing events in the Prope rties window, click
on the Proper ties butto n ( l ] ) to
the left of the Events butto n to return to disp lay ing prope
rties in the Prope rties wind ow.
Properties and Event Procedures of the Form
You can ass ign prope rtie to the form itself in code. H
oweve r, a statem ent such as
frmDe mo.Te xt = "Dem onstr ation "

will no t work. The fo rm is referr ed to by the keywo rd


Me. There fo re, the prope r sta temen t is
Me.T ext = "Dem onstr ation "

To disp lay a list of a ll the even ts assoc iated with frmDe


mo, select the fo rm in the Fo rm
Des igner and click o n the Even t butto n in the Prope
rties window's too lbar.
The Header of an Event Procedure
As menti oned earlier, in the heade r fo r an eve nt proce
d ure uch as
Priva te Sub btnOn e Click ( .. . ) Hand les
btnOn e . Click

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

Priva te Sub Butto nPush ed( ... ) Hand les


btnOn e .C lick
A lso, an event proce dure can handle more t han one
event . For insta nce, if th e prev io us
line is chang ed to

Priva te Sub Butto nPush ed( ... ) Hand les


btnOn e . Click , btnTw o .Cl ick
ts
44 • Chap ter 2 Visua l Basic, Cont ro ls, and Even

r btnO ne or btnTwo is clicked.


the even t procedure wi ll be invo ked if eithe
hold ers for the phrase
We have been using ellipses ( ... ) as place
ByV al e As Syst em.E vent Args
ByV al send er As Syst em.O bjec t,
wo rd
ndin g of this type of phrase. Essentia lly, the
In C hapt er 5, we wi ll ga in a bette r und ersta some
raised the eve nt, and the lette r "e" ca rries
"sender" ca rries a reference to the obj ect that We will not make use of
ct wants to com mun ica te.
add ition al informati on that the se ndin g obje
eithe r "send er" or "e".

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.

1. From Visual Basic, click on Open Proje


ct in the File menu. (A dialog box will appear.)
dow nloa ded from the website.
2. Display the cont ents of the C h07 subfo lder
3. Dou ble-c lick on 7-2-3.
4. Dou ble-c lick on 7-2-3.sln..
/Other
5. If the Solution Explorer window is not
visible, click on Solution Explorer in the View
Windows menu.
ar at the
6. ln. the Solution Explorer window, click
on frmPresident.vb. (Five butto ns will appe
.) At any time you can click on the View Code
top of the Solution Explorer. See Fig. 2.23
click on the View Designer butt on to invoke
butto n to invo ke the Cod e Editor, or you can the
the Form Designer. The Show All Files and
Refresh butt ons, whic h allow you to view all
nsive ly begi nnin g
rtain files, wi ll be used exte
fi les in a program's fo lder and to upda te ce
used in th is textb ook.
with C hapt e r 7. The first butt on wil l not be

Show View View


All Files Refresh Code Designer

~ My Proje ct
[> bin
fm1Pr esid ents.v b

FIGURE 2.23 Solu tion Expl orer wind ow.

7. Pres F5 to run the program.


(See
, and press the Display Presidents butto n.
8. Type in a nam e (such a ]arne or William)
y time a de ired.
Fig. 2.24.) You can repeat this process as man
9. End the program.
2.3 Visual Basic Events • 45

a':} LJ.S. Preside ts l = I @] 1.....!3 ~·J

Rrst name: James

I Display Presidents
l
President James Madison
President James Monroe
President James Polk
President James Buchanan
I
President James Garfield
President James Carter
--

FIGURE 2.24 Output for program 7-2-3.

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

which moves the focus to the spec ified control.


3. We have ended our programs by clicking th e Stop Debugg ing butto n or press ing Alt + F4.
A mo re e legant technique is to create a button, ca ll it btnQuit, with captio n Quit and the
fo llowing event procedure:
Private Sub btnQuit_ Click( . .. ) Handles btnQuit.C lick
Me .Close()
End Sub

4. For state ments of the form

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

Private Sub b tnOn e_ Cli c k( . .. ) Handles btnTwo .C lick


btnTwo. Te x t = "Press Me"
End Sub
ns cut,
6. The Code Editor has many features of a word processo r. For instance, the operatio
the Tool-
copy, paste, and find can be carried out with the sixth through ninth buttons on
bar. These ope rations, and seve ral others, also can be executed from the Edit menu.
7. The Code Editor can detect certain types of errors. For instance, if you type
tx t F i rs t . Text = h ell o
word
and then move away from the li ne, the automat ic syntax checker wil l underl ine the
or is
"hello" with a blue squiggle to ind icate that somethin g is wrong. When the mouse cur
what
hovered ove r the underlin ed exp ression, the ed ito r will disp lay a message explaini ng
g the error, the dialog box in
is wrong. If you try to run the program without correctin
Figure 2.25 will appear.

1icros.oft Vis.ua l Basic 20 0 Express

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

FIGURE 2.25 Error dialog box.

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

I@:J!IIW Some default events.


Control D efault Event

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.

Practice Problems 2.3

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

2. Private Sub btnOutpu t_ Click( ... ) Handles btnOutpu t.Click


txtBox.F oreColor = Color.Re d
txtBox.T ext = "Hello"
End Sub

3. Private Sub btnOutpu t Click( ... ) Handles btnOutpu t.Click


txtBox.B a ckColor = Color.Ora nge
txtBox.T ext = "Hello"
End Sub

4. Private Sub btnOutpu t_ Click( ... ) Handles btnOutpu t.Click


txtBox.T ext "Goodbye"
txtBox.T ext "Hello"
End Sub

5. Private Sub btnOutpu t_ Click( ... ) Handles btnOutpu t.Click


txtBox.T ext = "Hello"
txtBox.V i sible = False
End Sub

6. Private Sub btnOutpu t_ Click( ... ) Handles btnOutpu t.Click


txtBox.B ackColor = Color.Ye llow
txtBox . Text = "Hello"
End Sub

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

8. Private Sub txtFirst_ Leave( ... ) Handles txtFirst. Leave


lblOne .BackColo r = Color.Wh ite
lblOne .Text = "Hello"
End Sub

9. Private Su b txtSecond_ Enter( ... ) Handles txtSecon d.Enter


lblOne .BackColo r = Color.Go ld
lblOne.T ext = "Hello"
End Sub

10. Private Sub txtSecond_ Enter( ... ) Handles txtSecon d.Enter


lblOne.V isible = False
lblOne.T ext = "Hello"
End Sub

In Exercises 11 through 16, determine the errors.


11. Private Sub btnOutpu t Click( ... ) Handles btnOutpu t.Click
Forml.Te xt = "He llo"
End Sub
2.3 Visual Basic Events • 49

12. Private Sub btnOutpu t_ Click( ... ) Handles btnOutpu t.Click


txtBox.T ext = Hello
End Sub

13. Private Sub btnOutpu t_ Click( .. . ) Handles btnOutpu t.Click


txtFirst. ForeCol or = Red
End Sub

14. Private Sub btnOutpu t_ Click( ... ) Handles btnOutpu t.Click


txtBox = "Hello"
End Sub

15. Private Sub btnOutpu t_ Click ( . .. ) Handles btnOutpu t. Click


txtBox . Font.Siz e = 20
End Sub

16. Private Sub btnOutpu t_ Click( ... ) Handles btnl.Clic k, btn2.Cli ck


Me.Color = Color.Ye llow
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

OBJECT PROPERTY SETTING


ll .... TextAiig nrnent GJI 8 ![}[] frmAli gn Tex t Tex t Alignme nt
txt Box ReaciO nl y Tru e
brnLeft Tex t Left Justi fy
[ Left Justify btnCent e r Tex t Cente r
brnRigh t Tex t Right Just ify
[ Center

[ Right Justify

(Wingd ings charac-


34. Whe n one of the buttons i pressed , the face changes to a smiling face
te r"]") or a frown ing face (Wingd ings c h aracte r "L") .

OBJECT PROPERTY SETTING

ll .... Face ~~ 8 1[};[1 frmFace Tex t Face


lblFace Fo nt N a me W ingdings
@ Fo nt S ize 24
Text K
Smile S mile
btn S mil e Text
btnFro wn Tex t Frown
Frown

the text box .


35. Pres ing the buttons alte rs the backgro und and foregro und co lors in
OBJECT PROPERTY SETTING

ll .... Colorful Text ~~ 8 IE![] frmCo lo r Tex t Co lo rful Text


lblBack Text Bac kgro und
Background Red l [ Blue l btnRecl Tex t R eel
brnBlue Text Blue
Beautiful Day
txt Box Text Bea utiful Day
Tex tAii gn Cente r
Foreground Vlll1ite Yello•"'
lblFo re Tex t Foregrou nd
btnWhi te Tex t White
brn Yello w Tex t Ye llo w

red . When it loses


36. When on e of th e three text boxes rece ives the focus, its tex t b comes
tex t boxes to Left
the focus, the tex t returns to black. The buttons se t the a lignmen t in the
se ttings fo r the
or Right. No te: Re ly on lntell iSe n.se to provid e you with the proper
TextAli gn prope rty.
OBJECT PROPERTY SETTING

D::t One, Two, Three ~~ 8 l[};f] frml 23 Tex t O n e, Two, Three


txtO ne Tex t O ne
One
txtTwo Tex t Two
txt Three Tex t Three
Two
brnLeft Tex t Left
Three btnRigh t Tex t Right
2.3 Visual Basic Events • 51

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.

OBJECT PROPERTY SETTING


a;:t Sayi ng!; frmQuote Tex t Sayings
txtQuote ReadOnly True
txtL ife Text Life
Future Tn.Jth txtFuture Tex t Future
Life
txt Truth Text Truth

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.

OBJECT PROPERTY SETTING


a;:t Text Box GJI 8 I[§] frmTextBox Text Text Box
txt Box
btnDisab le Text Disable Text Box
Disable Text Box btnEnable Tex t Enable Text Box

Enable Text Box

In Exercises 3 9 through 44, write a program to carry out the task.


39. The fo rm contains four squ are buttons arranged in a rectangular array. Each button h as the
caption "Push Me". When the use r clicks on a button, the button disappea rs and the other
three become o r remain visible. See Fig. 2.26.

a:} Pus.h Me ~~~ Traffic Light ~~ 8 ~ ~

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

Solutions to Practice Problem 2.3

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

Programming Projects 100

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:

Mathematical Notation Visual Basic Notation


a · b or a X b a* b
a
r aAr

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

removes a ll the items d isplayed in the list box l tBox .

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

OBJECT PROPERTY SETTING


a,. 3-1-1
frm A rithmetic Text 3- 1-1
r- - - - - - - - - ,
l stResu~s
lstResults
btnCompute Tex t Compute

Compute

Private Sub btnCompute_ Click( ... ) Handles btnCompute.C lick


lstResults.It ems . Clear()
lstResults.Ite ms.Add(3 + 2)
lstResults . Items.Add(3 - 2)
lstResults.Ite ms.Add(3 * 2)
lstResults.Ite ms.Add(3 I 2)
lstResults.Ite ms.Add(3 A 2)
lstResults.Ite ms.Add(2 * (3 + 4))
End Sub

[Run, and then click o n the button.]

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

dista nce = speed X time elapsed

H e re's h ow this proble m wo uld be solved with a computer progra m:

Private Sub btnCompute_ Click( ... ) Handles btnCompute.C lick


Dim speed As Double
56 • C hapter 3 Variables, Input, and O utput

Dim t i meElapse d As Double


Dim distance As Double
lstResul ts . Items.Cl ear()
speed = 50
timeElap sed = 14
distance = speed * timeElap sed
lstResult s.Items.A dd (distance )
distance = 410
timeElap s ed = distance I speed
lstResul ts.Items . Add(time Elapsed)
End Sub

[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

Dim v arName As Double

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

Dim varName As Double = 50

declares the specified variab le as a va riable of type Double and gives it th e ini tial value 50.
The statement

lstBox.Item s.Add(varN ame)

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

Dim interestRa te As Double


interestRa te = 0.05

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:

Private Sub btnCompute _ Click( . . . ) Handles btnCompute . Click


Dim a As Double
Dim b As Double = 3
lstResults .Items . Clear()
lstResults. Items.Add (a)
lstResults .Items . Add(b)
a = 5
lstResults .Items.Ad d(a * (2 +b))
End Sub

[Run , and then click on the button . T he fo llowing is di splayed in the list box .]
0
3
25

If var is a variab le, then th e ass ignment statemen t

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

Private Sub btnCompu te_ Click( ... ) Handles btnComp ute.Click


Dim a As Double
Dim b As Double = 3
Dim c As Double
lstResul ts.Items. Clear()
lstResult s.Items.A dd(a)
lstResult s.Items.A dd(b)
a = 5
c = a * (2 + b)
lstResult s.Items.A dd(c)
End Sub

The expression a* (2 + b) is evaluated to 25, and then this valu e is ass igned to the vari able c.

Incrementing the Value of a Variable


Beca use the expression on the right side of an ass ignment statement is evaluated before an
ass ignment is made, a statement such as

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

In general, if n has a numeric value, then the statement

var += n

add s n to the value of var.

Built-In Functions: Math.Sqrt, lnt, Math.Round


There are several co mmon operation s that we often perform on numbers other than the stan-
dard arithmetic operation s. For instance, we may take the square root of a number or round a
number. These operations are perform ed by built-in functions. Functions assoc iate with one or
more value , called the inj)ut , a single value called the output. The function is said to return the
output value. The three functions considered here have numeric input and output.
The function Math.Sqr t ca lculates th e square root of a number. The function Int find s the
greatest intege r less than or equ al to a number. Therefore , lnt discards the decimal part of pos-
itive numbers. The va lue of Math.Rou nd(n, r) is the number n round ed to r decimal places.
The parameter r ca n be omitted. If so, n i round ed to a whole number. Some examples fo llow:
Math.Sqr t (9) is 3. lnt(2.7 ) is 2. Math.Rou nd(2 .7) is 3.
Math.Sqrt(O ) i 0. lnt(3) i 3. Math.Round(2.3I7, 2) i 2.32 .
Math.Sqrt (6.25) is 2.5. Int(- 2. 7)is -3. Math.Rou nd( 2.317, 1) is 2.3.
3.1 Numbers • 59

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:

Private Sub btnCompute Click( ... ) Handles btnCompute.Click


Dim n As Double
Dim root As Double
n = 6. 76
root = Math . Sqrt(n )
lstResults.Items .Clear()
lstResults.Items.Add(root)
lstResults.Items.Add(Int(n))
lstResults . Items . Add( Math .Round(n, 1))
End Sub

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

Private Sub btnCompute_ Click( ... ) Handles btnCompute . Click


Dim a As Double
Dim b As Double
a = 2
b =3
lstResults . Items.Clear ()
lstResults.Items .Add( Math . Sqrt((S *b) + 1))
lstResults . Items.Add(Int( (a A b) + 0.8))
lstResults . Items.Add( Math .Round(a I b, 3))
End Sub

[Run, and then click on the butto n. The fo llowing is disp layed in the list box.]
4
8
0.667

The Integer Data Type


In this text, we sometim es need to use va riab les of type Intege r. An intege r variab le is declared
with a state ment of the fo rm

Dim varName As Integer

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

Two other types of multipl e-decla ration state ment are


Di m a As Do uble , b As I nteger
Dim cAs Doubl e = 2, b As I n t ege r = 5

Two Integer-Valued Operators


this section, the Mod
ln add ition to the five arithme tic operato rs discussed at the beginni ng of
rators. Let m and n be pos itive
operato r and the integer division operato r( \ ) are also useful ope
an integer quotien t
whole numbers. When you use long division to divide m by n, you obta in
m Mod n is the inte-
and an integer rema inder. In Visua l Bas ic, m \ n is the integer quotien t and
ger remainder. Fo r instance ,
14 \ 3 is 4 and 14 Mod 3 is 2
19 \ 5 is 3 and 19 Mod 5 is 4
10 \ 2 is 5 and 10 Mod 2 is 0.

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

lfi':JIIIM level of precedence for arithmetic operations.


() Inne r to outer, left to right
1\ Left to right in express ion
'!' / Left to right in expressio n
\ Left to right in expressio n
Mod Left to ri ght in express ion
+- Left to ri ght in express io n
3.1 N um be r • 61

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

Three Types of Errors


G rammat ical errors, such as misspellings, omts tons, or incorrect punctuation s, are called
syntax errors. Most syntax errors are spotted by the Code Ed itor when they are entered. The
editor und erlines the syntax erro r with a blue squiggly line and d isplays a description of the
error when the mouse cursor is hovered over the squiggly li ne. Some incorrect statements and
the ir errors are as follows:
Statem ent R eason for Error
lstBox.l tms.Add (3 ) The word Items is misspelled.
lstBox.ltems.Add(2+ ) T he nu mber following the plus sign is missing.
Dim m; n As Integer The se micolon should be a comma.
Error that occur while a program is runn ing are called runtime errors or exceptions. They
usually occur because something outside the program, such a a use r, database, or hard d isk, doe
not behave as ex pected. For instance, if the file Data.txt is not in the root folder of the C drive,
then a statement that refers to the fil e by the fi lespec "C: \Data.txt" will cause the program to
stop execut ing and produ ce a message box with the title
FileNotFou ndExceptio n was unhandled .

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.

The Error List Window


Syntax errors are not only ind icated in the Code Ed itor, but al o are listed in the Error List window.
Note: If the window is not visible, click on Error List in the View/Other Windows menu.

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.

Private Sub btnCompute _ Click( ... ) Handles btnComput e.Click


Dim m; n As Double
lstResults .Items . Add(S
lstResults. Items.Add (a)
End Sub
62 • Chapter 3 Variab les, Input, and O utput

[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

Desc ri ption Fil e Lin e Column Proj ect


frmShowErrors..vb 4 10 3-1-6
lorJ 1 Ch aracter is not vali d.
26 3-1-6
1 ~ 2 ')' expected. frm Sh owErrors.vb 5
l.;t 3 Name 'a' is not decl ared. frmShowErrors.vb 6 26 3-1-6

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

displays NaN. Note: NaN is an abb rev iation fo r "Not a Number."


7. If the va lu e of num Var is 0 and numVar h as type Double, then the statements
numVarin v = 1 I numVar
lstBox.It ems . Add(numV arinv)
lstBox.It ems.Add (l I numVarin v)

cause the following items to be displayed in the list box:


Infinity
0

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.

Practice Problems 3.1 ·· -·-

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

4. W ri te a tateme nt that increa es the va lue of the numer ic va riab


le var by 5%.

In Exerci ses 1 throug h 6, evalua te the numeric expres sion withou


t the compu ter, and then
use Visual Basic to check your answer.
1. 3 * 4 2. 711 2
11
3. 1/ (2 3) 4. 3 + (4 *5)
5. (5-3) *4 6. 3 * ((- 2)115)
In Exerci ses 7 throug h 10, evalua te the expres sion.
7. 7\3 8. 14 Mod 4
9. 7 Mod 3 10. 14\4
In Exerci ses 11 through 16, determ ine wheth er the name is a va
lid variabl e name.
11. sa les.2008 12. room& Boa rd
13. fO rM_ l040 14. 1040B
15. expenses? 16. INCOM E 2008
In Exercises 17 through 22, evalua te the numer ic expression where
a = 2, b = 3, and c = 4.
17. (a*b) + c 18. a*( b +c)
19. ( l +b)* c 20. a 11c
21. b 11 (c-a ) 22. (c- at b
64 • Chapter 3 Variab les, Input, and Output

to calcu late and displa y the value of


In Exerc ises 23 throu gh 28, write an event procedure
the expression.
3
23. 7. 8 + 5 24. (1+2 ·9)
4
25. 5.5% of 20 26. 15 - 3(2 + 3 )
27. 17(3 + 162) 28. 4 1/2 - 3 5/8
in the value of each variable after each
In Exerc ises 29 and 30, comp lete the table by fill ing
line is execu ted.
29.
X y
btnE valua te.Cl ick
Priva te Sub btnE valua te Click ( ... ) Hand les
Dim X, y As Doub le
X - 2

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

Priva te Sub btnE valua te - Click ( ... ) Hand les


btnE valua te.Cl ick
Dim bal, inter , withD r As Doub le
bal = 100
inter = 0 . 05
withD r = 25
bal += inter * bal
bal = bal - withD r
End Sub
yed in the list box by the lines of
In Exerc ises 31 throu gh 38, determ ine the outpu t displa
code.
31. Dim amou nt As Doub le
amou nt = 10
lstOu tput.I tems. Add( amou nt - 4)

32. Dim a, b As Integ er


a = 4
b = 5 * a
lstOu tput . Items .Add( a + b)

33. Dim n As Integ er = 7


n += 1
lst0u tput. Items .Add (1)
lstOu tput. Item s . Add(n )
lstOu tput.I tems .Add (n + 1)

34. Dim num As Integ er = 5


num = 2 * num
lstOu tput.I tems. Add( num)
3.1 N umbers • 65

35. Dim a, b As Integer


lstOutput.I tems.Add( a + 1)
a = 4
b =
a * a
lstOutput.I tems.Add( a * b)

36 . Dim tax As Double


tax 200
t ax 2 5 + tax
lstOutput . Items.Add( tax)

37. Di m totalMinut es, hours, minutes As Integer


= 135
tota l Minutes
hours = totalMinut es \ 6 0
minutes = totalMinut es Mod 60
lstResults. Items.Add (hours)
lstResults . Items . Add(minute s)

38. Dim t otalOunces , pounds , ounces As Integer


totalOunce s = 90
pounds =
totalOunce s \ 16
ounces = totalOunce s Mod 16
lstResults. Items.Add (pounds)
lstResults. Items.Add (ounces)

In Exe rcises 39 through 44, identify the errors.


39. Dim a , b, c As Double
a 2
b 3
a + b = c
lstOutput. Items . Add(c)

40. Dim a, b, c, d As Double


a 2
b 3
c d = 4
lstOutput. I tems.Add(5 ((a +b) I (c +d)

41. Dim balance, deposit As Double


balance 1,234
deposit $100
lstOutput. Items . Add(balanc e + deposit)

42 . Dim interest , balance As Double


0 . 05 = interes t
balance = 800
lstOutput. Items.Add (interest * balance)

43. Dim 9W As Double


9W = 2 * 9W
lst0utput . Items.Add(9 W)

44. Dim n As Double = 1.2345


lstOutput . Items . Add(Round( n , 2 ))
66 • Chapter 3 Va riab les, Input, and Output

In Exercis es 45 and 46, rewrite the code using one line.


45. Dim quanti ty As Intege r
quanti ty = 12

46. Dim m As Intege r


Dim n As Double
m = 2
n = 3

In Exercis es 4 7 through 52, find the value of the given functio n.


47. lnt(1 0.75) 48. lnt(9 - 2) 49. Math.S qrt ( 3 * 12)
50. Math.Sqrt( 64) 51. Math.R ound( 3. 1279 , 3 ) 52. Math.Round ( - 2. 6)
and bare numeri c
In Exercis es 53 through 58, find the value of the given functio n where a
variable s of type Double , a = 5 and b = 3.
53. lnt(-a / 2) 54. Math.R ound( a /b) 55. Math.S qrt ( a - 5)

56. Math.S qrt( 4 + a) 57. Math.R ound (a + .5 ) 58. lnt (b * 0. 5 )


Privat e Sub
In Exercis es 59 through 66, write an event procedu re with the header
and having one line for each step.
btncom pute_ Click ( 0 0 0) Handle s btnCom pute 0 Click,
Lines that display data should use the given variable names.
59. The fo llowing steps calculat e a company's profit:
(a) Declare all va riables as type Double.
(b) Ass ign the value 9845 6 to the va riable revenue .
(c) Ass ign the value 45000 to the variable costs.
profit.
(d) Ass ign the differen ce betwee n the variables revenue and costs to the variable
(e) Display the va lue of the variable profit in a list box .
GOO The followin g steps calculat e the amount of a stock purchase:
(a) Declare all variables a ty pe Double.
(b) Ass ign the value 25.625 to the variable costPerShare.
(c) Ass ign the value 400 to the variable numberOfShares .
(d) Ass ign the produ ct of costPerShare and numberO fShares to the variable
amount .
(e) Display the va lue of the variable amount in a list box .

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 :

(a) Declare all variable as type Double .


(b) Ass ign the va lue 5000 to the variable fi xedCosts.
(c) Assign the value 8 to the variable pricePerUnit.
(d) A ssign the value 6 to the variable costPerUnit.
3.1 Number • 67

(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

1600 ga llons of water


71. A U. S. geo log ical survey showed that Americ ans use an average of
used each year
per person per day, includin g industri a l use. How man y ga llons of water are
in the United S tates? Note: The current populat io n of the United States
i about 315 mil-
lion people.
a window area equa l
72. Accord ing to FHA specific ations, each room in a house should have
minimu m window area for a 14-ft
to at least 10% of the floor area of the room. What is the
by 16-ft room?

Solutions to Practice Problem 3.1


add it ion to be performed first, the
1. 14. Multiplic ations are pe1fo rmed befo re additions. If the intent is for the
express ion should be wri tten (Z + 3)* 4.
the variable var I, whereas the second
2. The first ass ignment statemen t ass igns the va lue of the variab le var2 to
ass ignment statemen t assigns varl's va lue to var2 .
3.

a b c

Private Sub btnEva luate - Click ( ... ) Handle s


btnEva luate.C lick
0 0 0
Dim a, b, c As Double
3 0 0
a = 3
3 4 0
b - 4
3 4 7
c - a + b
21 4 7
a = c * a
21 4 7
lstResu lts.Item s.Add( a - b)
21 16 7
b = b * b
End Sub

able the left of the equal sign) has


Each time an as ignment statemen t is executed, on ly one variab le (the vari
to

its va lue changed.


4. Each of the three fo llowing statemen ts increases the va lue of var by 5%.

var var + (0.05 * var)


=
var = 1.05 * var
var += 0 . 05 * var

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

Variables and Strings


of string variab les are
A string variable is a name used to refer to a string. The allowable names
VideoNot c or altered with
th e same as those of numeric va riables. The valu e of a string variable is assigned
c var iable. String
ass ignme nt stateme nts and displaye d in a list box like the va lue of a numeri
Strings

variab les are declared with stateme nts of the form


Dim varNam e As String
3.2 Strings • 69

Example 1 The following program shows how a signme nt statem ents i nd


the Add
n'letho d are used with strings. The string variabl e president is ass igned
a value by h e th ird line,
and this va lue is di played by the sixth line. The q uo tat ion mark
surro und ing eac? string litera l
are no t part of the literal and are not d isplaye d by the Add metho
d. (The fo rm fo r th ts example
con ta ins a button and a list box. ) Note: The Code Editor colors
string literals red.
Privat e Sub btnDis play_ Click( ... ) Handle s btnDis
play . Click
Dim presid ent As String
presid ent = "Georg e Washi ngton"
lstOu tput.I tems.C lear()
lstOut put.Ite ms.Ad d( "presi dent" )
lstOut put.Ite ms.Ad d(pres ident)
End Sub

[Run, and then click on the button . Th fo llowing is displayed in


the list box.]
presid ent
George Washi ngton

If x, y, . . . , z are charac ters and strVar is a string variabl e, then the


statem ent
strVar = "xy .. . z"

ass igns the string literal xy . . . z to the variabl e and the statement

lstBox . Items .Add ( "xy ... z")

or

lstBox .Items .Add( strVar )

di plays the string xy . . . z in a list box. If strVar2 is anothe r string


va riable, then the statement
strVar 2 = strVar

ass igns the va lue of th e va riable strVar to th e va ri able strVar


2. (The va lue of strVar will
re ma in the sa me. ) String lite ra ls used in ass ignm ent o r lstBox .lte
ms.Add statem ents mu st be
sur round ed by qu otati o n ma rks, but string varia bles are neve
r surro und ed by qu o tatio n
ma rks.

Option Explicit and Option Strict


Option Explic it a nd Option Strict bo th affect progra mming
. Th ro ugh o ut this book, we
ass um e tha t both optio ns a re in effec t. H av ing th em enab led
i co nside red good progra m-
ming prac tice . Opt io n Exp lic it requires that all va riables be decla
red with Dim statem e nts.
The disab ling of t hi s opt io n ca n lead to erro rs res ulting fro m
th e mi sspe lling of na mes of
va riab les. Opt io n S tric t requires exp lic it con ve rsio ns in mos t cases
whe re a va lue o r va ri able
of o n e t ype i ass igned to a va ri able of an other type. The a bse nce
of thi s opt io n ca n lead to
da ta loss.
Visual Bas ic prov ides a way to enfo rce Optio n Explic it and O ption
S trict for all progra ms
you crea te. C lick o n Options in the menu bar's Tools menu to open
the Op tion dialog box. In
the left pane, click o n the symbo l ( EJ o r C> ) to the left of Project s
and Solutio ns to expand t hat
entry. Then click o n the subent ry VB Defaul ts. Fo ur default project
settings will appear on the
right. (See Fig. 3 .1.) lf the se ttings for O ption Explic it and O bj ect
S trict are no t a lready set to
O n , change them to O n . Note: O ptio n Infer is disc ussed in C hapter
6.
70 • Chapt er 3 Vari ables , Input, and O utput

l 'i( l...;a...J
Optio ns

Default project settings :


r ~ Environ
m ent
General
Fonts and Colors
I Option Explicit: [on ~)
Keyboar d Option Strict: [on ~)
~ Proj ects and Solution s
Option Compar e: [Binary ~)
General
VB Defaults Option Infer. [on ~)
Text Editor Ba sic
Window s Form s Designe r

_-Jl [
..___o_ K Ca ncel
Show all settings

FIGURE 3.1 Optio n defaul t projec t setting s.

Using Text Boxes for Input and Output


statem e nts such as
The conte nt of a text box is always a string. Therefore,

strVa r = txtBo x.Tex t

and

txtBo x . Text = strVa r

to th e tring variab le strVar and vice


ca n be used to assign the co ntent s of t he text box
versa.
W ith Optio n Strict set to On, suc h
Numb ers typed into text boxes are stored as strings .
before they can be ass igned to nume ric
strings must be exp lic itly conve rted to nume ric va lues
C Dbl and C lnt conve rt strings repre-
va riab les o r used in num ric exp ress ions. The funct ions
Intege r, respec tively. Go ing in the other
sentin g ' mbers into numb ers of type Doub le and
a string rep rese ntatio n of the numb er.
direct ion, the funct ion CStr conve rts a numb er into
There fore, statements such as

dblVa r = CDbl (txtB ox.Te xt)

and

txtBo x . Text = CStr( dblV ar)

he doub le variab le dblVar and vice versa.


ca n be used to ass ign th e con tents of a text box to t
le," "conv ert to Integer," and "conv ert
CDbl, C lnt, and CStr, which tand for "conv ert to Doub
asting funct ions .
to String," are referred to as data conve rsion or typec
3.2 Strings • 71

Example 2 The fo llow ing progra m add s two numb ers suppl ied by
the user.

OBJECT PROPERTY SETTING


a_. Additi on ~I @) I~ fnnAdd Text Add it ion
Rrst lblFirstN um A utoS ize False
number: Text First num ber:
txtFirs tN um
Second lblSec ondN um A utoS ize False
number:
Text Secon d num ber:
tx tSecondN u m
Compute Sum
btnCo mpute Text Comp ute ~u m
lblS um Text S um:
Sum : txtS um ReadO n ly True

Priva te Sub btn Comp ut e _ Cl ick ( ... ) Hand


les btnCo mput e.Clic k
Dim n uml, num2 , sum As Doub le
numl = CDbl ( t xtFi r stNum .Text )
n um2 = CDbl (tx t Sec ondN um.Te xt )
sum = numl + num2
tx tS um . Text = CStr ( sum )
End Sub

[Run, type 45 into th e first tex t box, type 55 in to the


secon d tex t box, and cl ick o n the butto n.]

a.. Addi1i on l = I [§) ~~ ·tll


Rr~:t
number: 45

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

txtB ox.T ext 1234


""""
1-l ~l fro m
Opt ion St rict On disallow·s im plicit conv ersio ns
'I nt~er ' t o 'Strin g' .
.............. ............... ........................... ............................ ,

* Repl~.~~ ..·~.??..~:. lj''.i.~~..:S~~.r.Q:?.?.1.J .'. :]


p i vate Sub Butt o nl _Cli ck ( ByVa l send e r As Syj
t xtBo x . Text = CStr(1234)~
~
~ I m
.
I'll ,Expand All Previews
FIGURE 3.2 An Auto Corre ction helpe r box.

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

n. (The form for th is exa mple


Example 3 The follow ing program illust rates conc ate natio !.
space at the end of the strin g ass igned to quote
cont a ins a butto n and a text box. ) N otice the uld have to be
that ass igns a va lue to quo te wo
If that space were n't prese nt, then the state ment
quot e = quot el & " " & quot e2.

) Hand les btnD ispla y.Cl ick


Priv ate Sub btnD ispla y_ Clic k( ...
g
Dim quot el, quot e2, quot e As Strin
isn' t over , "
quot el = "The ballg ame
quot e2 = "unt il it's over ."
quot e = quot el & quot e2
txtO utpu t . Text = quot e & " Yogi Berr a"
End Sub
is disp layed in the tex t box.]
[Run , and then click on the butto n. The following
it's over . Yogi Berr a
The ball game isn' t over , unti l

ted with num bers and allows numbers to be


Visua l Basic also allows strin gs to be conc atena
res ult is a strin g.
conc atena ted with numb ers. ln each case, the

with a num ber. Noti ce that a


Example 4 The following program conc ate nates a strin g
e the word "keys." (The form for this example
space was inserted afte r the word "has" and befor
cont a ins a butto n and a text box.)
) Hand les btnD ispla y.Cl ick
Priv ate Sub btnD ispla y_ Clic k( ...
Inte ger
Dim str As Strin g , numO fKey s As
str = "The pian o keyb oard has "
numO fKey s = 88
& " keys ."
txtO utpu t.Te xt = str & numO fKey s
End Sub
ng is displayed in the text box.]
[Run, and then click on the butto n. The fo llowi
The pian o keyb oard has 88 keys .
3.2 Strings • 73

The statement

strVar = strVar & strVar2

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

strVar &= strVar2

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

is the number of che1racters in the string,

str.ToUp per

is th e string with a ll it lette rs cap ita lized,

str.ToLow er

is the string with a ll its letters in lowercase, and

str.Trim

is the string with all spaces removed from the front and back of th e string. Fo r instance,

"Visual" . Length is 6. "Visual" . ToUppe r is VISUAL.


"123 Hike".Le ngth ~ 8. "123 Hike".ToL ower ~ 123 h ike.
"a" & " bed ".Trim & "efg" ~ abcdefg.

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

of the first occ urrence


is - 1 if str2 is not a subst ring of str; otherwi se it is the beginni ng position
of str 2 in str. So me exampl es using these two method s are as fo llows:

"fanati c".Sub string( O, 3) is "fan" . "fanati c".Ind exOf(" ati") is 3.


"fanat ic".Su bstring (4, 2) is "ti". "fanati c".Inde xOf("a ") is 1.
"fanat ic" . Substri ng(4) is "tic". "fanati c".Inde xOf("n t") is -1.

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 .

ers of str 1 to the


Note: In Exampl e 5, c is in the third pos ition of str 1, and there are three charact
charact e r in position n. Thi fact is
left of c. In genera l, there are n charact ers to the left of the
used in Exampl e 6.

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

n = fullN ame. Inde xOf( " " )


first Nam e = fullN ame .Sub strin g(O,
n)
lastN ame = fullN ame . Subs tring (n
+ 1)
m = lastN ame. Leng th
lstR esul ts.It ems .Cle ar()
lstR esul ts.It ems .Add ( "Fir st name
: " & firstN ame)
lstR esul ts.It ems .Add ( "You r last
name has " & m & " lett ers. " )
End Sub

[Run , type "Joh n Doe" into the tex t box, and


then click on the butto n.]

D:} 3-2-fi l = I @) 1--ES~


Name ~irs! and last only): John Doe

IFirst name : John


n alyze Name
L.Your last name has 31etters .
l

The Empty String


The strin g "" , whic h cont a ins no character
s, is ca lled the empt y strin g or the zero- lengt
strin g. It is diffe rent fro m" ",th e strin g cons h
ist ing of a single space.
The state ment lstB ox . Item s .Add ( "") inse
rts a blank line into the list box. The cont ents
of a tex t box can be clea red with e ither the state
ment
txtB ox . Clea r()

o r the state ment


txtB ox.T ext = ""

Initial Value of a String


Whe n a strin g va ri able is decla red with a Dim
state ment , it has the keyw ord N o thing a its
defau lt va lue. To spec ify a d iffere nt ini tial va
lue , fo llow the decla rat io n state ment wit h an
sign fo llowe d by the initia l va lue. Fo r in ranee equ a l
, the state ment
Dim pres As Stri ng = "Ada ms"
decla res the varia b le p1·es to be of type S tring
and ass igns it the initia l va lue "Ada ms".
An error occu rs when eve r an attem pt is made
to access a prop erty or meth od for a str ing
va riable havi ng the va lue N othin g o r to displ
ay it in a list box. Therefore, unless a tring
able is guara nteed to be ass igned a va lue befo va ri-
re be ing used, you should initia lize it-e ven
just as ign the empt y strin g to it. if you

Widening and Narrowing


T h e ass ignm ent of a va lue o r va riable of type
Do ub le to a va riable of type Intege r is calle
narro wing beca use the poss ible va lu es of an d
Intege r varia ble are a subse t of the poss ible va Video Note
of a Doubl va riable. Fo r the sa me rea o n , ass lues
ignin g in the rever e direc tion is calle d wide W ide n ing
Op t io n S tric t req ui res the use of a conv e rsio ning . a nd
n fun ct io n when narro wing, but allows wid enin
with o ut a con ve rsion func t io n . Spec ifically, g narrowing,
a wid enin g state ment of the fo rm scope
dblV ar = intV ar
76 • Cha pter 3 Va riabl es, Input, and Output

t of the form
is va lid . However, a narr owin g tate men

intV ar = dblV ar

is not valid . It must be replaced with

in tVar = Cin t(db lVa r)


valu e of
g with Inte ger var iables. Fo r insta nce, the
Gre at ca re must be take n whe n com p utin re cann ot be
pone ntia tion has type Doubl e and th erefo
an express ion invo lving divis ion or ex a who le num ber.
expl icit conv ers ion even if the valu e is
ass igned to an Intege r variab le with out ts inva lid.
of the follow ing two ass ignm ent state men
Fo r insta nce, Opt ion Stric t mak es each

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

inte rnal docu men tatio n . The fi rst


Example 7 The follo wing rewrite of Examp le 6 uses of the va riab le,
the com men t in line 5 gives the mea ning
com men t desc ribes the entire prog ram, w it.
ose of the thre e lines that follo
and the fina l com me nt desc ribes the purp
... ) Han dles btnA naly ze.C lick
Priv ate Sub btnA naly ze_ Clic k( nd nam e
name and the leng th of the seco
'Det erm ine a pers on's firs t
ame As Stri ng
Dim fullN ame , first Nam e, lastN
Dim m As Inte ger ing the two nam es
Dim n As Inte ger 'loc atio n of the spac e sep arat
fullN ame = txtN ame . Tex t
n = fullN ame .Ind exO f( " " )
O, n)
first Nam e = full Nam e.Su bstr ing(
n + 1)
lastN ame = full Nam e.Su bstr ing(
m = lastN ame .Len gth
tion in a list box
'Dis play the des ired info rma
lstR esu lts . Item s.Cl ear( )
nam e: " & first Nam e)
lstR esu lts.I tem s.A dd( "Fi rst )
name has " & m & " lett ers ."
lstR esu lts.I tem s.A dd( "You r last
End Sub
3.2 Strin gs • 77

Som e of the bene fits of documen tatio n


are as follo ws:
1. Oth er peop le can easil y unde rsta nd the
program.
2. You can unde rstan d the program whe
n you read it later.
3. Lon g programs are eas ier to read beca
use the pu rposes of indiv idua l piec es can
min ed at a glan ce. be dete r-

Goo d prog ram min g prac tice dicta tes that


programmers docu men t the ir code at the
time that they are writ ing it. In fact, man sa me
y softw are com pani es requ ire a ce rtain
men tatio n before they release a version, leve l of docu-
and som e judge a prog ramm er's perfo rma
we ll thei r code is docu men ted. nce on how

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

A new -to-V B20 10 feature ca lled impl icit


line cont inua tion allows unde rsco re char
be omi tted from the end of a line that acte rs to
obvi ously has a cont inua tion- for insta
ends with an amp ersa nd, an arith meti c nce, a line that
operator, or a com ma. We use this fea ture
this text book . For exam ple, the line abov thro ugho ut
e wi ll be writ ten
Dim quo tati on As Stri ng = "Goo
d code is its own " &
"be st doc ume ntat ion. "

Line con tinu atio n, with or with out an unde


rscore characte r, ca nno t be used insid e a
quot atio n marks. Whe neve r yo u wan t pair of
to disp lay a literal strin g on two lines of
must first brea k it into two shor ter strin the scre en, yo u
g join ed with an amp ersa nd. Inte lliSe n
depe ndab le in letti ng you know if you have e is extr eme ly
brok en a line improperly.
Line cont inu atio n , with or with out an
unde rsco re char acte r, does not work with
state men ts. The refo re, each line of a com co mme nt
men t state men t must begi n with its own
apos trop he.
Scope of a Variable
Wh en a vari able is decl ared in an even
t proc edur e with a Dim sta teme nt, a port
is set as ide to h old the valu e of the varia ion of memory
ble. As soon as the End Sub state men t
dure is reac hed, the mem o ry loca tion is for the proce-
freed up; that is, the variab le ceases to exis
ab le is said to be local to the proc edur t. The vari -
e or to have local scope. In gene ral,
variab le is the port ion of the program that the scop e of a
can refer to it.
Whe n va riab les of the sam e n ame are decl
ared with Dim state men ts in two diffe rent
procedures, Visua l Basic gives them sepa even t
ra te mem ory loca tion s and trea ts them
variab les. A va lue ass igned to a vari able a two diffe rent
in one proc edur e will not affect the va lue
tically nam ed variab le in the oth er proc of the iden -
edure.
Visual Basic provides a way to mak e a
variab le recognized by every proc edur e
code. Suc h a var iab le is called a clas s-lev in a form's
el vari able and is said to h ave clas s-lev
el scope. The
78 • Cha pter 3 Va riab les, Input, and Out put

een the stat e men ts


riab le ca n be plac ed anyw here betw
Dim state men t for a class- leve l va Dim stat eme nt i not inside an
End Cla ss , pro vide d that the
Pub lic Cla ss fo rmNa me and lic cla ss form Nam e
the Dim state men t just afte r the Pub
eve nt proced ure. Normally, we plac e e Edit or.) Wh en a
the Dec lara tion s sect ion of the Cod
sta tement. (We refer to this region as afte r the pro-
- leve l va riab le has its va lue ch ange d by a procedu re, the valu e p rsist s even
class le with the sa me
even t proc edu re decl ares a loca l va riab
ced ure has finished exec utin g. If an for cod e insid e th e
the nam e refe rs to the loca l va riable
nam e as a class- leve l va riab le, then
proc edur e.
-
el variable to keep t rack of the num
Example 8 The follo wing prog ram uses a class -lev
ber of times a butt on has been click ed.

Pub lic Cla ss frrn Cou nt


'Cla ss-l eve l var iab le
Dim nurn Tim es As Inte ger =
0
k
k( .. . ) Han dles btnP ush Me. Clic
Priv ate Sub btnP ushM e_ Clic
nurnT i mes += 1
" &
txtO utp ut.T ext "The but ton has bee n clic ked
nurn Tim es & " tim es."
End Sub
End Cla ss
imes .]
[Run , and click o n the butt on three t

c~ Class- Level Varia le


l = I [§] j,.. tJ .J

( Push Me

The button has been click ed 'l t imes .

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

can be replaced with any of th e following statements:


strV ar CTyp e(dbl Var, Strin g)
strV ar Conv ert.T oStri ng(d blVa r)
strV ar dblV ar.To Strin g

Some altern ative s to the use of C lnt and CDb l are


dblV ar CTyp e(str Var, Doub le)
intV ar CTyp e(str Var, Integ er)
intV ar CTyp e(dbl Var, Integ er)
intV ar Integ er.Pa rse(s trVa r )
dblV ar Doub le.Pa rse(s trVa r)
dblV ar Conv ert.T oDou ble(s trVar )
intV ar Conv ert.T oint3 2(str Var)
intV ar Conv ert . Toin t32(d blVa r)

These alte rnat ives are comm on to all the Visua l


Studi o languages and there fore are pre-
ferred by advan ced programm ers. We have decid
ed to use CStr, CDb l, and C lnt fo r the
fo llow ing two reaso ns:

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

Practice Problems 3.2

1. Wha t is the va lue of "Com puter".lnd exOf("E")


?
2. Wha t is the d iffe rence in the outpu t prod uced
by the following two tatem ents? Why 1
CStr used in th e first sta teme nt, but not in the secon
d?
txtBo x.Te xt CStr (8 + 8)
txtBo x.Te xt 8 & 8

3. G ive an exam p le of a prohi bited state ment th at


invoke an Auto Co rrection helpe r box
with the headi ng "Opt ion Stric t On disall ows impli
cit conv ersion from 'Strin g' to 'Double'."
Also, give the sugges tion for fixing the error.

In Exerc ises 1 throu gh 28, deter mine the outp ut


displayed in the text box or lis t box by the
lines of code.

1. txtBo x. Text = "Vis ual Basi c"


2. lstBo x. Item s .Add ("He llo")
3. Dim var As Strin g
var = "Ern ie"
lstBo x.Ite ms.A dd(v ar)
4. Dim var As Strin g
var = "Ber t"
txtBo x.Te xt = var
80 • Chap ter 3 Va ri ab les, Input , and O utput

5. txtB ox.T ext = "f" & "lute "

6. lstB ox. Item s .Add ("a" & "cut e")

7. Dim var As Doub le


var = 123
txtB ox.T ext = CStr (var )

8. Dim var As Doub le


var = 3
txtB ox.T ext CStr (var + 5)
"You r age is" & 21 & "."
9. txtB ox.T ext
"Fre d has " & 2 & "chi ldre n."
10. txtB ox.T ext
11. Dim r, bAs Strin g
r "A ROSE"
b II IS II
txtB ox.T ext = r & b & r & b & r
12. Dim s As Strin g, n As Inte ger
s "trom bone s"
n 76
txtB ox.T ext = n & " " & s

13. Dim num As Doub le


txtB ox.T ext = "5"
num = 0.5 + CDb l(txt Box . Text )
txtB ox.T ext = CStr (num )
14. Dim num As Inte ger = 2
txtB ox.T ext CStr (num )
txtB ox.T ext CStr (l + Cint (txtB ox.T ext) )

15. txtB ox.T ext "goo d"


txtB ox.T ext &= "bye "

16. Dim var As Strin g = "eig ht"


var &= 11
h 11
txtB ox.T ext = var

17. Dim var As Strin g "WALLA"


var &= var
txtB ox.T ext var

18. txtB ox. Text


11
IDUr 11

txtB ox.T ext &= txtB ox.T ext

19. lstB ox. Item s .Add ("aB c". ToUp per)


Of(" lll") )
lstB ox.I tems .Add ("W allle ss".I ndex
lstB ox.I tems .Add ("fiv e".L engt h)
"mp h")
lstB ox.It ems. Add (" 55 ".Tri m &
Y".S ubstr ing(5 , 3))
lstB ox .I tems .Add ("UN DER STUD
20. lstB ox . Items.Ad d("8 Ball " . ToLo wer)
f("k "))
lstB ox.I tems .Add ("co lone l".In dexO
lstB ox. Item s .Add ( "23 . 45" . Leng th)
Subs tring (1))
lstB ox. Items .Add ("re volu t i onar y".
pper ". Inde xOf ( "pp" , 5))
lstB ox. Item s .Add ("wh ippe rsna
21. Dim a As Inte ger 4
Dim b As Inte ger 2
Dim c As Strin g = "Mu nicip ality "
3.2 S trings • 81

Dim d As String = " pal"


lstBox .Items .Add( c . Length )
lstBox .Items .Add(c .ToUp per)
lstBox .Items .Add(c . Subst ring(a , b) & c.Sub string
(5 *b))
lstBox . Items . Add(c .Index Of(d))
22. Dim m As Intege r = 4
Dim n As Intege r = 3
Dim s As String = "Micro soft"
Dim t As String = "soft"
lstOut put.Ite ms.Ad d(s.Le ngth)
lstOut put . Items. Add(s. ToLow er)
lstOut put.Ite ms.Ad d(s . Substr ing(m , n - 1))
lstOut put.Ite ms .Add(s .Index Of(t))
23. How many posit ions does a string of eight charac ters have ?
24. What is the highes t n um bered positio n for a string of eight charac
ters?
25. (True or False ) If n is the length of str, then str. substr ing
(n - 1) is the string con ist-
ing of the last charac ter of str.
26. (True or Fa! e) If n is the length of str, then str. Substr
ing (n - 2) is the tring consist-
ing of the las t two charac ters of str.

In Exerci ses 2 7 throug h 32, identif y any errors.


27. Dim phoneN umber As Double
phoneN umber"234-5 67 8"
txtBox .Text = "My phone numbe r is " & phoneN umber
28. Dim quote As String
quote = I came to Casab lanca for the waters .
txtBox .Text = quot e & " : " & "Boga rt"
29. Dim end As String
end= "happ ily ever after. "
txtBox .Text = "They l ive d " & end
30. Dim hiyo As String
hiyo = "Silv er"
txtBox = "Hi-Yo " & hiYo
31. Dim num As Double 1234
txtBox .Text = CStr(n um.Ind exOf(" 2"))
32. Dim num As Intege r = 45
txtBox .Text = CStr(n um . Length )

In Exerci ses 33 throug h 36, write an event proced ure with


the header Privat e sub
btnCom pute_ Click ( ... ) Handle s btnCom pute. Click, and having one line for
each step.
Displa y each result by assigni ng it to the txtOut put.Tex t proper
ty. Lines that display data
should use the given variab le names.
33. The fo llowing steps give the name and birth yea r of a famous
invent or:
(a) Declare all va riables used in steps (b)- (e).
(b) Assign "Thomas" to th e va riable firstName.
(c) Ass ign "Alva" to the variable middleName.
(d) A ss ign "Edi son" to the va riable las tName.
(e) Ass ign 1847 to the va riable yearOjBirth.
(f) Display the inve nto r's fu ll name followed by a comma and
his yea r of birth.
82 • Chapt er 3 Va ri ables, Input, and Output

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

36. The following steps giv e ad vice:


(a) Decla re the variab le used in step (b).
(b) Assig n "Fore" to the va riab le prefi x.
(c) Disp lay the phras e "Fore warne d is Forea rmed."
out the task. Speci fy where in the
In Exerc ises 3 7 and 38, write a line of code to carry
progr am the line of code shoul d be placed .
to all parts of the progr am.
37. Decla re the var iable str as a tring variab le visible
e o nly to the btnTe st_Cl ick event
38. Decla re the variab le str as a tring variab le visibl
proce d ure.
ied. Write a progr am to carry out the
In Exerc ises 39 throu gh 42, the interf ace is specif
stated task.
and thund er, the torm is n/5 miles away.
39. If n is the numb er of secon ds between lightn ing
betwe en lightn ing and thund er and
Write a progra m that reads the nun1b er of seco nds
in Fig. 3.3 .
reports the d istan ce of the sto rm . A sampl e run is shown

l = I @] 1-a -1 a_. Trainin g Heart Ra e l = I @] ~~,~:•J


g T u nderst o rm

Number of seconds between Age : 20


1.25
lightnin g and thunde r:
Resting heart rate : 70

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

mm e nds tha t you ma inta in yo ur tmining


40. The Amer ican College of Spo rts Medi c ine reco
ng heart rate is co mput ed as
hean mte durin g an aerob ic worko ut. You r traini
rest ing h ea rt rate (yo ur pul e
.7 * (220 - a) + .3 * r , where a is your age and r is your
n's age and rest ing hea rt rate and
when you first awake n) . Wr ite a progr am to read a perso
ng hea rt rate.) A samp le run is
disp lay the tra ining h ea rt rate. (Dete rmine your traini
show n in Fig. 3 .4 .
runni ng, and sw immi ng are 200,475,
41. The numb er of calori es burned per hour by cycling,
t for each 3500 calori es burne d.
and 275, respec tively. A perso n loses 1 pound of weigh
3.2 Strin gs • 83

Wri te code to read the num ber of h ours


spen t at each activity and then display
of poun ds work ed off. A sample run is sh the num ber
own in Fig. 3.5.

a_. Triat hlon l= I @) ~~ J r.~ ..J Baseba ll

Number of hours cycling : 2


Team : Yank ees
Number of hours running : 3
Games won : 68
Number of hours swimming : Games lost : 52

Compute W eight Loss Compute Percentage

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-

In Exe rcises 43 thro ugh 48, writ e a prog


ram to carr y out the ta sk. The prog ram
vari ables for each of the quan titie s and shou ld use
disp lay the outc ome in a text box with
Exa mpl e 2. a label as in

43. Req uest a compan y' annu al reve


nu e and expe nses as inpu t, and d i play
inco me (reve nu e minu s the co mpa ny's net
ex penses). (Test the prog ram with the
$410 ,000. ) amo unts $550 ,000 and
44. Req u est a co mpany's ea rnin gs-p
e r- hare for the yea r and the price of one
inpu t, and then di play the share of stoc k as
compan y's price -to-e a rn ings rat io (tha t
the program with the amo unts $5 .25 and is, pric e/ea rnings ). (Tes t
$68. 25. )
45. Calc ulate the amo un t of a wa iter's
tip, give n the amo unt of the bill and the
as input. (Tes t the program with $20 and pe rcen tage tip
15 percen t. )
46. Con vert a perce ntage to a decima
l. For insta nce, if the user ente rs 125%
th en the outp ut sh ould be 1. 25. into a text box,
47. Wri te a prog ram that cont ains a
butt on and a read -onl y text box on th e
box initi ally cont aini ng 100. Each time form , with the text
the butt on i clicked on, the num ber in
box should decrease by 1. the tex t
48. Wri te a prog ram that req ues ts a
(complet e) phon e num ber in a tex t box
the area code in anot her tex t box whe n and then disp lays
a button is cl icked on.
49. W rite a program that req ues ts a se
n tenc e, a word in the se nten ce, and anot
then disp lays the ente nce with the first her word and
word rep laced by the seco nd . For exam
u er respond s by typ ing "Wh at you don ple, if the
't know won 't hurt yo u." into the first tex
know and owe into the seco nd and third t box and
text boxes, then the me age "Wh at you
won 't hu rt you." is disp laye d. don 't owe
50. Wri te a program that requests a lette
r, co nverts it to uppe rcase, and gives its
the sent ence "TH E QU IC K BRO WN FOX first pos ition in
JUM PS OVE R A LAZY DOG ." For exa
if the user re pond s by typ ing b into the mple,
tex t box, then the message "B first occurs
10." is d isp layed. in posi tion
51. The fo rmulas = \l24d gives an estim ate of the spee d in miles
per hour of a car that skid -
ded d feet on dry conc rete whe n the brak
es were appli ed. Wr ite a prog ram that requ
e ts th e
ut
84 • Cha pter 3 Variables, Inpu t, and Outp

ram for a car


estim ated spee d of the car. (Try the prog
dist ance skidded and then disp lays the
that skid s 54 feet.)
t as inpu t and
tive num ber con tain ing a deci ma l poin
52. Wri te a program that requests a posi the num ber of digits
the left of the deci mal poin t and
then displays the num ber of digits to
to the righ t of the dec ima l poin t.
lays the average
to be inpu t one at a time, and then disp
53. Wri te a program that allows scores top text box
) The user should type a score into the
of the scores upo n request. (See Fig. 3.7. s as desired.
s process can be repe ated as many time
and then clic k on the Record butt on. Thi lay the average of
click on the Calculate butt on to disp
At any time the user should be able to -level vari ab les.
Not e: Thi s prog ram requires two class
all the core that were ente red so far.

a~ •ve rage Score


~em : Price :

Enter a score : and Price


Display ~em

Reco rd the Score

( Calculate the verage Score )

verage
score :
5

FIGURE 3.8 Sam ple outp ut of


FIGURE 3.7 Sam ple outp ut of Exer cise 54.
Exer cise 53.
yed in a list box
itu re sales (ite m and pric e) to be d ispla
54. Wri te a program that allo ws furn request. (See
l commiss ion of the sales (6% ) upo n
one at a time, and then shows the tota clic k on
and price into the text boxes and then
Fig. 3.8. ) The use r hould type each item any time the
repe ated as many times a desired. At
the Display butt on. Thi s process can be miss ion of all the sales
button to d isplay the tota l com
user should be ab le to press the Show
requires a class- leve l var iab le.
that we re ente red . Not e: Thi s program
never eith er the
e 2 so that txtS um will be clea red whe
55. Add an even t proced ure to Exa mpl
cha nged .
first num ber or the seco nd num ber is

Solutions to Practice Problems 3.2


distin guish es betw een uppe rcase and
E in the strin g " ompu ter" . lnde xOf
1. - 1. There is no uppe rcase lette r
lowe rcase. ct
teme nt di splays 88. With Optio n Stri
T he first state ment d isplays 16 in the text box, whereas the seco nd sta and txtBo x .Text
2.
be valid if CStr we re missing, since 8
+ 8 is a num ber
in effect, th e fi rst state men t wo uld not
d state ment as if it were
is a strin g. Visua l Basic treats the secon
r(8)
txtB ox.T ext = CSt r(8) & CSt
3. Som e possibilities are

SUGGESTION FOR FIXING


PROHIBITED STATEMENT

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

3.3 Input and Output

Formatting Output with Format Functions


The Forma t functi ons are used to display numbe rs in famili ar
forms. H ere are some exa mples of VideoN ote
l~ow
' r~' umbe rs are conve rted to strings with Forma t functi
ons:
Formatti ng
output
FUNCTION STRING VALUE

Forma tNumb er(123 45 .62 8, 1) 12,34 5.6


Forma tCurre ncy(1 2345. 628, 2) $12,3 45.63
Form atPerc ent(0. 185, 2) 18.50 %

The value of Forma tNum ber(n, r) i the string conta ining


the numbe r n round ed tor decim al
places and displayed with comm as as thousa nds separa tors.
The value of Forma tC urrenc y(n, r )
is the string consisting of a dollar sign followed by the va
lue of Forma tNumb er(n, r). For-
matC urrency uses the accou ntant's con ve ntion of denot ing
negative amoun ts with surrou nding
pa ren theses. The va lue of Forma tPe rcent( n, r) is the string con
isting of the numbe r n displayed
as a percen t and round ed to r decim al places . With all three
functi ons, r can be omitted. If so,
the numb er is round ed to two decim al places. Strings corre
pondi ng to numbe r less than one
in magni tude have a zero to the left of the decimal po int. A
lso, n can be a number, a numer ic
exp ression , or even a string corres pondi ng to a numbe r.

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%

Using a Masked Text Box for Input


Proble ms can arise when the wrong type of data is entered as
input into a text box. For instan ce,
if the user replies to the reques t for an age by entering "twenty-one
" into a tex t box, the progra m
can eas ily crash. Somet imes this type of predica ment can be
avo ided by using a masked text box
for input. (In later chapte rs, we will consid er other ways of insurin
g the integrity of input. )
In the Toolbox, the icon for the MaskedTextB ox control consis
ts of a rectan gle containing the
two charac ters # and _. The most import ant property of a maske
d text box is the Mask property
that can be used to restric t the charac ters entered into the box.
A lso, the Mask property can be used
to how certain characters in the contro l-to give users a visual
cue that they hould be enteri ng a
phone numbe r or a social security numbe r, for example. Some
possible settings for the Mask prop-
rty are hown in Table 3.2. The first four settings can be selecte
d from a list of specified option s.
Th last three settings genera lize to any numbe r of digits, letters
, or ampersands. If the Mask prop-
erty is left blank, then the MaskedTextB ox contro l is nearly identic
al to the TextB ox contro l.

ltt1:J!IfW Some settings for the Mask property.


Setting Effect
000-00-0000 Th e user can enter a social securit y numbe r.
000-0000 Th e user can enter a ph one numbe r {w ithout an area code
(000) 000-0000 ).
The user ca n enter a ph one numbe r (with an area code ).
00/00/0000 The use r ca n enter a dare .
0000000 The use r ca n enter a pos iti ve integer consist ing of up to 7
digits.
LLLLL The user ca n enter a string consist ing of up to 5 letters.
&&&&&&&& The user ca n enter a string co nsistin g of up to 8 charac ters.
86 • Chap ter 3 Varia bles, Input , and O utpu t

e Mas k prope rty has the se tting 000-0 0-


S uppose a form conta ins a masked tex t box whos
-_ _ " will appea r in th mas ked tex t
0000 . Whe n the program is run , the string " _-_
of each of the nine und ersco re charac -
box. The use r will be allowed to type a digit in place
rac ters ca n be typed anywhe re e lse in the
te rs. The h yphe ns cann ot be altered, and no cha
mas ked tex t box.
tting for a Mask pro perty are replaced by
At run time, the charac ters 0, L, and & in the se
digits, letters, and cha ra cters, respe ctive ly.
unde rsco re chara cters that are place ho lders for
are dropp ed.) Whe n the characters "-"," (",
(Spaces are also allowed. Howeve r, trailing spaces
they appea r as themse lves in the mas ked tex t
")", or "/" appea r in a settin g for a Mask prope rty,
mask se ttings , but th ese se ven will suffice for
box and cann ot be altered . There are so me other
our purposes.
ign time. It looks like an ordin ary text
Figur e 3.9( a) shows a masked tex t box durin g des
t box is used to se t the Mask prope rty rathe r
box. Howe ver, the Tasks butto n for the masked tex
the result of click ing on the Task butto n.
than the Mult iline prope rty. Figur e 3.9(b ) shows
Mask dialog box shown in Figur e 3.10.
Then, click ing on "Set Mask .. . " brings up the Input
box that is invoked when you click on the
(This input dialog box is the sa me input dialog

9L_ == ==

(a) (b)

FIGURE 3.9 The Mask ed TextB ox contr ol.

l 'Y 1- .n. J
Inpu Mask

or select Custo m t o defin e a cus.tom ma sk.


Select a predefin ed mask description from t he list below
- --
IMask Description Data Form at Valid ating Type
12345 Int32
Numeric (5-digits)
(574) 555-0123 (non e)
Phone numb er
(none)
Phone numb er no area co .. . 555 -0123
12 1/ 2003 Date Tim e
Short date
12!11 / 200311:20 Date Tim e
Short date and t ime (US)
000 -00-1234 (non e)
Soc ial security numb er
23:20 Date Tim e
Time (Europ ean/ Military)
11:20 DateTime
Time (US)
98052-6399 (non e)
Zip Cod e
(non e)
<Custom >
- --
[{] Use Val idat ing Type
Mask:

Preview:

[ OK l[ Cance l )

of a mask ed text box.


FIGURE 3.10 Input dialog box used to set the Mask prope rty
3.3 Input and Outp ut
• 87

ellip ses in the Mask prop erty's Setti ngs box.)


You can use this inpu t dialo g box to selec t a com-
monl y used valu e fo r the Mask property, or creat
e you r own custornize d mask in th e Mask text
box. To prod uce the settings 00/00/0000 and
000-00-0000, click on "Sho rt date" and "Soc
secu rity numb er", respectively. We use the prefi ial
x mtb for the n ames of mas ked text boxes.

Dates as Input and Output


So far, all inpu t and outp ut has been eithe r
num be rs o r trings. H owever, app lica tions some
times requi re dates as inpu t and outp ut. Visua -
l Basic has a Date data type and a Date litera
A var iab le of type Date is decla red with a state l.
men t of the fo rm
Dim varN ame As Date

Just as string li terals are wri tten surro unde d


by q uotat ion mark s, date litera ls are wr itten
roun d ed by num ber signs. For insta nce, the state sur-
ment
Dim dayO finde pend ence As Date = #7/4 /177 6#
decla res a date varia b le and ass igns a va lu e to
it.
The func tion COa te conv erts a strin g to a date.
For insta nce, the state ment
Dim d As Date = CDa te(tx tBox . Text )

ass igns the cont ents of a text box to a va riab


le of type Date.
Oate s can be form atted with the Form atOa teTim
e funct ion. If dateVar is a varia ble of type
Date , then the va lue of

Form atDa teTim e(da teVa r, Date Form at.Lo


ngDa te)
is a strin g cons isting of the date spec ified by
dateVar with the day of the week and the mon th
pelled o ut. For insta nce, the two lines of code

Dim dayO finde pend ence As Date = #7/4 /177


6#
txtB ox.T ext = Form atDa teTim e(da yOfi ndep
ende nce, Date Form at .Lon gDat e)
display Thursday, July 04, 1776 in the text box.
Note : lf Date Form at . Long Date is replaced with
Date Form at. Shor tDat e, 7/4/1776 will be displ
ayed in the text box.
Ther e are many func tions invo lving dates. Two
very usefu l ones are Toda y and OateOiff.
The va lue of

Toda y

is the curre nt date as deter mine d by the co mput


er syste m's clock. The va lue of
Date Diff (Dat einte rva1 .Day , d1 , d2)

is the num ber of days betw een the two dates.


AddYears is a useful meth od for work ing with
dates . If d is a va riab le of type Date, and n is
an integer, then the value of

d.Ad dYea rs(n)

is the value of d adva n ced by n years. Two simil


ar meth ods are AddO ays and AddM onth s.
88 • Chap ter 3 Variab les, Inpu t, and O utput

perta ining to a date inpu t by the


Example 1 The fo llow ing prog ram gives info rmat ion t Mask
be set by click ing on Shor t date in the Inpu
user. The mask for the masked text box can
dia log box.
OBJECT PROPERTY SETTING

c~ Birth Data GJ I @) I@J frmA ge Tex t Birth Data


lblDayOfBirth Text Date of birth:
Date of birth: _ / _ / _ mtbD ayOfB irth Mask 00/00/0000
btnC omp ute Text Com pute Data
Compute Data lb lFuii Date Tex t Full birth date:
txtFu ii Date Read On ly True
Full birth date : lbiToday Tex t Tocla y's date:
txtToday Read Only True
Today's date: lblAge ln Days Text Age in days:
txtA gelnDays ReaciOn ly True
f!v;je in days :

. . . ) Han dles btnC omp ute.C l ick


Priv ate Sub btnC omp ute_ Clic k(
OfB irth. Text )
Dim d As Date = CDa te (mtb Day
me(d , Date Form at . Long Date )
txtF ul l Date . Text = Form atDa teTi
e(To da y , Date Form at . Long Date )
txtT oday . Text = Form atDa teTim d, Toda y) , 0)
ber(D ateD if f (Dat eint erva l .Day ,
txtA gein Day s.Te xt = Fo rmat Num
End Sub
ing. ]
butto n. One poss ible outc ome is the fo llow
[Run , ente r your birthday, and click on the

c Bi rth Data
l= I[§J I. --"'2. .I

Date of birth : 04/ 06/ 1992

Compute Data

Full birth date : Monday, Apnl06. 1992

Today's date : Fnday , September 24. 2010

f!v;je in days : 6,745

Getting Input from an Input Dialog Box


t, whe re the type of info rm at io n requ ested
is speci-
Norm a lly, a text box is used to obta in inpu t and woul d
etimes, we wan t just one piece of inpu
fied in a labe l ad jace nt to the text box. Som so lved
the fo rm perm anen tly. T he prob lem can be
rathe r not h ave a text box and label stay on
t of the form
with an inpu t d ia log box. Whe n a state men

= Inpu tBox (pro mpt, title )


st r i n gVar
sc reen .
the one show n in Fig. 3.11 pops up on the
is exec u ted, an inpu t dia log box simi lar to presses
box at the botto m of the d ialog box and
Afte r the use r types a respo n e into the text title argu men t is
igned to the strin g varia ble. The
Ente r (o r click O K) , th e re pons e is ass t i a strin g
a rs in the T itle bar. T he promfJt argu men
optio nal and prov ides the text that appe
into th e text box.
that te lls the user wha t informati on to type
3.3 l np ut and O utput
• 89

Title ___. Nam e L ~ J


Prompt ___. Enter your full name .
( OK )
[ Cancel
l

FIGURE 3.11 Sample inpu t dial og box.

W hen you type the open ing pare nthes is fo


llow ing the word Inpu tBox, the Cod e Ed ito
plays a line con taini ng the general form of r dis-
the lnputBox state men t. See Fig. 3.1 2. Thi
lnte lliSe nse is ca lled Para mete r Info . Opti featu re of
onal pa rame ters are surro und ed by squa re
A ll the pa rame ters in th e gene ral fo rm of the brac kets.
lnpu tBox sta teme nt are optio nal exce p t for
prom/Jt.

Dim prom pt, titl e, fullN ame , first


Nam e As Stri ng
Dim dayO fBir th As Date
prom pt= "En ter your full nam
e."
titl e = "Nam e"
fullN ame = Inpu tbox <I
Inpu tBox ( Prom pt As Stri ng , [Tit le
As Stri ng = "" ] , [Def aultR espo nse
Stri ng = ""], [XPos As Inte ger = As
- 1] , [YPos As Inte ger = - 1 ] ) As
Stri ng
Displays a promp t in a d ialog box, waits for the
user to input text or cl ick a button , and then
return s a string
Prompt: Required String expression displayed as
the message in the dialog box . The maximum length
Promtn is approximately I024 charac ters, depending of
on the width of the characters used. If PromfJt
consists of more than one line, you can separate
the lines using a cm;iage retum character
(Chr( 13)), a line feed character (Chr( 10)) , or a can·iag
e retum /line feed combination (Chr( 13) J
& Chr( l 0)) between each line.
----
FIGURE 3.12 Para mete r Info featu re
of lntel liSen se.

Example 2 The fo llowing prog ram uses two In putB ox


func tions. Wh enev er an Inpu t-
Box func ti on is enco un tered in a prog ram,
an in put dia log box appe a rs, and exec ut ion
unt il t he user respo nds to the req uest. The stops
func t ion retur ns the va lue ente red into the
d ialog box. inpu t

Priv ate Sub btnD ispl ay_ Clic k(


... ) Han dles btnD ispl a y.C li c k
Dim prom pt, titl e, fullN ame , first
Nam e As Stri ng
Dim date OfB irth As Date
prom pt= "En ter your full nam
e."
titl e = "Nam e"
fullN ame = Inpu tBox (pro mpt, title
)
first Nam e = fullN ame .Sub strin g(O
, fullN ame .Ind exO f( " " ))
prom pt= "En ter your date of birt
h."
titl e = "Bir thda y"
date OfB irth = CDa te (Inp utBo x(pr
omp t, title ))
txtO utpu t.Te xt = first Nam e & ",
you are " &
Date Diff ( Dat eint erva l .Day , date
OfB irth, Toda y) & " days old. "
End Sub
ut
90 • Cha pter 3 Vari ab les, Inpu t, and Outp

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

a.. Nam e and Age


l= l@] i. ~ .I

Display Rrst Name and /Jv;Je J

Emma . you are 67 5 days old.

lue, no mat ter


log box is trea ted as a sing le strin g va
The resp onse typed into an inpu t dia ider ed as part of the
not need ed and, if incl uded, are cons
wha t is type d. (Quotat ion marks are to a num ber with
inpu t dia log box sho uld be con vert ed
strin g.) Num eric data typed into an ulat ion. Just as with
to a num eric variab le or used in a calc
CDb l o r C lnt before bein g ass igned le or an exp res ion. For
a li tera l. It can not be a variab
a text box, the typed data must be
acce ptab le.
insta nce, num , 1/2, and 2 + 3 are not

Using a Message Dialog Box for Output


"Co rrec t" or "Nic e
atte nt ion with a brie f message such as
Som etim e you wan t to grab the user's u er h as read it.
no ciga r." You wan t thi mes age to appe ar on the sc ree n on ly unti l the
try, but show n in Fig. 3.13 .
a message dial og box such as the one
Thi s task is eas ily acco mplish ed with

Title Consolation

Prompt Nice t ry, but no ci ga r.

OK

FIGURE 3.13 Sam ple mess age dialo g box.

W hen a stat eme nt of the form


Mes sage Box .Sho w(p rom pt, titl e)
prompt eli played
strin gs, a message dialog box appe ars with
is executed, where prompt and title are Enter, clicks on the
s on the scre en unti l the user presses
and the Title bar capt ion title , and stay t
clicks OK. For instance, the tate men
Close butt on in the upper-right corn er, or
on" )
but no cig ar." , "Co nso lati
Mes sage Box . Sho w(" Nice try,
and just exec ute
t the va lu e for the argu men t title
prod uces Fig. 3.13. You can omi the rest of the message
Mes sage Box . Show (pro mpt ) . If
you do, the Titl e bar will be blan k and
dialog box wi ll appe ar as before.

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

file. Programs are often mad easie r to unde rstan


d and main tain if such a constant is given a
name. Visua l Ba ic has an objec t, called a name
d cons tant, that serves this purpose. A named
constant is decla red and used in a mann er simil
ar to a va riable. The two main differences are that
in the decla ratio n of a named constant, Dim is
replaced with Const, and the value of the name
constant cann ot be chan ged elsewhere in the d
program . N amed constants ca n be thought of
read-only varia bles. as
A named constant is decla red and ass igned a va
lue with a state men t of the form
Cons t CONS TANT_ NAME As Data Type
= valu e
Th e stand ard co nve nt ion i that the names be
wr itten in uppe rcase lette rs with word s sepa rated
by unde r co re characters. Like a Dim tatement,
a onst state ment ca n be place d in th e Decla-
ratio n secti ons of a program (for class- leve l scop
e) or in a proce dure (for loca l scope ). Named
constant decla rati ons in procedures usually are
placed nea r the begin ning of the proce dure .
orne exa mples of named co nstan t decla ratio ns
are
Cons t INTE REST RATE As Doub le =
0.04
Cons t MINIMUM_ VOTING_ AGE As Inte
ger = 18
Cons t BOOK _ TITL E As Stri ng = "Pro
gram ming with VB20 10"

Exa mples of state ments using th ese named cons


tants are
inte restE arne d = INTEREST RATE * CDb l(txt Amo unt.T
ext)
If (age >= MINIMUM_ VOTING_ AGE) Then
Mess ageB ox.Sh ow(" You are elig ible
to vote .")
End If

Mess ageB ox.Sh ow(B OOK_ TITL E, "Tit


le of Book ")

Alth ough the value of a named co nstan t such


as INTEREST_ RATE will not change durin g
the exec ution of a prog ram, the va lue may need
to be chan ged at a later time. The prog ramm er
ca n ad just to this chan ge by altering just one
line of code instead of sea rchin g through the
entir e prog ram for each occurrence of the o ld
intere t rate.

Sending Output to the Printer (optional)


The follo wing fi ve steps se nd outp ut to the print
er.
1. Doub le-cli ck on the Print Docum ent cont ro
l in the A ll Wind ows Form s or Printing gro up of
the Toolbox. (The cont ro l will appea r with the
defau lt name Print Docum entl in a se parat e
pane ca lled the comp onen t tray, at the botto m
of the Form Des igner.)
2. Do uble- click on Print Documen tl to invo ke
its Print Page even t proce dure. (The code for
print ing tex t will be place d in this even t proce
dure. )
3. Place the state ment

Dim gr As Grap hics = e.Gr aphi cs

in the eve nt proce dure. (Thi s state ment decla


res gr as a graph ics obj ect ca pable of pri nting
both text and graphics. )
4. Ente r a tatement of th e form

g r . Dra wStr i ng(s tr , font , Brus hes. colo r, x, y)

for eac h line of tex t to be print ed. Here str is a


strin g, font spec ifics the font name, size, and
style, color spec ifies the color of the tex t, and x
and y are intege rs givin g the locat ion on th e
t
92 • Cha pter 3 Variables, In put, and O utpu

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.

co lum n table of the top thre e all-


Example 3 The following program prod uces a two- ted.
is chan ged after the table 's head er is prin
time home-ru n hitte rs. N otice that the font
PROPERTY SETTING
OBJECT
a ... Sluggers GJ []D [ID frmH R Tex t S lugge rs
Tex t Prin t Table
btnP rint
Print Table l btnP rev iew
Prin tDoc umen tl
Tex t Prev iew Table

Preview Table l Pri n tPrev iew Dia log l

'num ber of poin ts in an inch


Con st ONE I NCH As Inte ger =
100
HEIGHT As Inte ger = 25 'one -qu arte r of an inch
Con st LINE
) Han dles btn Prin t.Cl ick
Priv ate Sub btnP rint _ Clic k( ...
Prin tDoc ume nt1 . Prin t()
End Sub
3.3 lnput and O utput
• 93

Priva te Sub btnPr eview_ Click ( ... ) Hand


les btnPr eview .Clic k
Print Previ ewDi alog1 .Docu ment = PrintD ocum
ent1
Print Previ ewDi alog1 .Show Dialo g()
End Sub
Priva te Sub PrintD ocum ent1_ Print Page (
. . . ) Hand les Print Docu ment 1.Pri ntPag e
Dim gr As Grap hics = e.Gra phics
Dim x1 As Integ er = ONE_ INCH
•use one inch beyon d left marg in
Dim x2 As Integ er = 3 * ONE_ INCH
'offs et for secon d colum n
Dim y As Integ er = ONE_ INCH
use one inch top marg in
Dim font As New Font ( "Cou rier New" , 10,
FontS tyle .Bold )
gr.Dr awSt ring( "PLAYER" , font, Brush es
.Blue , x1, y)
gr . Draw Strin g( "HR" , font, Brush es .Blue
, x2, y)
font = New Font ( "Cou rier New" , 10, FontS
tyle .Regu lar)
y += LINE_ HEIGHT
'move down one= quart er inch
gr.Dr awSt ring( "Barr y Bonds " , font, Brush
es .Blac k, x1, y)
gr.Dr awSt ring( "762" , font, Brush es .Blac
k, x2, y)
y += LINE HEIGHT
gr.Dr awSt ring( "Hank Aaron " , font, Brush
es .Blac k, x1, y)
gr.Dr awSt ring( "755" , font, Brush es .Blac
k, x2, y)
y += LINE_ HEIGHT
gr.Dr awSt ring( "Babe Ruth" , font, Brush
es .Blac k, x1, y)
gr.Dr awSt ring( "714" , font, Brush es .Blac
k, x2, y)
End Sub

[Run, click on the Preview Table butto n, click the Zoom


down - arrow to the right of the magn i-
fying glass, and se lect 100%. The fo llowin g text appea
rs in t he pre vi ew wind ow.]
PLAYER HR
Ba rry Bo nd s 762
Hank Aaro n 755
Ba b e Ruth 71 4

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 .

1. Is the sta te men t


txtOu tput. Text = Form atNum ber(1 2345. 628,
1)
co rrect , o r sh ould it be writte n as fo llows?
txtOu tput. Text = CStr( Form atNum ber(1 2345.
628, 1))
2. Wha t i th e differe nce in the outco mes of the fo llowin
g two sets of code?
strVa r = Input Box ("How old are you?" ,
"Age" )
numV ar = CDbl (strV ar)
txtOu tput. Text = numV ar

numV ar = CDbl (Inpu tBox( "How old are you?"


, "Age" ))
txtOu tput. Text = numV ar
94 • Chap ter 3 Va riables, Input, and O utput

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)

2. txtOu t put.T ext Form atNu mber (-12. 3456 , 3)

3. txtO utpu t . Text Form atNu mber (l234 , 1)

4. txtO utpu t.Tex t Form atNu mber (l234 5)

5. txtO utpu t . Text Form atNum ber ( O.Ol 2, 1)


-2)' 1)
A

6. txtO utpu t.Tex t Form atNum ber(5 * (10

7. txtO utpu t.Tex t Form a tNum ber (- 2 I 3)


2345 , 1)
8. Dim numV ar As Doub le = Math .Rou nd(l.
r)
txtO utpu t . Text = Form atNum ber(n umVa
9. Dim n umVa r As Doub le = Math . Roun d(l23 45.9)
r, 3)
txtO utpu t . Text = Form atNum ber(n umVa
10. Dim numV ar As Doub le = Math .Rou nd(l2 .5)
r, 0)
txtO utpu t . Text = Form atNum ber(n umVa
11. Dim numV ar As Doub le = Ma th . Roun d(ll.5 )
txtO utpu t . Text Form atNum ber(n umVa r, 0)

12. txtO utpu t.Tex t Form atCu rrenc y(l23 4.5)


13. txtO utpu t . Text Form atCu rrenc y(l23 45 . 67, 0)

14. txtO utpu t.Tex t Form atCu rrenc y(-12 3456 7)

15. txtO utpu t.Tex t Form atCu rrenc y( - 0 . 225)

16. txtO utpu t . Text Form atCu rrenc y(32 * (10 A 2))

17. txtOu t put .Tex t Form atCu rrenc y(4 I 5)

18. txtO utpu t.Tex t Form atPer cent( 0.04 , 0)

19. txtO utpu t.Tex t Form atPer cent( 0.075 )

20. txtO utpu t.Tex t Form atPe rcen t(-.0 5, 3)

21. txtO utpu t.Tex t Form at Pe rcen t(l)

22. txtO utpu t.Tex t Form atPer cent( O.Ol )

23. txtO utpu t.Tex t Form atPer cent( 2 I 3)

24. txtO utpu t.Tex t Form atPer cent( 3 I 4, 1)


6762 2)
25. txtO utpu t.Tex t "Pay to Fran ce " & Form atCu rrenc y(272
atCu rrenc y(24)
26. txtO utpu t . Text "Man ha t tan was purc hase d for " & Form
'Mil lion
27. Dim popU Sover 24 As Doub le= 177.6
'Mil lion
Dim co l legeG rads As Doub le = 45.5
45.51 177.6 = 0.256 1937
geGr ads I popU Sove r24, 1) &
txtO utpu t.Tex t = Form atPer cent( colle
old are colle ge grad uate s."
" of the U.S. popu latio n 25+ year s
0)
28. Dim degr ees As Strin g = Form atNu mber (l711 500,
."
tx t Outp ut . Text degr ees & " degr ees were conf erred

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

31. txtO utpu t.Tex t CStr ( # lOI23 I2010 #)


3.3 Input and O utput • 95

32. Dim d As Date = #6/19 /2011 # 'Fath er ' s Day


txtOu tput . Text = Forma tDateT ime(d , DateF ormat
.Long Date)
33 . Dim d As Date = #11/2 5 / 2010# 'Than ksgiv ing Day
txtOu tput.T ext = Forma tDateT ime(d , DateF
ormat .Long Date)
34. Dim d As Date = # 1/ 1/200 0#
txtOu tput.T ext = CStr( d . AddY ears(1 2))

35. Dim d As Date = #9 / 29/20 11#


txtOu tput.T ext =CStr (d.Ad dDays (3))
36. Dim d As Date = #10/9 /2010 #
txtOu tput.T ext = CStr( d . AddM onths( 4))
37. Dim d As Date = #4 / 5 / 2011#
txtOu tput.T ext = CStr(d .AddY ears(2 ))

38. Dim d As Date = #10/1 /2 010#


txtOu tput . Text CStr(d .AddD ays(32 ))
39. Dim d1 As Date #2/1/2 012# '2012 is a leap y ear
Dim d2 As Date d1.Ad dMon ths(1)
txtOu tput.T ext CStr( DateD iff(Da teinte rval.D ay, dl, d2))
40. Dim d1 As Date #1/1 / 2012# '2012 is a leap year
Dim d2 As Date #1 / 1/201 3#
txtOu tput . Text CStr( DateD iff(Da teinte rval.D ay, d1, d2))
41. Dim bet As Doubl e 'Amou nt bet at roule tte
bet = CDbl( InputB ox("H ow much do you want
to bet?" , "Wa ger") )
txtOu tput.T ext = "You might win" & 36 *bet
& " dolla rs . "
(Assum e that the respon se is 10.)
42. Dim word As Strin g
word = InputB ox ("Word to negat e:", "Nega tives" )
txtOu tput.T ext = "un" & word

(As ume that the respon se is tied. )


43. Dim lastNa me, messa ge, firstN ame As Strin
g
lastNa me = "Jone s"
messa ge = "What is your first name Mr. "
& lastNa me & "?"
firstN ame = InputB ox(me ssage, "Name ")
txtOu tput.T ext = "Hell o " & firstN ame &
" " & lastNa me
(As ume that the respon se is ]ohn. )
44. Dim intRa te, doubl ingTim e As Doubl e 'inter
est rate, time to doubl e
intRa te = CDbl( InputB ox("C urrent inter est
rate? ", "Inte rest" ))
doubl ingTim e = 7 2 I intRa te
lstOu tput.I tems. Add(" At the curre nt inter
est rate, money will" )
lstOu tput.I tems . Add(" doubl e in" & doubl ingTi
me & "yea rs.")
(Assum e that the respon e i 4.)
45. Const SALES TAX RATE As Doubl e 0 . 06
Dim price As Doubl e = 100
Dim cost = (1 + SALES _ TAX_ RATE) * price
txtOu tput . Text = Forma tCurre ncy(c ost)
96 • Chapter 3 Variable , Input, and Output

46. Cons t ESTATE TAX EXEMPTION As Doub le =


10000 00
Cons t TAX RATE = 0.45
Dim value OfEs tate As Doub le = 30000 00
state - ESTATE_ TAX_ EXEMPTION)
Dim tax As Doub le = TAX_ RATE * (valu eOfE
rency (tax) & " in estat e taxes ."
txtOu tput. Text = "You owe" & Form atCur
47. Dim gr As Grap hics = e.Gra phics
FontS tyle . Bold)
Dim fon t As New Font( "Cou rier New", 10,
es.Bl ue, 175, 200)
gr.Dr awSt ring( "Hell o World ", font, Brush
48. Dim gr As Grap hics = e . Grap hics
12, Font Style .Itali c)
Dim font As New Font( "Tim es New Roma n",
ue, 75 , 100)
gr.Dr awSt ring( "Hell o", font, Brush es.Bl
ue, 75 , 125)
gr . Draw Str i ng("W orld" , font, Brush es.Bl

In Exerc ises 49 throu gh 56, identi fy any errors.


49. Cons t n As Integ er = 5
n += 1
txtOu t put.T ext = CStr( n)

50. Cons t n As Strin g = "abc"


n = n.ToU pper
txtOu tput . Text = n

51. Dim num As Doub le


num Input Box( "Pick a numb er from 1 to 10.")
=
txtOu tput. Text = "Your numb er is " & num
52. info = Input Box( )
53. Dim num As Doub le = Form atNum ber(l2 3456)
lstOu tput.I tems. Add( num )
54. txtOu tput. Text = Form atCur rency ($123 4)
Prize for Ficti on")
55. Mess ageBo x("Ol ive Kitte ridge ", "Pul itzer
ce" )
56. Messa geBox . Show (l776 , "Year of Indep enden
prope rty of a mask ed text box used
In Exerc ises 57 throu gh 62, give a settin g for the Mask
to input the stated inform ation.
57. A numb er from 0 to 999.
58. A word of at most ten letters.
59. A Mary land license plate consisting of three
letters fo llowed by three digits. (Example:
BHC3 65)
60. A California license plate consis ting of a digit
fo llowed by three letters and then three digits.
( ExamJJ le: 7BHC 365 )
61. An ISBN number. [Every book is identified by
a te n-cha racte r Intern ationa l Stand ard Book
the last cha racter is either a d igit
Numb er (ISBN ). The first nine characte rs are digits and
or the letter X.] (Exam fJle: 0-32-108599-X)
62. A two- letter state abbrev iation. (ExamfJle: CA)
the task.
In Exerc ises 63 and 64, write a statem ent to carry out
63. Pop up a message dia log box with "Goo d Advic
e" in the title bar and the message "First
solve the problem. Then write the code."
3.3 Input and Output • 97

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:

~:~ _. Tip T Interest rate : . 5

Compute Balance
Enter Data

A 1 5 ~;. tip on ~20. is


l
FIGURE 3.14 Sample output of FIGURE 3.15 Sample output of
Exercise 74. Exercise 75.

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.

Solutions to Practice Problems 3.3


A lthough the second statemen t is nor
1. The first statemen t is co rrect, since FormatN umber evaluates to a string.
incorrect , the use of CStr is red undant.
2. The outcomes are ident ical. In this text, we pri maril y use the second style.

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

specify the data types of the variables, and assign initial


values to the variab les. In this book,
most variable have data types Doub le, Integer, String
, or Date.
5. Valu es are ass ign ed to va riables by assignment statem
ents. The va lues appea ri ng in ass ign -
ment statem ents can be literals, variab les, or expre ssions
. String literals used in ass ignme nt
sta temen ts must be surro unded by quota tion marks.
Date litera ls used in ass ignme nt state-
ments must be surrou nded by numb er signs.
6. Comment statem ents are used to expla in formu las,
state the purposes of variab les, and artic-
ulate the purpo es of various part of a progra m.

7. 0 /Jtion Explicit requir es that all variab les be decla


red with Dim statem ents. Option Strict
requir es the use of conve rsio n functi ons in certai n situat
io ns.
8. The Error List window displays, and helps you find
, errors in the code . The Auto Correction
featur e of lntell iSense suggests correc tions when errors
occur.
9. Line co ntinu ation is used to exten d a Visua l Basic
statem ent over two or more lines.
10. The scope of a variable is the portio n of the progra
m in which the va riable is v isible and ca n
be used . A variable decla red insid e an even t proce dure
is a id to have local scope and is v is-
ible onl y insid e the procedure. A va riable decla red in
the Decla ration s sectio n of a progra m
is a id to have class-level scope and is visib le throu ghout
the entire progra m.
11. Masked text boxes he lp obta in correc t input with
a Mask prope rty that spec ifies the kind of
data that can be typed into the tex t box.

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.

16. The PrintD ocument contro l is used to send outpu


t to the printe r, and the PrintPreviewDialog
control is used to prev iew the outpu t.
17. The fo llowin g functi ons accep t numb ers, string , or
dates as input and return numb ers o r
stringsas o utput.

FUNCTION INPUT OUTPUT


CDbl string or numbe r numbe r
C lnt string or numbe r numbe r
CStr string or numbe r tring
Forma tCurrency num ber string
FormatN um be r numbe r string
Forma tPerce n t numbe r string
FormatDateTime date tring
DateD iff date, date num ber
lnputBox string, tring string
lnt num ber num ber
Math.Round num ber, numbe r number
Math.Sqrt num ber number
100 • Chap ter 3 Vari ab les, In put, and O utput

CHAPTER 3 PROGRAMMING PROJECTS


fy two numb ers and then adds, subtr acts, or
1. Write a progr am that a llows the user to speci
priate butto n. The o utput should give the
multi pl ies them when the use r clicks on the appro
3. 18. Note : If one of the numb ers in an
type of ar ithme tic performed and the res ult. See Fig.
uld be cleared.
input text box is chan ged, t he outpu t text box sho

l= 1-£1 -~J
ll _. Calcu lator l = I @) l,...tJ J a ~ A -1 Auto Repai r
@)

Customer: John Doe


Rrst
number:
GJ Second
number: Hours of labor: 3.5
Display

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

FIGURE 3.19 Possi ble outco me of


FIGURE 3.18 Possi ble outco me of
Progr ammi ng Proj ect 2 .
Programmi ng Proje ct 1.

the rate of $35 per hour for labor. Also, sup-


2. Supp ose automob ile repa ir custo mers are billed at
sales tax. Write a program to display a sim-
pose costs for part and supplies are subj ect to a 5%
hours of labor, and the cost of parts and
plified bill. The custo mer's name , the numb er of
boxes. Whe n a butto n is clicked, the cus-
supplies should be entered into the program via text
in a list box, as show n in Fig. 3.19.
tome r's name and the three costs shou ld be displayed
of money from 0 throu gh 99 ce nts input by
3. Write a progr am to make chan ge for an amou nt
th e numb er of co ins from each deno mina-
the u er. The outpu t of the progr am hould show
tion u ed to make chan ge . See Fig. 3.20.

a,. Chang e l = I @) l1!-t3 J a_. Conve rsion l = I @) I~·"'J

93 Miles : 5 ( Convert to Metric J


Amount of change :

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

Possib le outco me of FIGURE 3.21 Poss ible outco me of


FIGURE 3.20
Progr ammi ng Proj ect 3 . Progr ammi ng Proje ct 4.

Syste m lengt h in miles, yards, feet, and


4. Write a program to con vert a U.S. C usto mary
mete rs, and ce ntime ters. A samp le run is
inche s to a Metri c Syste m lengt h in kilom ete rs,
, feet, and inche s are read from the text
show n in Fig. 3.2 1. After the numb ers of miles, yards
to inches and then div ided by 39.37 to
boxes, the lengt h should be conv erted entir ely
be used to break the total numb er of
obta in the va lue in mete rs. The Int funct ion hould
Program ming Projects
• lOl

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:

total inch es = 63360 * mil es + 36 *yards + 12 *fee t + inches


tota l meters = total inches/ 39 .3 7
kilomet ers = lnt( meters/ 1000 )

5. Write a progra m to print a business trave l ex penses attac hm


ent fo r a n inco me tax
re turn. The prog ram h ould requ es t as input the na me of the orga niza
tio n visited , the
dates a nd locatio n of th e visit, and the ex penses fo r mea ls and enterta
inment , a irplan e
fa re, lodg ing, and tax i fa res . (O nl y 50 % of the ex penses for mea ls and
e nte rta inment
a re ded uctible. ) A poss ible fo rm layo ut and run a re shown in Figs.
3.22 a nd 3.23,
respect ive ly.

a ... Busin ess Trave I Expenses l= i §J i- a


Organization visited : SIGCSE 201

Dat es: March 10-13

Location : Milwaukee . WI
Meals and entertainment : 19 .10

Nrplane fare : 25 .15

Lodging : 675.35

Taxi fares : 45

I Print Business Travel Expenses M achment


I
l Preview Business Travel Expenses M achment
J

FIGURE 3.22 Form with sample data for Program ming Proj ect 5.

Busines Trave l Expenses


Trip to attend meeting of
S IGCSE 20 10
March 10-13 in Milwaukee, WI
Meals and enterta inment: $ 190. 10
A irplane fa re: $250.15
Lodging: $675 .35
Tax i fares: $45.00
Total other than meals and enterta inment: $9 70.50
50% of mea ls and enterta inment: $95.05
T O TAL DEDUCTIBLE EXPEN S ES: $ 1,065.55

FIGURE 3.23 Output for sample run of Program ming Proj ect 5.
De cis ion s

4.1 Relational and Logical Operators 104


• ANSI Values • Relati onal Opera tors • Logica l Opera tors • Boolea
n Data Type
• Two Boolea n-Valued Metho ds • A Boolea n-Valu ed Functi on
4.2 If Blocks 112
• If Block • Nested If Blocks • Elself C lauses • Input Va lidatio
n with If Blocks
4.3 Select Case Blocks 130
• General Form of a Se lect Case Block
4.4 Input via User Selection 143
• Using a List Box for Input • Gro up Box Contr ol • Using Rad
io Button s for Input
• Using Check Boxes for Input • Events Raised by Select ions
Summary 154

Programming Projects 154

103
104 • Chap ter 4 Dec isio ns

4.1 Rela tional and logical Operators


r to
ramm ing constructs decision and loop. In o rde
In C hapt er 1, we d isc ussed the two log ica l prog e of
spec ify a co nditi on t hat deter mines the cours
make a dec ision or cont ro l a loop, yo u need to
act ion.
nal opera to rs (such as < and = )tha t is e ither
A cond ition i an express io n invo lving re latio .
te log ica l opera tors (such as A nd, O r, and Not)
true o r false. Cond iti o ns also may incorpora .
co mpare strin gs with the relati ona l operators
AN I va lu es deter mine th e orde r used to
va lu es True o r False .
Boolea n va riab les and litera ls ca n assum e the

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 .

lfT1:J!IIM A few ANSI values.


66 B 122 z
32 (space) 48 0
33 49 1 90 z 123 {
57 9 97 a 125 }
34 "
65 A 98 b 126
35 #

N ew, Microsoft Sa n erif, and Times New


Most of the best- know n fonts, such as Courier .
ass igns characters to the num bers fro m 0 to 255
Rom an, adhe re to the ANS I stand ard , whic h
s.
Tabl e 4.2 shows a few of th high er ANS I value

lf!1:J!IfM A few higher ANSI values.


177 ± 181 fL 190 3 4
162 ¢.
1
188 /4 247
169 © 178
189 1'2 248 cp
176 ° 179 3

If n is a numb e r be twee n 0 and 255, then

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 )

Fo r insta nce , th e tatem e nt


is the AN I value of the first ch aract er of str.

tx t Bo x. Tex t = Chr (6 5)

state ment
displays the lette r A in the tex t box, and the

l s t Box. I t ems .Add (Asc (" Appl e"))

displ ays the numb er 65 in the li t box.


in strin gs using the high er AN SI ch aract ers.
Conc atena tion can be used with C hr to obta
rms to the ANS I stand ard, the state men t
Fo r insta nce, with one of the fonts t hat confo
4.1 Relat iona l and Log ica l Ope rators
• 105

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

Example 1 Dete rmin e whe ther each of the fo llow


ing cond ition s is true or fa lse.
(a) 1 < = 1
(b) 1 < 1
(c) " ca r" < "cat "
(d) "Do g" < "dog "
(e) Tod ay < Tod ay.A dd Days( 1)

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

g fro m left to righ t.


s are com pared one at a time wo rkin
(c) True. The cha ract ers of the tring
cha ract er decides th e o rd er.
Beca use the first two mat ch , the third
e, the first cha r-
. Bec ause uppe rcas e lette rs prec ede lowe rcase lette rs in the AN S I tabl
(d) True
acte r of "dog ".
acte r of "Dog" precedes the first char
nologically.
(e) Tru e. Tod ay prec edes to morrow chro

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

b h ave va lu es 4 and 3, and th e


Example 2 S upp ose the num e ric vari ables a and
co ndit io ns tru e o r
"h e llo" and "bye ". Are the fo llow ing
str ing va riab les c and d h ave valu es
fa lse?

(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

(2 < n) And ( n < 5)


ns 2 < n and
5 ) is a com bina tion of the two con ditio
The co ndition (2 < n ) A nd ( n <
.
n < 5 with the logica l ope rato r And 2 are co ndit ions,
And , O r, and N ot. lf condl and cond
The thre e ma in logica l ope rato rs are
th en the co ndit ion

con dl And cond 2

. O therwise, it is false. The cond ition


is tru e if both condl and cond 2 are true

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 .

Boolean Data Type


A state ment of the form

txtBo x.Te xt = CStr (con ditio n)

will display eithe r True or False in the text box, depen


ding on the conditi on. Any va riab le or
exp ress ion that evalu ates to eithe r True or False
is said to have a Bool ean data type. The fol-
lowing lines of code d isplay Fa lse in the text box.

Dim x As Integ er = 5
txtBo x.Te xt = CStr ((3 + x) < 7)

A variab le is declared to be of type Boo! an with


a statement of the form
Dim varNa me As Bool ean
108 • Chapter 4 Decisions

in the text box.


The fo llowi ng lines of code wi ll display True

Dim bool Var As Boo lean


Dim x As Inte ger 2
Dim y As Inte ger = 3
bool Var = x < y
txtB ox.T ext = CStr (boo lVar )
w ing
confirmed to be False by exec uting the follo
The answer to part (i) of Example 3 can be
lines of code.

Dim n as Inte ger = 4


Dim answ as Stri ng = "Y" "Y" )))
((n 7) Or (answ
txtB ox.T ext = CStr ( (n = 2) And

Two Boolean-Valued Methods


n
If strVar is a string variable, then the expressio

strV ar.S ubst ring (strV ar . leng th


- 3) = "ing "

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

with the value of strVar2.


is true if and only if the value of strVar ends of
way to test for the end of a string. The va lue
The Ends With meth od provides an alter nate
(2)
strV ar.E ndsW ith(s trVa r2)

with the value of strVar2.


is True if and only if the va lue of strVar ends e
sinc e it is more conc ise and read able. Cod
Con ditio n (2) is preferab le to cond ition (1) e it clear ly
ve code (or se lf~evid e nt code ), sinc
such as co nditi on (2) is ca lled decl arati task but
ress ion ( 1) shows how to acco mpli sh the
declares what you wan t to acco mplish . Exp guid ing
e out wha t is be ing achi eved . One of our
requires some deci pher ing in orde r to figur r poss ible. We prefe r what
arati ve code whe neve
prog ramm ing prin ciples will be to write decl
to how.
is the Start sWith meth od. The va lue of
The coun terpa rt of the Ends With meth od

strV ar.S tarts Wit h(st rVa r2)

s with the va lue of strVar2.


is True if and only if the valu e of strVar begin

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

IsNu mer ic(st rVar )


. For
ber with C lnt or CDb l, and is False otherwise
is True if strVar can be converted to a num 3", or
whe n the valu e of strVar is "2345", "$12
insta nce, IsNu meri c (strV ar) will be True
whe n the valu e of strVar is "five" or "4 - 2".
"5,677,890". The func tion valu e wi ll be False
4.1 Rela tiona l and Logica l Ope rators
• 109

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

Practice Problems 4.1

1. Is the cond ition "He llo " = "He


llo" true or fa lse?
2. Exp lain why (27 > 9) is true, whe reas
("27" > "9") is fa lse.
3. Com plet e Tab le 4.4.

lf!1:J!III Truth values of logical operators.


cond 1 cond 2 cond 1 And cond 2 cond 1 O r cond 2 Not cond 2
True True True
True Fa lse
False True
True
Fa lse False Fa lse

In Exe rcise s 1 thro ugh 6, dete rmin e the


outp ut displayed in the text box.
1. txtB ox.T ext Chr (l04 ) & Chr (l05 )
2. txtB ox.T ext ncn & Chr (35)
3. txtB ox.T ext "The lett er befo re G is
" & Chr (Asc ( "G") - 1)
4. txtB ox.T ext Chr (Asc ( "B") ) 'The ANS I valu
e of B is 66
5. Dim quo te, pers on, qMa rk As Stri
ng
quo te= "We 're all in this
alon e."
pers on = "Lil y Tom lin"
qMa rk = Chr( 34)
txtB ox . Tex t = qMa rk & quo te
& qMa rk & " - " & pers on
6. Dim lett er As Stri ng
lett er = "D"
txtB ox.T ext = lett er & " is
the " & (As c(le tter ) - Asc( "A") + 1) &
"th lett er of the alph abe t."
110 • Cha pter 4 Decisions

. 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

ln Exer cises 41 throu gh 45, write a cond ition equiv


alent to the negat ion of the given cond i-
tion. (For exam ple, a < > b is equiv alent to the
negat ion of a = b.)
41. a > b
42. (a =
b) O r (a = d)
43. (a< b) A nd (c <>d )
44. Not ((a= b) O r (a> b))
45. (a<> '"') A nd (a < b) A nd (a.Le ngth < 5 )
46. Rework Exe rcise 20 by evalu ating the Boolean ex press
ion in a program.
47. Rewo rk Exe rci e 21 by evalu at ing the Bool
an express ion in a program.
48. Rewo rk Exe rcise 22 by evalu at ing the Boole
an ex press ion in a program.
49. Rewo rk Exerc ise 23 by evalu ating the Boole
an expression in a program.
In Exerc ises 50 throu gh 59, deter mine whet her
True or False is displayed in the text box.
50. Dim str As Strin g = "targ et"
txtBo x.Te xt = CStr (str. Star tsWi th("t
") And str.E ndsW ith(" t"))
51 . Dim str As Strin g = •tick et"
txtBo x.Te xt = CStr (str. Start sWit h("T
") Or str.E ndsW ith(" T"))
52. Dim str1 As Strin g = "targ et"
Dim str2 As Strin g = "get"
txtBo x.Te xt = CStr (str1 .End sWit h(str
2))
53. Dim str1 As Strin g = "Tea pot"
Dim str2 As Strin g = "Tea"
txtBo x.Te xt = CStr (str1 .Star tsWi th(st
r2))
54. Dim str As Strin g = "$1,2 34.56 "
txtBo x.Te xt = CStr (IsN umer ic(st r))
55. Dim str As Strin g= "10,0 00,00 0 "
txtBo x.Te xt = CStr (IsN umer ic(st r))
56. Dim str As Strin g = "10 milli on"
txtBo x.Te xt = CStr (IsN umer ic(st r))
57. Dim str As Strin g = "2 + 3"
txtBo x.Te xt = CStr (IsN umer ic(st r))
58. Dim str As Strin g = "10E+ 06"
txtBo x.Te xt = CStr (IsN umer ic(st r))
59. Dim str As Strin g = "SE-1 2"
txtBo x.Te xt = CStr (IsN umer ic(st r))

Solutions to Practice Problems 4.1

1. Fa lse. T he first string has ix cha racte rs, where


as the seco nd has five . Two strings must be I 00%
ca ll ed equal. identi ca l w be
2. When 27 and 9 arc compared a strings, th e ir
first charac te rs, 2 and 9, dete rmin e th e ir o rde r. S
9 in the ANS I tab le, "27" < "9". ince 2 precedes
3. co ndl co nd2 cond 1 And cond2 cond 1 Or cond2 Not cond2
True True True True False
True False Fa l c True True
Fa lse True Fa lse True Fa lse
Fa lse Fa lse Fa lse False True
112 • Cha pter 4 Dec isions

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

If cond ition is true Then


Execute
Exec ute acti on 1 Execute
action 1
Else action 2
Exec ute acti on 2
End If

k.
FIGURE 4.1 Pseu doco de and flow char t for an If bloc

r of two num ber inpu t by the user.


Example 1 The fo llowing prog ram find s the large
The cond ition is
num l > num2
the cond i-
act ion cons ists of a sing le ass ignm ent state men t. Wit h the inpu ts 3 and 7,
and each
take n.
tion is false, and so the seco nd actio n is
PROPERTY SETTING
OBJECT
11:;; M axim um GJ I 8 I~ fnnM axim um Tex t Max imum
lblFirstNum Tex t Fir t num ber:
Rrnt number: txtFirstN um
lblSe cond Num Text Seco nd num ber:
Seco nd number: txtSe cond Num
btnF indL arger Text Find Larger Num ber
Rnd Larger Number Read Only True
tx tRe ult
4.2 If Blocks
• 113

Priv ate Sub btnF indL arge r_ Clic k(


... ) Hand les btnF indL arge r.Cli ck
Dim numl , num2 , large rNum As Doub
le
numl = CDbl (txtF irstN um.T ext)
num2 = CDbl (txtS ec ondN um .Tex t)
If numl > num2 Then
large rNum numl
Else
large rNum = num2
End If
txtR esul t . Text = "The larg er numb
er is " & large rNum & II II
End Sub

[Run , type 3 and 7 into the text boxes, and click


on the butto n.]

II ~
Maximum l = I @l !;. ~- .I

First numb er: 3

Second numb er: 7

l Find Larger Numb er


J
The larger number is 7.

Example 2 The If block in the follo wing program has a logic


a l opera tor in its co nd it ion .

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

Priv ate Sub btnE valu ate_ Clic k( ...


) Hand les btnE valu ate.C lick
'Eva luate answ er
Dim answ er As Doub le
answ er= CDbl (txtA nswe r.Te xt)
If (answ er >= 0.5) And (answ er <=
1) Then
txtS olut ion . Text "Goo d, n
Else
txtS olut ion. Tex t = "No, "
End If
txtS olut ion. Tex t &= "it hold s abou
t 3/4 of a gall on."
End Sub
114 • C hapt er 4 Dec isio ns

on the button. ]
[Run , type 10 into the tex t box, and cl ick

How marw gallons does a


t en-gallon hat hold?

Evalu ate Answer

No. it holds about ll of a gallon .

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.

ce to the user befo re prese n ting a


Example 3 T he fo llow ing program offe rs ass istan
quo tatio n .

' OBJECT PROPERTY SETTING

frmQu otation Tex t Q uota tion


~~ ~ Quot ation
lblQ uest ion Tex t Do yo u know what the
s is fY/ N)? _ game of skitt les is (Y(N ) 7
Do you know what the game of skittle
mt bAn swer Mask L
Displ03'f Quotation Tex t Disp lay Q uota t io n
btnD isplay
txtQ uo te Read O n ly True

( ... ) Han dles btnD isp l a y .Cli ck


Priv ate Sub btnD i s play_ Clic k
Dim mes sage As Stri ng den " &
form of bow ling in whic h a woo
mes s age = "Sk ittle s is an old nge d in a squ are. "
nine pins arra
"dis k is used to knoc k down
If mtb Ans wer. Tex t . ToU pper =
"N" Then
Mes sage Box .Sho w(m essa ge , "De fini tion " )
End If
ttle s." &
txtQ uote . Tex t "Lif e ain ' t all bee r and ski
" - Du Mau rier (189 4)"
End Sub
, and click on the button.]
[Run, type "N " into the masked text box

g-j Qu otati o n l= @)

is (Y/ N)? N
Do you know what the game of skittles

Display Quot ation


4.2 If Blocks
• 115

De mit ion

Skittl es is an old form of bow ling in w hich


a w ooden di sk is used to kno ck dow n
nin e pin s arran ged in a sq uare.

OK

[Press OK.]

D;i Quo atio n

Do you know what the game of skittles is (Y


/ N)? N

Display Quotation

Life ain all beer and skittles . - Du Maurier (1


&94)

[Rer un the program, type "Y" into the mask


ed text box, click on the butto n, and ob~erve
desc ripti on of the ga me is skipp ed.] that the

Note: Logic erro rs are the most difficu lt error


s to find. A com mo n type of logic error
a mi sia n of the ToU pper meth od in Exam is the
p le 3 .
Nested If Blocks
An actio n part of an If bloc k can cons ist
of anot her If bloc k. In th is situa t io n the If
sa id to be neste d. Examp les 4 and 5 emp loy blocks are
nested If bloc ks.

Example 4 The colo r of the beac on light atop Boston's


old John H anco ck bui lding fore-
casts the weat her acco rding to the follo wing
rh yme:
Stea dy blue, clea r view.
Flash ing blue, clouds due.
Stea dy red, ra in ah ead.
Flas hing red, snow inste ad.
The following program requests a colo r (Blue
or Red) and a mode (Steady or Flash ing) ks
d isplays the weat her forecast. Both actio ns inpu t and
assoc iated with th e main If block cons ist of
If blocks.
OBJECT PROPERTY
D_. W eathe r Beacon G?JI @] I[][ ] frmW eathe r Text
SETTING
Wea ther Beaqon
Color of the light (8 or R): lblCo lo r Tex t Co lor of the
-
Mode (5 or F):
light (B orR) :
- mtbC olor Mask L
lb lMod e Text Mod e (S or F ~ :
Interpret Beacon
mtbM ode Mask L
btnln terpr et Text Interpret Beacon
txtFo recas t Read On ly True
11 6 • Cha pter 4 Dec isio ns

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

Dj ' ea her Be acon


l = I @) I.,.....,.-""'~.,....,..!.I
Color of the light :sor R}: R

Mode (S or 5

( Interpret Beacon I
RAIN .HEA.D

costs and reve nue for a compan y and


Example 5 The follo win g prog ram requests the e, it disp lays the
cost s and reve nue are equa l; othe rwis
displays the message "Brea k even" if the
is ano ther If bloc k.
profit or loss. The acti on follo win g Else
PROPERTY SETTING
OBJECT
ll Prof itllo ss GJI G ICID frmS tatus Tex t Profit/Loss
lbiC osts Tex t Costs:
Costs : txtC osts
lblR ev Text Rev enue:
Reve nue :
txtR ev
btnS how Tex t Sho w Fina ncia l Stat us
[ Show Rnancial Status ]
txtR esult Read O nly True

... ) Han dles btnS how .Cli ck


Priv ate Sub btnS how_ Clic k(
loss As Dou ble
Dim cos ts, reve nue , pro fit,
cos ts = CDb l (txt Cos ts.T ext)
4.2 lf Blocks • 117

revenu e = CDbl (txtRe v . Text)


If costs = revenu e Then
txtRe sult . Text = "Break even"
Else
If costs < revenu e Then
profit = revenu e - costs
txtRe sult . Text = "Prof it is 11 & Forma tCurre ncy(pr
o fit) & "·"
Else
loss = costs - revenu e
txtRe sult.T ext = "Loss is " & Forma tCurre ncy(lo
ss) & II II
End If
End If
End Sub

[Run, type 9500 and 8000 in to the text boxes, and click on the button
.]

Costs : 95

Revenue : 8

Sho•.-• Rnancial Status

Loss is .;: 1,5

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

If (numl > num2 ) Then


" & numl
txtRe sult .Text = "The large r numb er is
Else if (num2 > numl) Then
txtRe sult.T ex t "The large r numb er is " & num2
Else
txtRe s ul t.Te x t "The two numb ers are equa l."
End If
End Sub

[Run, type 7 into both tex t boxes, and press the butto n.]

Rrst numbe r: 7

Second numbe r: 7

Rnd Larger Numbe r

The t•; •o numbe rs are equal.

that are not determ ined by a simple


The If block in Exa mple 7 allows us to calcu late va lues
formul a.

e Socia l Secu rity


Example 7 The Socia l Security or FI A tax has two components-th
800 of ea rn ings for the year, and the
benefi ts tax, which in 2009 is 6.2% on th first $106,
ing progra m calcul ates an employee's
Medicare tax, wh ich is 1.45 % of earn ings. T he follow
FICA tax fo r the curren t pay period .
OBJECT PROPERTY SETTING

a_. F1CA Ta e:s. [£](][] ~ frmFIC A Tex t FICA Taxes


lbiToD ate A uto ize Fa lse
Total eamings for this year Tex t Tota l ea rnin gs fo r
prior to the current pay period : this yea r prior to th
c urre n t pay pe riod :
Earnings for the
current pay period : txtToD a te
lblC urre n t Text Earn ings fo r t he
Calcula te FICA Taxes c urre n t pay period :
txtC urren t
FICA taxes for the btnCa lcula te Tex t Calcu late FI CA
current pay period : Taxes
lb!Tax Text FICA taxes fo r the
c urren t pay period :
txtTax ReadO n ly True

les btnC alcul ate . Click


Priva te Sub btnC alcul ate Cl ick( . .. ) Hand
bene f1t- tax and Mec~c re a""
'Calc ulate socia l secu rity
'for a singl e pay perio d in 2009
Cons t WAGE BAS E As Doub le = 10680 0 'Ther e is no socia l secu rity bene fits
tax on incom e above this level .
Dim ytdE arnin gs , curEa r nings As Doub le
4.2 If Blocks • 119

Dim social Securi tyBen Tax, medica reTax, ficaTa xes


As Double
ytdEa rnings = CDbl (txtTo Date.T ext)
curEa rnings = CDbl (txtCu rrent . Text)
If (ytdEa rnings + curEar nings ) <= WAGE BASE Then
social Securi tyBen Tax = 0 . 062 * curEar ni ngs
Elseif ytdEa rnings < WAGE_ BASE Then
socia l Secur ity BenTax = 0.062 * (WAGE_ BASE y t dEarni ngs )
End If
medica reTax = 0.0145 * curEar nings
ficaTa xes = social Securi tyBen Tax + medica reTax
txtTax . Text = Forma tCurre ncy (ficaT axes)
End Sub

[Run , type 12345 .67 and 543.2 1 into the top two text boxes and click
on the button.]

a .. R:CA. 1 axes

Total eamings for this year


prior to the current pay period : 12 . 5.67

Eaminos for the 5 .21


current pay period :

FICA taxes for the


current pay period :

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

[Run, e n te r a grade po int a ve rage be twee n 2 and 4, a nd click o n th e butto n .]

a ... Gradua ion Ho no r

GPA{ 2through 4): 18

[ Determine Honors J

You graduat ed magna cum laude.

Input Validation with If Blocks


r in to a tex t box, a nd the n the progra m
S uppose a progra m ca lls fo r th e use r to e nte r a numbe
tex t box e mpty o r e nte rs an inapp ro-
uses the numbe r in a cmnpu ta tio n . If the user leaves the
lued fun c t io n IsNum e ric ca n be used to
p ria te num be r, the progra m will c rash . The Boo lean -va
preven t this fro m h appen ing.
fo rm
Note: Wh n boolVa l is a Boo lea n va lu e, a sta te me nt o f the

If boolV al = True Then

can be sh o rte n ed to

If boolV al Then

S imila rly, a statem e nt of th e fo rm

If boolV al = False Then

ca n be sh o rte n ed to

If Not boolV al Then

ric to gua rd aga inst


Example 9 The fo llow ing progra m uses the funct io n lsNum e
improp e r input.
OBJECT PROPERTY SETTING
ll,. Addition ~I ~ !Em frmAd Jition Tex t Additi on
lblFirst Num Text First numbe r:
Rrst number :
txtFirstN um
lblSeco ndNum Tex t Second numbe r:
Second number :
txtSeco nd N um
Add Numbers btnAd d Tex t Add N um be rs
lblSum Tex t Sum:
txtSum ReadO n ly True
Sum :

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

[Ru n , leave the first text box empt y, en ter "two"


into the secon d text box, and click o n the
butto n .]

~~ ~ Addit ion = @) ~ I
Rrst number: J
Second numbe r: two l··· ~ ,j

[ Jl.dd Numbe rs ) Each text box is emp or has an improp er entry.


Sum :

' lj
( OK ]

If blocks also can be used to guara ntee that a n


umbe r input by the user is in the prope r
range. Fo r insta nce, when the user is as ked to input
an exa m grade, a state men t such as
If (grad e >= 0) And (grad e <= 100)
Then

can be used to guara ntee that the numb er in put


is betwee n 0 and 100.

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.

If c ondl Then If cond l And cond2 Then


If c ond2 Then actio n
a c tion End If
End If
End If

FIGURE 4.2 A con fusing If bloc k and an impro veme nt.

2. In Appe ndix D, the sec tion "S teppi ng th rough


Programs Co nta ining Dec isio n Struc tures:
C h apter 4" uses the Visua l Bas ic debu gg ing too ls
to trace the fl ow th rough an If block .
122 • Chap ter 4 Decisions

Practice Problems 4.2


root is to
ber into txtN umb er for whic h the sq uare
1. Supp ose the user is aske d to inpu t a num mes-
of code that fo llow will disp lay e ither the
be take n. Fill in the If bloc k so that the lines
are root of the num ber.
sage "Num ber can't be nega tiv ."or the squ
Han dles btnS qrt. Clic k
Priv ate Sub btnS qrt Clic k( ... )
'Che ck reas onab lene ss of data
Dim num As Dou ble
num = CDb l(txt Num ber.T ext)
If

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

4. Private sub btnDisplay_ Click( ... ) Handles btnDisplay.C lick


Dim change As Double = 356 'Amount of change in cents
If change >= 100 Then
txtOutput.Te xt = "Your change contains " &
Int(change I 100) & " dollars."
Else
txtOutput.Te xt "Your change contains no dollars."
End If
End Sub
5. Private Sub btnDisplay_ Click( ... ) Handles btnDisplay.C lick
Dim a as Double 2
Dim b As Double 3
Dim c As Double 5
If a * b < c Then
b 7
Else
b c * a
End If
txtOutput.Te xt CStr(b)
End Sub
6. Private Sub btnDisplay_ Click( .. . ) Handles btnDisplay.C lick
'Cost of phone call from New York to London
Dim length, cost As Double
'Request the length of a phone call
length= CDbl(InputBo x("Duration of the call in minutes?"))
'Calculate cost of phone call
If length < 1 Then
cost = 0.46
Else
cost 0.46 + (length - 1) * 0.36
End If
'Display the cost of the call
txtBox.Text = "Cos t of call: " & FormatCurren cy(cost)
End Sub
(Assu me the response is 31.)
7. Private Sub btnDisplay_ Click( .. . ) Handles btnDisplay.C lick
Dim letter As String
letter InputBox("En ter A, B, or C.")
letter letter.ToUpp er
If letter = "A" Then
txtOutput.Te xt = "A, my name is Alice."
Elseif letter = "B" Then
txtOutput.Te xt = "To be, or not to be."
Elseif letter = "C" Then
txtOutput.Te xt = "Oh, say, can you see."
Else
txtOutput.Te xt "Not a valid letter."
End If
End Sub
(Assume the response is B.)
124 • Chapter 4 Dec isions

8. Private Sub btnDispl ay_ Click( . .. ) Handles btnDispl ay.Click


Dim vowel As Boo l ean = False
Dim l tr As String
l t r = InputBox ("Enter a letter.")
ltr = ltr.ToUp per
If ( ltr "A") Or (ltr "E") Or (ltr "I") Or
(ltr "0") Or ( l tr "U") Then
vowel True
End I f
If vowel Then
txtOutpu t . Text l tr & " is a vowel . "
Else
txtOutpu t.Text ltr & " is not a vowel . "
End If
End Sub
(Assume the response is a.)
9. Private Sub btnDispl ay_ Click( ... ) Handles btnDispl ay.Click
Dim a As Double = 5
If (a > 2) And ( (a = 3 ) Or (a < 7 ) ) Then
txtOutpu t.Text "Hi"
End If
End Sub

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

11. Pr i vate Sub btnCompu t e Click( ... ) Handles btnComp ute.Click


Dim msg As String = "You are old enough to vote"
))
Dim dateOfBi rth As Date= CDate(In putBox(" Enter y our date of birth."
I f dateOfBi rth . AddYears (lB) <= Today Then
txtOutpu t.Text = msg &
Else
txtOutpu t.Text = msg & " in " &
DateDiff (Dateinte rval.Day , Today, dateOfBi rth.AddYe ars(lB) ) &
11
days. 11
End If
End Sub
(Assume that your 18th birthday is o ne wee k away.)

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

Di m nick sDa teOf Birt h As Date =


#9 / 16/1 992#
If date OfB irth < nick sDa teOf Birt
h Then
t xtO utpu t.Te xt = "You are olde
r than Nick ."
El s eif date OfB irt h = n i cksD ateO
fBir th Then
txtO utpu t.Te xt "You are the exac t same age as
Nick . "
El se
txtO utpu t.Te xt "You are youn ger than Nick ."
End If
End Sub
(As ume that the respo n e is 10/25/1 992.)
In Exercises 13 thro ugh 16 , iden tify the
erro rs, state th e type of each erro r (syn tax,
time, or logic ), and corr ect the bloc k of code run-
.
13. Priv ate Sub btnD ispl ay_ Clic k(
... ) Han dles btnD ispl ay.C lick
Dim num As Dou ble = 0.5
If (1 < num < 3) Then
txtO utpu t.Te xt = "Num ber is betw
een 1 and 3 . "
End If
End Sub
14. Priv ate Sub btnD ispl ay_ Clic k( ...
) Han dles btnD ispl ay . Clic k
Dim num As Dou ble = 6
If num > 5 And < 9 Then
txtO utpu t.Te xt "Yes "
Else
txtO utpu t.Te xt "No"
End If
End Sub
15. Priv ate Sub btnD ispl ay_ Clic k( ...
) Han dles btnD ispl ay.C lick
Dim majo r As Stri ng
majo r = "Com pute r Scie nce"
If majo r = "Bu sine ss" Or "Com
pute r Scie nce" Then
txtO utpu t.Te xt = "Yes "
End If
End Sub
16. Priv ate Sub btnD ispl ay_ Clic k( ..
. ) Han dles btnD ispl ay.C lick
'Tog gle swit ch from on to off
and from off to on
Dim swit chO n As Boo lean
swit chO n = CBo ol(In putB ox(" Ente
r True of Fals e.", "The swit ch is on." ))
If swit chO n Then
swit chO n = Fals e
End If
If Not swit chO n Then
swit chO n = True
End If
txtO utpu t . Text CStr (swi tchO n)
End Sub

I n Exer cises 17 thro ugh 20, simplify the


code .
17. I f (a 2 ) Then
a = 3 + a
Else
126 • Cha pter 4 Decisions

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

[l J Yankee Doodle Preside nt

Which U.S. President was bom on July 4?

Evaluate Allswer Number of guesses : 0

FIGURE 4.3 Form for Exercis e 35 .

a button is clicked and


36. Write a program that reads a tes t core fro m a tex t box each time
is clicked . Use two class-
then displays the two highes t score wh enever a seco nd butto n
level variables to track the two highes t sco res.
program ming language.
37. Write a program to play "Hid e and Seek" with the name of our
caption on the button
When the button is clicked on, the name sh ould disappea r and the
is pressed, the name
should change to "Show Name of Langua ge." The next time the button
of Langua ge," and so on.
sh ould reappear and th caption should revert to "Hide Name

OBJECT PROPERTY SETTING

ll ~ Hide and Seek ~~ ~ lrn::J frmHid eSeek Text Hide and Seek
lblLanguage Text VB 20 10

VB 2010 btnDisp lay


Font.S ize
Text
26
Hide Name of Language

Hide Name of Language

's state income tax. Write a


38. The flowch art in Fig. 4.5 (on the nex t page) calcula tes a person
wi th taxable incomes of
program corresponding to the flowch art. (Te t the program
$ 15 ,000, $30,00 0, and $60,00 0.)
39. Rework Exercise 32 using a variab le of type Date and the
DateO iff functio n.

40. Write a program that request s you r date of birth as input


and tells you whethe r or no t you
are 25 years old or older. If n ot, the program sho uld tell you the numbe r of days until you
will have your 25th birthd ay.
your age. Hint: Use the Date-
41. Write a program that requests your date of birth as input and tells
block to modify the result.
D iff functio n with the Dateln terval.Year option, and then use an If
lf the amoun t deposited is
42. Savings accoun ts state an interest rate and a compo unding period.
per yea r, then the balanc e
P, th e stated interest rate is r, and interes t is compo unded m times
111

in the accoun t after o ne year is P · ( 1 +: ) • For instance , if $1000 is depos ited at 3%


balance after one year is
interes t compo unded quarterly (that is, 4 times per year), then the

1000 .
03 )4
(1 + ~ = 1000. 1.0075
4
= $ 1,030.3 4.

mpared directl y. The


Interes t rates with d ifferent compo unding periods ca nnot be co
the co mparis on. The APY
concep t of APY (annu al percen tage yield) must be used to make

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

(The APY is the simpl e interest rate that yields the sa


me amou nt of interest after one yea r
as the compound ed annu al rate of interest.) Write a
progra m to co mpare interes t rates
offered by two different banks and determine the most
favora ble intere t rate. Se Fig. 4.4.

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

FIGURE 4.4 Possible outcome of Exercise 42.

Yes
20000?

Set tax =
.02 *Income Yes No
income :s
50000?

Set tax = Set tax =


400 + .025 * 1150 + .035 *
(Income - 20000) (Income - 50000)

FIGURE 4.5 Flowc hart for Exercise 38.


130 • Cha pter 4 Dec ision s

the task shou ld be


the pro gra m in Exa mpl e 8 wit hou t using Else if clauses. Th at is,
43. Rewrite
ple If blo ck .
ca rried out wit h a seq uen ce of sim
wee n 2 and 4
pro gra m in Exa mp le 8 so tha t the G PA is va lid ated to be bet
44. Rewrite the
before the If block is exec uted.

4.2
Solu tion s to Practice Problems

1. I f (num < 0) The n "In put Err or" )


can 't be neg ati ve. ",
Me ssag eBo x.S how ("N urn ber
txtN um ber .Cl ear ()
txtN um ber .Fo cus ()
Els e
txtS qua reR oot .Te xt = CS tr(M ath .Sq rt(n um ))
End If layed
also true. Tha t is, it wi ll be disp
lo" wi ll be disp layed whe n (a < b) is true and (c < 5) is
2. The word "hel write th e bloc k is
ons arc true. The clea rest way to
whe n bmh of these two cond iti
The n
If (a < b) And (c < 5)
txtB ox. Tex t = "he llo "
End If

4.3 Select Case Blocks


osing among
ck is an efficie nt dec isio n-m aking stru cture tha t simplifies cho
A Select Cas e blo isio ns based on the trut h
If con stru cts. If blocks ma ke dec
severa l act ions. It avo ids com plex of an exp ress ion call ed a
a con dition; Sel ect Cas e cho ices are det erm ined by the va lue
va lue of
preceded by a clau se of the form
sele cto r. Eac h poss ible acti on is
Cas e val ueL ist
on sho uld be tak en .
of the sele cto r for whi ch the acti
where valueList ite mizes the va lues

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

a .. Hor se Race GJ I G IE![] frmRace Tex t H orse Rac e


lblP osit ion A utoS ize False
Rnishing position Tex t Fini shin g pos itio n
(1. 2. 3....): (1, 2, 3, .. . ):

Evaluate Position txtP osition


btnE valu ate Tex t Eva luat e Po itio n
txtO utco me Rea dOn ly Tru e

Ev alu ate .Cl ick


Cli ck( ... ) Han dle s btn
Pri vat e Sub btn Eva lua te_
r 'se lec tor
Dim pos itio n As Int ege
tPo siti on. Te xt)
pos itio n = Cin t (tx
4.3 Select Case Blocks
• 131

Selec t Case positi on


Case 1
txtOut come. Text "Win 11
Case 2
txtOut come. Text "Place "
Case 3
txtOut come. Text "Show"
Case 4, 5
txtOut come . Text "You almos t placed in the money ."
Case Else
txtOut come. Text "Out of the money ."
End Selec t
End Sub
[Run, type 2 into the text box, and click on the button .]

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

In the mon8)' . Congrat ulations.


132 • Chapt er 4 Dec isions

General Form of a Select Case Block


A typical form of the Se lect Case block is

Selec t Case selec tor


Case value List 1
actio n 1
VideoNote
Case value List 2
Select Case blocks
actio n 2
Case Else
actio n of last resor t
End Selec t
lue li t conta in one or more of the fol-
where Case Else (and its action ) is optio nal, and each va
lowing types of items:

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;

5. a range expressed in the form a To b , where a


and b are litera ls, variables, or exp ressions.
sepa rated by comm as. Each action
Two or more items appea ring in the same list must be
is evalu ated, Visual Bas ic looks for the
consists of one or more statem ents. After the select or
and carries out its assoc iated act ion . (If
first value-list item includ ing the va lue of the select or
lists, on ly the act ion assoc iated with the
the va lue of the selector appea rs in two different va lue
or does not appea r in any of the value
first value list will be carried out.) If the value of the select
program will co ntinu e with the tate-
lists and there is no Case Else clause, execution of the
ment following the Selec t Case block.
. The pse udoco de for a Selec t Case
Figure 4.6 conta ins the fl owch art for a Se lect Case block
block is the same as for the equiv alent If block .

and then displays the


"' Example 3 The follow ing progra m requests a mont h and a year,
block nes ted inside a Se lect Case block.
numb er of days in that mont h. The program uses an If
r. (A year is a leap year if there are 366
The If block determ ines wheth er the year is a leap yea
t year.) The value lists come from the
days from Janu ary 1 of that year to Janua ry 1 of the nex
rhyme "Thir ty days hath Septe mber."
OBJECT PROPERTY SETIING
D- Count Days ~~ @J ~ frmDays Tex t Coun t Days
lblMo nth : Text Month {1- 12):
Month (1 - 12): Mask 00
mtbM onth
Year: lblYear Text Year:
mtbYear Mask 0000
I Determ ine Numb er of
l Determine Number
of Days in Month
btnDe termin e

txtOu tput
Text

ReadO nly
Days in Month
True

les btnD eterm ine.C lick


Priva te Sub btnD eterm ine_ Click ( ... ) Hand
ext)
Dim month As Integ er = Cint (mtbM onth.T
Dim yr As Integ er = Cint (mtbY ear.T ext)
4.3 Select Case Blocks • 133

Evaluate
selector

Yes
Action 1

Yes
Action 2

Yes
Action n

Perform
action of
last resort