Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
1K views

An Introduction To Programming Using Visual Basic 2010

Uploaded by

Josue Molina
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views

An Introduction To Programming Using Visual Basic 2010

Uploaded by

Josue Molina
Copyright
© © All Rights Reserved
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 is@math.umd.edu

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

FIGURE 4.6 Flowc hart for a select case block.

Dim dl , d2 As Date
Dim numb erOfD ays As Integ er
Selec t Case month
Case 9, 4 , 6, 11 eptcm b :r, Apr~l, J•me, and Novem ber
numb erOfD ays = 30
Case 2 F bruar y
dl = CDate ( "l/1/ " & yr)
d2 = dl.Ad dYea rs(l)
If Date Diff( Date inter val . Day, dl, d2)
366 Then
numb erOfD ays 29
Else
numb erOfD ays = 28
End If
Case Else 'all the rest
numb erOfD ays = 31
End Selec t
134 • Chap ter 4 Decis ions

& " has " &


txtO utpu t . Tex t = mont h & "/" & yr
numb erOfD ays & " days ."
End Sub
cl ick on the butto n to find the numb er of days
[Run , ente r 2 and 2012 into the text boxe s, and
in Febru ary, 2012 .]

aj Co

Month (1 - 1

Year: 2 12

Determ ine Number


of Days in Month

212 1 has 29 days.

a num eric va riable; however, the selec tor


ln the three prece ding exam ples, the selec tor was
an expression .
also can be a strin g varia ble, a date varia ble, or

firstN ame as a se lecto r.


Example 4 The follo wing program has the str ing varia ble

OBJECT PROPERTY SETTING

a Quiz GJ []D [j[] frmQuiz Text Qu iz


lblQ uestio n Au toS ize False
What '• •as President W hat was Pres ident
Wilson s fir.:.i name . Tex t
Wilso n 's first name?
Interpret Am:,•, er txtN ame
btn!n terpre t Tex t Interpret Answer
txtRe ply Read O n ly True

) Hand les btni nter pret .Cli ck


Priv ate Sub btni nter pret _ Clic k( ...
Qui
Dim first Nam e As Strin g
first Nam e = txtN ame. Text .ToU pper
Sele ct Case first Nam e
Case "THOMAS"
txtR eply . Text "Co rrec t."
Case "WOODROW"
txtR eply .Tex t "Sor ry, his full name was " &
"Tho mas Wood row Wils on."
Case "PRE SIDE NT"
txtR eply .Tex t "Are you for real ?"
Case Else
txtR eply .Tex t "Nic e try, but no ciga r."
End Sele ct
End Sub
4.3 Select C:;~se Blocks • 135

[Run , type "Woodrow" into the tex t box, and click on the button .]

a_. Qu iz

What was President


Wilson 's first name? Woodrow

Interpret .Answer

Sony. his full name 'Nas Thomas 1Noodrow Wilson .

Example 5 The following program has the string selector any tring.Substrinf (0 , 1) . In the
sample run , only the first action was carried out, even though the value of the elec~or was
in both
of the first two value lists. Visual Basic stops looking as soon as it find s the value of the
selector.
OBJECT PROPERTY SETTING
a... Analyze First Character [E]I ~ I~
frrnAn alyze Text Analyze First
Enter a string : C haracter
lblEnter Text Enter a string:
Analyze txtString
btnAnalyze Text Analyze
txtResult ReadO n ly True

Private Sub btnAnal yze_ Click ( . . . ) Handles btnAnal yze . Cl ick


'Analyze the first charact er of a string
Dim anyStrin g As String
anyStri ng = txtStr i ng.Tex t. ToUpper
Select Case anyStrin g . Substr i ng(O, 1)
Case nsn , nzn
txtResu lt . Text "The string begins with a sibilan t."
Case "A" To "Z"
txtResu lt . Text "The string begins with a nonsibi lant."
Case "0 11 To 11
9 11
txtResu lt . Text "The string begins with a digit."
Case Is < "0"
txtResu lt.Text "The string begins with a charact er of " &
"ANSI value less than 48."
Case Else
txtResu lt . Text "The string begins with : > &
< II

" ? @ \ or
End Select
End Sub

[Run, type "Sund ay" into the tex t box, and click on the button.]

a... Ana lyze First Cha racter

Enter a string: Sunday

Analyze

The string begins with a sibilant .


136 • Chapte r 4 Decisions

Comments
less than o r equa l to the
1. In a Case clause of the fo rm Case b To c , the valu e of b shou ld be
va lue of c. Otherwise, the clause is meanin gles .
e list, is acc idental ly omit-
2. If the word Is , which should preced e an ineq uality ign in a va lu
ted, the edito r will automa tica lly inse rt it when checki ng the line.
type a the e lector. For
3. The items in th e va lue list must evalu ate to a literal of the sa me
instance, if the selecto r eva lu ated to a string va lue, as in

Dim firstNa me As String


firstNa me = txtBox .Text
Select Case firstNa me

then the clause


Case firstN ame.L ength

wou ld be meanin gless.


level scope; that is, the
4. Any variable declared inside an If or Select Case block h as block-
variabl e cannot be refe rred to by code outside the block.
ning Selection Structures:
5. In Appen dix D, the section "Stepp ing through Programs Contai
h a Select Case block.
C hapter 4" uses th e Visual Basic debugg ing tools to trace the flow throug

Practice Problems 4.3


var iab le num. Determ ine
1. Suppose the selecto r of a Select Case block is the numeri c
whethe r each of the fo llow ing Case clauses is valid.
(a) Case 1, 4, Is < 10
(b) case Is< 5, Is>= 5
(c) case nwn = 2 (where t he selecto r num is of type Double )
for a who le- numbe r grade
2. Do the followi ng two programs always produc e the same output
from 0 to 100?

grade = Cint(t xtBox .Text) grade = Cint(t xtBox .Text)


Select Case grade Select Case grade
Case Is >= 90 Case Is >= 90
II All
txtOu tput.T ext II All txtOu tput.T ext
Case Is >= 60 Case 60 To 89
Pass 11 txtOu tput.T ext 11
PaSS 11
txtOut put . Text 11

Case Else Case 0 To 59


"Fail" txtOu tput.T ext 11
Fail"
tx t Outpu t.Text
End Se l ect End Select

EXERCISES 4.3 .

parent heses, determ ine the


In Exerci ses 1 throug h 6, for each of the respon ses shown in the
output display ed in the text box when the button is clicked on.
Click
1. Privat e Sub btnDis p1ay_ Click( . .. ) Handle s btnDi splay.
Dim age, price As Double
age = CDbl (InputB ox ("What is your age?") )
Selec t Case age
4.3 Select Case Blocks • 137

Case Is < 6
price 0
Case 6 To 17
price 3.75
Case Is >= 17
price 5
End Select
txtOutp ut.Text "The price is " & FormatC urrency (price)
End Sub

(8.5, 17)

2. Private Sub btnDisp lay_ Click( ... ) Handles btnDisp lay.Clic k


Dim nurn As Double
nurn = CDbl(In putBox( "Enter a number from 5 to 12"))
Select Case nurn
Case 5
txtOutp ut.Text •case 1"
Case 5 To 7
txtOutp ut.Text "case 2"
Case 7 To 12
txtOutp ut . Text "case 3 11
End Select
End Sub

(7, 5, 11. 2)

3. Private Sub btnDisp lay_ Click( ... ) Handles btnDisp lay.Clic k


Dim age As Integer
age= Cint(Inp utBox(" Enter age (in million s of years)" ))
Select Case age
Case Is < 70
txtOutp ut.Text "Cenozo ic Era"
Case Is < 225
txtOutp ut . Text "Mesozo ic Era"
Case Is <= 600
txtOutp ut.Text "Paleoz oic Era"
Case Else
txtOutp ut.Text "?"
End Select
End Sub

(100, 600, 700)

4. Private Sub btnDisp lay_ Click( ... ) Handles btnDisp lay.Clic k


Dim pres As String
pres = InputBox ("Who was the younges t U.S . preside nt?")
Select Case pres.ToU pper
Case "THEODORE ROOSEVELT", "TEDDY ROOSEVELT"
txtOutp ut.Text = "Correc t. He became preside nt at age 42 "
&
"when Preside nt McKinle y was assassi nated."
Case "JFK", "JOHN KENNEDY", "JOHN F. KENNEDY"
txtOutp ut.Text = "Incorr ect. At age 43, he was the younges
t " &
"person elected preside nt."
138 • Chapte r 4 Decisions

Case Else
txtOu tput.T ext "Nope"
End Selec t
End Sub

(J FK, Teddy Roosevelt)


5. Privat e Sub btnDis play_ Click( . . . ) Handl es btnDi splay. Click
Dim messag e As Strin g, a, b, c As Double
equa ti on " &
messag e = "Analy zing soluti ons to the quadr atic
"AX A2 + BX + C = 0. Enter the value for "

a CDbl ( InputB ox (messa ge & "A"))


b CDbl(I nputBo x(mess age & "B"))
c CDbl ( InputB ox(me ssage & "C"))
Selec t Case (b A 2) - (4 * a * c)
Case Is < 0
tx t Outpu t . Text "The equati on has no real soluti ons."
Case 0
tx t Outpu t.Text "The equati on has exac t ly one soluti on."
Case Is > 0
tx t Outpu t.Text "The e quatio n has two so l utions ."
End Se l ect
End Sub

(1 ,2,3 ; 1,5,1; 1,2, 1)


ck
6. Pr ivate Sub btnDis pl a y_ Click( . .. ) Handle s btnDis p l ay.Cli
Dim wha t ever As Double
whatev er= CDbl( InputBox("E nter a numbe r:"))
Select Case whatev er
Case El se
txtOu tput.T ext " Hi"
End Select
End Sub
(7, - 1)
In Exercises 7 through 12, identif y the errors.
Click
7. Priv ate Sub btnD i splay_ Click( . .. ) Handle s b t nDisp lay .
Dim num As Double = 2
Se l ec t Case num
txtOut put . Text 11
TW0 11

End Se le c t
End Sub
8. Privat e Sub btnDis play_ Click( ... ) Handle s btnDi splay. Click
Dim num1 As Double 5
Dim num2 As Double = 2
Select Case numl
Case 3 <= num1 <= 10
txtOu tput.T ext = "betwe en 3 and 10."
Case num2 To 5; 4
txtOu tput.T ext "near 5."
End Select
End Sub
4.3 Se lect ase Blocks • 139

9. Private Sub btnDisplay_ Click( .. . ) Handles btnDisplay.C lick


Dim nom As String
nom = InputBox ("What is your name?")
Select Case nom
Case nom = "Bob"
txtOutput.Te xt "Hi, Bob."
Case Else
End Select
End Sub

10. Private Sub btnDisplay_ Click( . . . ) Handles btnDisplay.C lick


Dim word As String = "hello"
Select Case word . Substring(O, l)
Case h
txtOutput.Te xt = "begins with h."
End Select
End Sub

11. Private Sub btnDisplay_ Click( . .. ) Handles btnDisplay.C lick


Dim fruit As String = "Peach"
Select Case fruit . ToUpper
Case Is >= "Peach"
txtOutput.Te xt = "Georgia"
Case "ORANGE To PEACH"
txtOutput.Te xt = "Ok"
End Select
End Sub

12. Private Sub btnDisplay_ Click( ... ) Handles btnDisplay.C lick


Dim purchase As Double
purchase = CDbl (InputBox("Q uantity purchased?") )
Select Case purchase
Case purchase < 10000
txtOutput . Text = "Five dollars per item."
Case Is 10000 To 30000
txtOutput.Te xt = "Four dollars per item."
Case Is > 30000
txtOutput.Te xt "Three dollars per it em."
End Select
End Sub

In Exe rcises 13 through 18, suppose the selector of a Select Case block, word, evaluates to
a String value. D etermine whether the Case clause is valid.
13. Case nunn & 11
til 11
14. Case "hello" , Is < "goodbye"
15. Case 0 To 9
16. Case word <> 11
No"
17. Case "abc".Substri ng(O, 1)
18. Case Is <> .. Non
140 • Chapter 4 Decisions

In Exercises 19 through 22, rewrite the code using a Select Case block.
19. I f a = 1 Then
txtOutput. Text "one"
Else
If a > 5 Then
txtOutput. Text "two"
End I f
End If

20. I f a = 1 Then
lstOutp ut . Items .Add ("lambs")
End If
If ((a< = 3) And (a< 4)) Then
lstOutp ut.Items.A dd("eat")
End I f
If ((a= 5) Or (a> 7)) Then
lstOutp ut. Items .Add ("ivy")
End If

21. If a < 5 Then


If a = 2 Then
txtOutput. Text 11
yes"
Else
txtOutput. Text "no"
End If
Else
If a = 2 Then
txtOu tput.Text "maybe"
End I f
End If

22. I f a = 3 Then
a = 1
End If
If a = 2 Then
a = 3
End If
If a = 1 Then
a = 2
End If

23. Table 4.5 gives the terms used by the N ationa l W ea the r Se rv ice to describe the degree of
cloudiness. Write a program that requests the pe rce ntage of cloud cove r as input a nd th e n
di p lays th e app ro priate descriptor.

lt4:JIIJW Cloudiness descriptors.


Percentage of Cloud Cover Descriptor

0-30 clear
31- 70 pa rtly cloudy
71-99 cloudy
100 ove rcast
4.3 Select Oase Blocks • 141

24. Table 4.6 sh ows the location of books in the library stacks according to the ir call numbers.
W rite a program that requ es ts the ca ll number of a book as input and d isp lays th e location
of th e book.

IM:JIIIM Location of library books.


Call N umbers Location

100 to 199 basement


200 to 500 and over 900 main floor
501 to 900 except 700 to 750 upper floor
700 to 750 archi ves

25. Figure 4. 7 sh ows some geometr ic shapes and formulas for the ir areas. Write a program th at
requests the user to select one of the shapes, req uests the appropriate lengths, and then
gives the area of the figure.

G }
Circle Parallelogram Kite
3.1 41593 * r " 2 I* h (I * w) I 2

FIGURE 4.7 Areas of geometric shapes.

26. Break-Even Analysis. S uppose a ce rtain prod uct se lls for a dollars per unit. Then the reve nue
fro m se lling x un its of the product is ax do llars. If the cos t of produc ing each unit of the
product is b do llars and the company has o verhead cos ts of c do llars, th en the tota l cos t of
producing x units of the product is bx + c do llars. (Note: Revenue is the amount of money
rece ived fro m the sa le of the produ ct. The va lues of a, b, and care ca lled the marginal rev-
enue , marginal cost, and fixed cost respec tive ly. The break- even po int is the va lu e of x for
which the revenu e equa ls the total cos t.) Write a program that req uests the marginal rev-
enu e, marginal cost, fixed cos t, and number of units of the product produ ced and so ld (x)
and then displays one of the fo llowing three outputs: PROFIT, LOSS , o r BREAK EVEN.
27. Write a program that reques ts an exam score and ass igns a letter grade with the scale
90-100 (A ), 80-89 (B) , 70-79 (C ), 60- 69 (D) , 0- 59 (F). (Tes t the program with the
grades 84, 100, and 57.) VideoN ote

28. Table 4.7 conta ins information on several states. Write a program that requests a state and G rad ing
system
category (flower, motto , and nickname ) as input and displays the requested info rmation. lf ( Ho mewo rk )
the state or category requested is not in the table, the program sh ould so inform the use r.

State flowers, nicknames, and mottoes.


State Flower Nick name Motto
California Go lden Poppy Go lden State Eureka
Indiana Peony Hoos ier State C rossroads of America
Miss iss ippi Magnoli a Magnolia State By va lor and arms
New York Rose Empire State Eve r upward
142 • Chapter 4 Decision s

reco vered. If the


29. IRS informa nts are paid cash awa rds based on the va lue of the mo ney
ry, the info rmant rece ives 10 percent of
informa tion was specific enough to lead to a recove
of the remaind er, up to a
the first $75,000 , 5 percent of the next $25,000 , and 1 perce nt
the recover y as
maximu m award of $50,000 . Write a program that req uest the amo unt of
$ 125,000 , and
inpu t and displays the award . (Test the program on the amount s $ 10,000,
is The Book oflnside Informa tion, Boa rdroom
$ 10,000,000.) Note: The source of this formula
Books, 1993.
fo r prescrip tions.
30. Table 4. 8 contain s the meanin gs of so me abbrevi ations docto rs often use
use r sho uld be
Write a program that req uests an abbrev iati on and gives its meanin g. The
informe d if the meanin g is not in the table.

lij1:1!11:M Physicians' abbreviations.


Abbrevi ation Meaning

ac before mea ls
ad li b free ly as needed
bid tw ice daily
gtt a drop
hs at bedtime
q id four times a clay

ts beginni ng
31. Write a program that, given the last name of o ne of the six recent presiden
The program might
with Carter, displays his sta te and a colorful fact abo ut him. (Hint:
drink served in
need to request further informa tion.) (Note: Carter: Georgia ; The only soft
code name
the Carter White H ouse was Coca-C o la. Reagan : Ca lifo rnia; His Secret Service
his 85th birthday by parachu ting
was Rawhid e. George H. W. Bush: Texas; H e ce lebrated
imitatio n of Elvis Pre ley.
out of an airp lane. C linton: Arkan a ; In co llege he d id a good
Obama: Illino is;
George W. Bush : Texas; He once owned the Texas Rangers base ball tea m.
He was the e ighth left- hand ed pres ident.)
box and then clicks
32. Write a programs in which the user enters a number into a masked text
or one of three
on the appropri ate button to have e ither one of three pieces of humor
i no t between 1
insu lts disp layed in a text box below the buttons. If the num ber entered
Some poss ible bits of humo r are "I can
and 3, the masked text box sho uld be clea red . (Note:
He's not coming h o me,"
resist everyth ing except temptat ion," "I just hea rd from Bill Bailey.
ible insults are
and "Addin g people to a late software project makes it later." Some poss
friends than an
"H ow much would you charge to haunt a house?" "I bet you have no more
alarm clock," and "When yo ur IQ rises to 30, sell.")

OBJECT PROPERTY SETTING


a J 4.3 Exerci£e 32 GJI ~ l[]f] frmExe rc ise32 Text 4.3 Exercise 32
lbiN umber Text Number (1-3):
Number (1-3): - mtbNum ber Mas k 0
btnH umo r Text &Humo r
.tiumor !nsu~
btnlnsul t Text &Insu lt
txtScnte nce R a !Only True
4.4 In put via User Se lection s
• 143

Solutions to Practice Problems 4.3

1. (a) Va lid. T h ese items a re redunda n t beca use 1 a nd 4 a re just


spec ia l cases of Is < 10 . H oweve r, thi s m akes
n o c.liffc rcncc in Visua l Bas ic.
(b) Va lic.l. Th ese ite ms a rc co ntrad ic to ry. H o we ve r, V isua l
Basic looks at t h em o n e at a t im e un t il it find s a n
ite m conta ining the va lue o f rh e selector . T h e act io n fo
llow in g th is Case c lause w ill a lways be ca rri ed our.
(c) ot va lic.l. It sho ulc.l be Ca se 2 .

2 . Yes. H oweve r, rh c progra m o n th e righ t is c lea re r an


c.l th erefore prefe rab le.

4.4 Input via User Selections


Programs freque ntly ask the use r to make selecti ons from lists
of opt ions. In the quest ion naire
in Fig. 4.8, studen ts can select their major fro m a list box, their
year fro m a set of radio button s,
and their compu ter languages studie d from a set of check boxes.
After the select ions have bee n
made, the use r clicks on the Record Data button to process
the informat ion . T he set of rad io
button s and et of check boxes are each conta ined in a group
box contro l. T he t itles sunk in to
th e tops of the group boxes are Year and Languages Studied.
After elect ions are made from the
three sets of cho ices, dec ision structu res can be used to proces
s the info rmatio n. Let's consid er
the fo ur types of contro ls in Fig. 4. 8 one at a time.

a .. Question naire

Major Year Languages Studied


Biologic al Science
BuSiness
Freshman [1] Visual Basic
Computer Science
Education
Sophmo re u Java
English Q Junior L{] c
Fine Arts
History Senior o c
Humanities
Mathematics L] C#
Physica l Sciences
Social Sciences Record Data [{] Cobol

FIGURE 4.8 Selecti o n con t ro ls.

Using a List Box for Input


The easiest way to populate a list box with items is to place the
items into the list box's String Col-
lection Ed itor at design time. When you click on the list box's
Tasks button and then click on Edit
Items (Fig. 4.9), the String Collec tion Ed itor appears. Figure 4. 10
shows the String Collec tion Edi-
tor filled with the items from Fig. 4.8. T h r e ways to fill the String
Collec tion Ed itor are as follows:
1. Type the items directl y into the String ollect ion Editor.
2. Copy a list of items from any tex t ed itor (such as N otepad
or Word ) with C tr l + C and paste
the list into the String Collec tion Edi tor with C trl + V.
3. Copy a colum n of data fro m a sp readsh ee t progra m (such
a Exce l) and paste it into the
String Collec tion Ed ito r.

When the use r clicks on an item at run ti me, that item i


high ligh ted, and the va lue of
lstBox .Tex t is that item rep rese nted as a string .
144 • Chap ter 4 Dec isions

Tasks button ~

0 = ""-0·~ ....o=JI UstBo x Tasks


! ls! Majom
LJ Use Data Bo un d Items

Unbo und' Mode


Edit Items ...

~ di<kho"
Edito r.
FIGURE 4.9 Cl ick on Edit Items to invok e the String Colle ction

St ri ng Co llectio n Edi or

Enter t he stri ngs in t he coll ection (one per li ne):


Biolo gic al Sc ien ce
Busin es>
Computer Science
Edu cation
Engli sh
Fin e Arts
Histo ry
Hum anities
Math emati cs
Physica l Sc iences
Soc ial Sci ences

~---O_K____~] [L___c_a_nc_e_l __~

FIGURE 4.10 String Collection Edito r.

mont hs can be typed


Example 1 The following program use a list of mont hs. The
ate way to obtai n the list of mont hs is to
d irectly into the Strin g Collect ion Edito r. An altern
into a cell of an Exce l sprea dshee t [ ee
ge nerat e it wi th Exce l. To do o, type Janua ry
le down to creat e the other mont hs [see
Fig. 4.11 (a )], click on the cell, drag its fi ll hand
twelve mont hs can be paste d into the Strin g
Fig. 4.ll (b )], and press Ctrl + C. Then the list of
Colle ction Edito r with Ctrl + V.
Hand les btnDeterm ine.C lick
Priv ate Sub btnD eterm ine_ Click ( ... )
Dim daysi nMon th As Strin g
Sele ct Case lstM onth s.Tex t
"Nov embe r"
Case "Sep temb er" , "Apr il" , "June " ,
daysi nMon th = "30"
Case "Feb ruary "
daysi nMon th = "28 or 29"
4.4 Input via Use r Se lect ions • 145

Case Else
daysinMo nth = "31"
End Select
txtDays.T ext = daysinMo nth
End Sub

[Run , click on a month , and then click on the button .]

aj umb er of Day s

Select a month :

January
February
March
( Determine Number of Days )
April
May
June
Ju~· Number of days: 31
August
Se~ember
tet;;.I4M
November
December

A
1 jJ a nu a~
A l
I - 1 January
2
3
7
fill handle
2 February
3 March
4 4 April
5 5 May
6 6 Jun e
7 7 July
8 8 Augus·
9 9 Sep ember
10 10 October
11 11 Nov ember
12 12 Decem ber
I

(a) (b)

FIGURE 4.11 Creating a list of months with Excel.

Example 2 The fo llowing program presents a list of famous movie lines spo ken by lead ing
male actors. After the user makes a selection and clicks on the butto n, the actor is identified.
The numberin g of the lines allow the Select Case block to be simpli fied .
Private Sub btnDeterr nine_ Click( ... ) Handles btnDeter rnine.Cli ck
Dim actor As String = ""
Select Case lstLines. Text.Sub string(O , 1)
Case 11
1 11 ,
11
2 11

actor = "Marlon Brando"


Case "3" , "4"
146 • Chapter 4 Decisions

actor = "Humph rey Bogart "


Case "5" , 11
6 11
actor = "Harris on Ford"
Case "7"
actor = "Leona rdo DiCapr io"
Case "8"
actor = "Roy Scheid er"
End Select
txtAct or.Tex t = actor
End Sub

[Run, click on one of the lines in the list box, and then click on the button.]

Unes spoken by leading actor:

1. I coulda been a contender. Determine the Actor


2. I'm gonna make him an offer he can 't refuse .
J. Pla'l it Sam .
. We'll ah·\'a'l S have Paris .
.A.ctor: Leonardo DiCaprio
5. Ma'l the force be with you .
S. I hate snakes .
7 I'm kin of the world '
8. You ·re gonna need a bigger boat .

ltem is Nothing.
When no item in a list box is highligh ted, the va lue of lstBox.S elected
item that has been
A lso, the stateme nt lstBox . Selecte ditem = Nothin g dese lects any
se lected. By default, only one item at a time can be se lected in a list box.

Group Box Control


4.7 , the group box
Group boxes are pass ive obj ects that contain related sets of controls . In Fig.
titled Languag es Studied con -
titled Year conta ins four rad io button contro ls and the gro up box
ed in group boxes.
tains six check boxes. C lusters of radio buttons are almost always contain
Actually, any se t of control s ca n be placed into a group box for visua l effect.
box, the controls
You rarely write event proced ures for group boxes. When you move a group
be attached to the group box. lf you hide
inside it fo llow as a unit. Therefo re, the controls are said to
to a group box, just cre-
a group box, the attached contro ls will be hidden as well. To attach a control
prefix for the name
ate the control any way you like and drag it inside the group box. The standard
with the Tex t property.
of a group box is grp. The tit! sunk into the top of a group box's border is set

Using Radio Buttons for Input


op tion . The n ame
Radio buttons allow the use r to make a single cho ice fro m among seve ral
rad ios, which had buttons that pressed in.
"radio button" co mes from a reference to t he first car
would ra ise any other butto n
Press ing on e button would move the dial to a preset station and
that was depressed.
Each button con-
Normally, a collecti on of several radio buttons is attache d to a group box.
is set with the Tex t property . (As with ordi-
i ts of a small circle accomp anied by a caption that
rad io button.) When a c ircle
nary buttons, an ampersa nd can be used to create an access key for a
button is sa id to be
or its acco mpanying caption is clicked, a solid dot appears in the c ircle and the
re, if one button is on
on. At mo t one radio button in a group can be on at any one time. Therefo
be turned off. The standard prefix
and another button in the group is clicked , the first button will
of radio buttons .
for the name of a radio button is rad. A single form. can have seve ral group
4.4 ln put v ia Use r Sele ction s
• 147

The C hecked property of a rad io button


tells if the button is on or off. The cond
ition
radB utto n .Che cked
is tru e whe n radBu tton is on and false whe
n radB utto n is off. The state men t
radB utto n.Ch ecke d = True
turn s on radB utto n and turn off all othe
r button in its group. The state men t
radB utto n.Ch ecke d = Fals e
turn s off radB utto n and has no effec t on
the othe r butt ons in its group.

Example 3 The follo wing prog ram di plays the adm


issio n fee to an even t. Afte r th e user
clicks on a rad io butt on and clicks on
the Determin e Fee butt on, the fee is disp
box . The Else clause in the If bloc k hand laye d in a tex t
les the case whe re no selec tion was mad
e.
OBJECT PROPERTY SETTING
a .... Admiss1on Fee
frmF ee Tex t Ad miss io n Fee
Age grpA ge Text Age
[ Determine Fee ] radC hild
child ( ' 6) Tex t c hild ( < 6)
radM ino r Text mino r (6- 17)
minor (5-17)
radA du lt Tex t adul t (1 8-64 )
Fee :
adu~ (18-64) radS e ni o r Tex t se nio r ( 65 +)
senior (65+) btn Oete rm ine Tex t Octe rm in ~ Fee
lb lFee Tex t Fee:
txtFe e Read On ly True
Priv ate Sub btnD eter min e_ Clic
k( ... ) Han dles btnD eter min e.Cl
If radC hild .Che cked Then ick
txtF ee.T ext = Form atCu rren cy(O
)
Els eif radM inor .Che cked Then
txtF ee.T ext = Form atCu rren cy(S
)
Els eif radA dult .Che cked Then
txtF ee.T ext = Form atCu rren cy(l
O)
Els eif radS enio r.Ch ecke d Then
txtF ee.T ext = Form atCu rren cy(7
.5)
Else
Mes sage Box .Sho w( "You mus t mak
e a sele ctio n." )
End If
End Sub

[Run, click on a radio button, and click


on th e Determin e Fee button]

a .. Adm issio n Fe e l = J@) I~·AJ!II


Age
[Det ermine Fee J
child ( '6)
minor (5-17)
Fee : 10.00
0 adu~ (18-64)
senior (65+)
148 • Cha pter 4 Dec ision s

Using Check Boxes for Input


t property ), pre-
ll squ are and a caption (se t with the Tex
A che ck box , whi ch con sist of a sma con tro ls. The
the user with a yes/ no cho ice. The form in Fig. 4. 7 con tain s six check box
se nts ty and True whe n
the va lue False whe n the squ are is emp
C hecked property of a chec k box has n ying capt ion )
user cl icks on the squ are (or its acco mpa
the squa re is chec ked. A t run time, the
chec ked states.
to togg le between the unc hecked and
.
mon thly cost of a compan y hea lth plan
Example 4 The follo wing program calc ulate the the tota l co t.
then clicks on the butt on to calcu late
The use r chec ks the desired plan s, and
PROPERTY SETTING
OBJECT

c ~.J Benefit> ~v1enu GJ I G I[][ ] frmM enu Tex t Bene fits Men u
Text Prescri ptio n Drug
chkD rug
Prescription Drug Plan {S33.15) P lan ($39.1 5)
Tex t Den tal P!an ($10 .81)
Dental Plan i. 1 .&1) chkD enta l
Text Visio n Plan ($2 .25)
chkVi sio n
u 'Vision Plan {S2.25) chkM edic a l Text Med ical Plan ($5 5.52)
Text Dete rmin e Tota l
btnDeterm ine
Mon thly Cos t
Text Tota l mon thly cost:
lblTo tal
Read O nly True
txt Tota l
Tota l morrth~t cost :

e . Clic k
k( ... ) Han dles btnD eter .min
Priv ate Sub btnD eter .mi ne_ Clic
Dim sum As Dou ble = 0
If chkD rug . Che cked The n
sum += 39.1 5
End If
If chk Den tal.C hec ked The n
sum += 10.8 1
End If
If chk Vis ion. Che cke d The n
sum += 2.25
End If
If chk Med ical .Ch ecke d The n
sum += 55.5 2
End If
txtT ota l.Te xt For. mat Cur renc y(su m)
End Sub
butt on.]
[Run, sele ct plan s, and then click on the

-/
1
Prescription Drug Plan ( l9.1 5)
0 Dental Plan {S1 .&1)
2] Vision Plan (S2.25)
f'i] Medical Plan {S55.5 )
4.4 lnput via Use r Selecti ons
• 149

When a check box has the focus, the spacebar can be used to check
(or uncheck) the box.
In addit ion, the state of a check box can be toggled from the keyboa
rd without first setting the
foc u to the check box if yo u crea te an access key for the check box
by includ ing an amper a nd
in the Text prope rty. (At run time, acce s keys appear underlined
after the A lt key is pressed.)
For instance, if the Tex t prope rty for the Den tal Plan in Exa mp le
4 is set as "&Den tal Plan",
then the user can check (or unchec k) the box by press ing A lt + D.

Events Raised by Selections


In most real-life progra ms, the use r is asked to make selectio ns from
several d ifferen t contro ls
and then click on a button in order to process the inform ation. Such
is the case with the Visual
Ba ic Font selection window hown in Fig. 4.12, where the OK button
is clicked after the selec-
tions have been mad e. Somet imes however, you would like to process
information a soon as an
item in a li t box, a radio button , or a check box is clicked . Visual
Basic provid es event proce-
dures for immediate process ing.

Bold Obliq m

Bfects Sample
Strikeout
L-J Underline a BbYylz

Scnpt:
Nest em

FIGURE 4.12 Font sel ection window.

W hen you click on an ite m in a list box, the Selectedlndex Chang


ed event is raised. When
you click on a radio button or a check box , the C hecked Changed
event is raised. T hese events
are the defa ult eve n ts for their contro ls.

~ Example 5 The following variati on of Examp le 4 keeps a runnin g total of ohe


month ly
cos t of the benefit s. The amoun t in the text box i increased each
time a check box becomes
checked and is decreased each time a check box beco mes unchec
ked. To create the head e r~ r
the event proced ure we doub le-clicked on the first check box , change
d the name 6f the event
proced ure fro m chkDru g_CheckedC hanged to checkB ox_C hecked
C hanged , and ~dd ed three
add itional events followi ng the keyword Handles.
150 • C hapt r 4 Dec isions

OBJECT PROPERTY SETIING


a J Benefit,. Menu LEJ [g]9 [] frmMe nu Tex t Benefit Menu
chkDrug Tex t Prescr iption Drug Plan ($39.15)
f Prescription Drug Plan (S39 .15) Text Denta l Plan ($ 10. 1)
chkDe ntal
L Dental Plan (510.81) chkVision Tex t Vision Plan ($2.25 )
chkM edica l Text Med ica l Plan ($55.52)
r Vision Plan (5225)
lblTot al Text Tota l month ly cost:
[ Medical Plan (555.52) txt Total Reac!O nly True

otal monthly cost :

) Hand les _
Priva te Sub check Box_ Check edCha nged( ...
kedC hange d,
chkD rug.C hecke dChan ged, chkD ental. Chec
edica l . Check edCha nged
chkV ision. Check edCh anged , chkM
Di sum As Doub le
If chkD rug. Check ed Then
urn+ = 39.15
End If
If chkD enta l.Che cked Then
urn+= 10 . 81
End If
If chkV ision .Chec k ed Then
.3 Uffi += 2 .2 5
End If
If c hkMe dical. Chec ked Then
sum += 55 . 52
End If
t x tTo t al.Te xt Form atCur renc y(sum )
End Sub

Comments
a single item fro m a list of options.
1. Both list boxes and rad io butto ns can be used to select
short lists (at mos t seven optio ns)
As a rule of thum b, rad io butto ns should be used with
nd list boxes shou ld be used with. long lists.
es unchec ked. Such is not the case
2. When the u er clicks on a checked check box, it becom
cked with code or by clicki ng on
with a radio button . A radi o butto n can only be unche
anoth er radio butto n.

Pr~ctice Problems 4.4

1. What is the difference betwe en a set of check


boxes attach ed to a group box and a set of
radio button s attach ed to a group box?
Why i it esse nti a l for the sets to
2. S uppos e a form con tains tw o se ts of rad io butto ns.
co nce rn a pp ly to sets of ch eck
be co nta ined in sepa rate group boxes? Do the sa me
boxes?
G ive two ways to guara ntee that the
3 Suppose a group box contai ns a et of rad io butto ns.
u er will se lect one of the radio butto ns.
4.4 Inp ut via U ser Se lecti ons • 151

EXERCISES 4.4

In Exercise s 1 through 8, det ermin e the effect of setting the property to


the va lu e
shown.
1. GroupBo xl. Text = "I ncome"
2. CheckBo xl .Checked True
3. CheckBo xl.Check ed False
4. CheckB oxl.Text = "&Vanil la"
5. RadioBu ttonl. Checked = False
6. txtOutp ut . Text = lstBox.T ext
7. RadioB uttonl.T ext = "Clear &All"
8. RadioBu ttonl .Checked = True

In Exercise s 9 through 12, write one or more lines of code to carry out the task.
9. Set the caption for Rad ioButton1 to "Yes".
10. C lear the small rectangu lar box of CheckBox 1.
11 . G uarantee that CheckBo x1 is checked .
12. Turn off RadioBu tton2.

In Exercise s 13 and 14, determin e the state of the two radio buttons after Button
1 ts
clicked.
13. Private Sub Buttonl _ Click( ... ) Handles Buttonl . Click
RadioBu ttonl.Ch ecked True
RadioBu tton2.Ch ec ked = True
End Sub

14. Private Sub But t onl_ Click( ... ) Handles Buttonl .Click
RadioBu ttonl.Ch ecked False
RadioBu tton2. Checked = False
End Sub

15. Suppose that a group box has two radio buttons attached to it. lf the sta tement
GroupBo xl .Visib le = False

is executed , will the rad io buttons also vanish ? Test your answe r.
16. Create a form with two group boxes, each hav ing two radi o buttons attached
to it. Run the
program and confirm that the two pair of radio buttons ope rate indepe ndently of
each
other.
17. A compute r dealer offers two basic compute rs, the Deluxe ($1000) and the
S uper ($ 1500).
The custome r can order any of the following add itional options: upgraded video
card
($200) , internal modem plus Wi-Fi ($30), or 1 GB of added memory ($120) . Write
a pro-
gram that compute s the cost of the compute r system se lected. See Fig. 4.13.
18. Write a program to book an airline flight. See Fig. 4.14 on the next page. If the sa me
ai rport
is selected from the two list boxes, the user shou ld be informed immedia te ly that the depar-
ture and arriva l airports must be different. If no airport has been selected from one or
both
of the list boxes when the button is clicked, then the user shou ld be to ld what informat
ion
must be supplied. Use message boxes to inform the user of problems.
15 2 • Chapte 4 Decisions

From : To :

Super
AUS AUS
" Deluxe
mal BOS
BWI BWI
[{] Upgraded Video Card DFW DFW
JFK JFK
LAX
lntemal Modem Wi-Fi MIA
ORD
1 GB additiona l memory SFO
1. /

1.320.00 You are flying from BOS to LAX.


Total Cost :

Possibl e outcom e of Exercis e 17. FIGURE 4.14 Possibl e outcom e of Exercis e 18.
FIGUR E 4.13
preside ntial candid ates. See
19. W rite a program that a llows you to vote for one of two
sho uld d isplay your vote.
Fig. 4.1 5. When the Cast Vote button is clicked on, the tex t box
for neither ." hou ld
In the event that neither radio button is on, the senten ce "You voted
appear in the text box.

a.. V te for O ne l= J @) I. .n ~I a_. residential El ig ibility

Natural bom citizen? -year U.S. resident?


President
Yes o Yes
o Kennedy
No No
Nixon

Date of Birth : 12122/1976


[ Oear Selected Candidate ]
Detennine Bigibility to Run
for President in 2012
l Cast Vote j
You voted for Kennedy . You are eligible to run for president in 2012.

Poss ible output for FIGURE 4.16 Possibl e o utp ut for Exercis e 20.
FIGUR : 4.15
Exercis e 19.
states that "No Per-
20. rticle II , Sectio n 1, C lause 5 of the Constitution of the United States,
S tates at the time of the
s n except a natural bo rn C itizen , o r a C itizen of the United
nt; n ith r ha ll any
dopt ion of this Consti tution, hall be eli gibl e to the Office of Preside
atta ined to the Age of thirty fiv e Yea rs,
Perso n be eligible to that Office who shall not have
" Write a progra m that deter-
nd been fourtee n Years a Reside nt within the United States.
in 2012. (Note: A nat-
' ines if a person is eligib le to run for Pres ident of the United State
t he U.S. gove rnmen t. A
ural born citizen is a per on who is born within the jurisdic tio n of
Day, 1/2 1/2013 .) See
2012 candid ate for preside nt must achi eve age 35 by Inauguration
Fig. 4.16. Hint: Use the AddYears method.
the section . When the
21. rite a program that u es the form in Fig. 4. 8 at the beginn ing of
has been made from both
button is clicked, the program sh ould first determ ine if a selecti on
sho uld appear telling the
the list box and the group of radio button . If no t, a message box
ns have been made, the
ser which types of selectio ns have not been made. If both selectio
essage "Inform ation Processed" shou ld be displayed.
4.4 lnput v ia User Se lectio ns
• 153

22. Wr ite a program that uses the form in Fig. 4.8


at the begin ning of the secti on. Whe n the but-
ton is clicked, the program should print the name
s of the comp uter languages studied. lf no
chec k boxes have been chec ked, the sente nce
"N o languages studied." should be print ed.
23. Figur e 4.17 shows an item from the 2008 U.S.
Indiv idual Inco me Tax Retu rn. Write a pro-
gram whose form re embl es item 39a. The prog
ram should look at the four ch ck boxes and
display in the large tex t box at the righ t of the
item the num ber of boxe chec ked.

39a Chec k { I ' You were bom be ore January


2. 1944. I Blind .l Total boxes
if: --, Spou se was born before January 2, 944,
::l Blind. f checke<l ..,.. 39a
FIGURE 4.17 Item 39a from Form 1040 of the 2008 U.S.
Indiv idual Incom e Tax Retu rn .

24. Writ e a program to spec ify the foregrou nd


and backgro und colors for a labe l cont ainin g the
word s VISU AL BAS IC. See Fig. 4.18. If the
sa me color is se lected from the two group
boxes, the user should be informed immediate
ly that the two colors mu t be different. If no
color ha been selec ted from one or both of
th e group boxes when the butto n is clicked,
then the use r should be to ld wh at informati
on must be supp lied. U se message boxe s to
inform the user of prob lems.

a J Co lo rs

Foreground Color D::; Sport and Hea lth Club


Background Color
White f White Membership Extras
o Yellow Yellow 10 AcU ( 1 ~)
Red
riJ Tennis privileges
Red
Senior (65+)
Blue o Blue
0 Private locker
~ Laundry service

VISUAL BASIC Calcu late


Month~· Fee
Monthlyfee: S15G.

FIGURE 4.18 Possi ble ou tcom e for Exerc ise 24.


FIGURE 4.19 Poss ibl e outco me of Exe rcise 25.

25. The bas ic mon thly cost of a membership


in a spo rt and healt h cl ub is $ 100 for adult s and
75 for senio rs. Ava ilable extras cost $25 each
per mon th . Writ e a program that uses the
form in Fig. 4.19 to calcu late a member's mon
thly fee. Before calcu lating the fee, make sure
that a membersh ip ca tegory has been selec ted.

Solutions to Practice Problems 4.4


1. With rad io button s, at mos t one button
can be on at any give n ti me, whereas seve ra
checked simul taneo usly. l check boxes ca n be
2. W ith two se ts of radi o button s, you wou ld
like to make two se lectio ns. Howeve r if th e two
gro up box, th en at most one rad io button can se ts arc in th e sa me
be on at any tim e.
S ince severa l chec k boxes ca n be checked at
any tim e, yo u need n't have th is conce rn with
Howe ve r, the two sets of check boxes are usua check boxes .
ll y placed in sepa rate gro up boxes to impro ve
the visua l effect.
3. Metho d 1: Make one of th e radi o button s
the defau lt radi o button; that is, se t its C hecke
des ign time. d prope rty to True at
Metho d 2: Place the code tha t refers to the radi
o butto ns in an If hlock that d isplays a messa
button in the gro up box has been checked. ge when no radi o
154 • Chapt r 4 Decisions

CHAPTER 4 SU MMARY
as dete r-
r with each num ber from 0 thro ugh 255
1. T he fu ncti on Chr associates a characte
m ned by the ANS I table. The func tion
Asc is the inverse of the Chr func tion .
<> ,<= , and >=.
2. T e relational operators are <,> ,=,
, Or, and Not.
3. T e prin cipa l logical operators are And
ators (ar ith-
g literals, variables, func tion s, and oper
4. A condition is an expr essio n invo lvin
evaluate d as e ither True or False.
m tic, relat iona l, or logical) that can be
e.
of Boolean data type is e ithe r True or Fal
5. T e valu e of a vari ab le or expression
r more con-
depe ndin g on the truth va lues of on o
6. A n If block decides wha t actio n to take If state men t
ion, the If, Elself, and Else parts of an
d tions. To allow several courses of act
can cont ain othe r If state men ts.
es-
actio ns depe nd ing on the value of an expr
7. Select Case block selects from one of several selec tor.
sion, called the selector. The entri es in the
value lists should h ave the same type as the
to se lect
s prov ide an effic ient way for a prog ram
8. List boxes, radio buttons, and check boxe
amo ng a set of possible opti ons.

CHAPTER 4 PROGRAMMING PROJECTS


cost on e-
e's Equ ipm ent Ren tal. Full-day rent als
1. Tab le 4.9 gives the price sche dule for Eddi le 4.9 in a list box whe n
and- a-ha lf time s half-day rentals. Wri te a program that displays Tab
o n the item
displays a bill in anot her list box based
an appr opri ate butt on is clicked on and a $30. 00 depo sit. A
tamer. The bill shou ld inclu de
1umber and time period chos en by a cu
sam p le outp ut is show n in Fig. 4.20.

im:J!IS:W Price schedule for Eddie's Equipment Rental.


Full-Day
Half-Day
Piece of Equipment
16.00 $2 4. 00
1. Rug cleaner
$12.00 $18.00
2. Lawn mower $30.00
$20.00
3. Paint sprayer

enta l
l = I @) l,_.a -..~J
aJ We lcome to Edd ie's Eq uipm ent

Ha l :::- d ay Full - d a:'l'


Pric e o ::: ::: qui p roen,;
$ 16 . 00 $2 4.00
1 . Rug cl ea n e r
[ Display Renta l Rates l 2. Lawn mow er
3. Pai n t .;p raye r
$12 . 00
$20 _00
$1 3 _00
$30. 00
--- ~enta l
~ece ip t ::r om :::ddi e'.; :::qui proe nt
Select an item (1. 2. or 3): 2
rent a l )
F Lawn mow er: $ 18 _00 ( Full day
Select a duration (H or F): . 00
J>e p osi, ;: $30

l Display Customer Bill J Icta l : $48 .00

ing Project 1.
FIGURE 4.20 Form layout and sample outp ut for Programm
Prog ramm ing Projects
• 155

2. The Ame r ican Hea rt Asso ciati on sugg


ests that at most 30% of the calo ries in our
from fat. Alth oug h food labe ls give the diet come
num ber of calo rie and amo unt of fat per
they ofte n do not give the perc enta ge serv ing,
of calo ries from fat. This perc enta ge ca
lated by mult iplying the num ber of gram n be calc u-
s of fat in one serv ing by 9 and divi ding
ber by the tota l num ber of calo ries per that num -
se rvin g. Wri te a program that req uest s
num ber of calories per rving, and the the name,
grams of fat per se rvin g as inpu t, and tells
the food meets the Ame rica n H eart Asso whe ther
ciation reco mm end at ion . A sa mp le run
in Fig. 4.21. is show n

a... Ana lyze Mort gage l = I @) lj..-t.J J


Name of food : Lov..fat milk Amount of loan : 2 00

Calories per serving : 120 Interest rate :


(such as 5.25) 6
Grams of fat per serving : 5
Duration in months : 360

Compute %Calories from Fat Artalyze

37. 50'/~ calori es from fat M onth ~· payment : 1.438 .92


exceeds HA. recommendation
Total interest paid: S278 .011 .65

FIGURE 4.21 Poss ible outp ut for Prac tice


FIGURE 4.22 Possible outp ut for Prac tice Prob lem 3.
Prob lem 2.

3. Wri te a program to analyze a mortgage


. See Fig. 4.22. The use r should ente r the
the loan , the annu al perc enta ge rate of amo unt of
inte rest, and the dura tion of the loan in
Whe n the user click s on the butt on, the mon ths.
info rma tion that was ente red hould be chec
make sure it is reaso nab le. If bad data have ked to
been supp lied, the use r should be so advi
Oth e rwise, the mon th ly paym ent and the eel.
tota l amo unt of inte rest paid should be disp
The formu la for the mon thly paym ent is layed.

pay men t=p *r/( 1- (1 +r) " (-n) ),


where /J is the amo unt of the loa n, r is the
mon thly inte res t rate (ann ual rate d ivide
give n as a num ber betw een 0 (for 0 perc d by 12)
ent) and 1 (for 100 perc ent) , and n is the
of the loa n in mon ths. The formula for dura t ion
the tota l inte rest pa id is
tota l inte rest = n *pay men t - jJ.
4. Table 4.10 gives the 2008 federal inco
me tax rate schedule for sing le taxpayers.
gram that req uests taxa b le inco me and calc Wri te a pro-
u late the fed eral inco me tax.

lfi!:lllll•l 2008 federal income tax rates for single taxpayer


s.
Taxa ble Inco me Ove r But Not Ove r The Tax Is Of Amo unt Ove r
0 $8,025 LO% $0
8,025 $32,550 $802 .50 + 15% $8,025
$32, 550 $78,850 $4,4 81.25 + 25% 32,550
$78,850 164,550 $16,056.25 + 28% $78,850
164,550 357,700 40,052.25 + 33% $ 164,550
$357, 700
103,791.75 + 35% $357,700
Cha ptet 4 Dec ision s
156 •
ts of the quadra t ic equ atio n ax + bx
2 +c= 0
m to dete rmi ne the real roo
5. W rite a progra ing the roo ts, ensure
valu es of a, b, and c. Befo re find
(w ere a o:F 0) afte r req uest ing the ing on whe the r the
is non zero . [No te: The equ atio n has 2, 1, or 0 solut ions depend
tha t a solution s are
- 4 ':'a* c is pos it ive, zero , or nega tive . In the first two cases, the
va lue of b/\2 .] Tes t the pro-
giv en by the quadra tic formula (-
b ± Ma th.S qrt (b/\ 2- 4 *a* c ))/ (2* a)
ffic ients:
gram with the fo llow ing se ts of coe

a= 1 b = - 11 c = 28 Solutio ns are 4 and 7


a= 1 b= -6 c = 9 Solutio n is 3
a= 1 b= 4 c = 5 N o solution

le 4.11. U se the form in


er from the rest aura nt menu in Tab
6. Wri te a progra m to place an ord and bec omes visible
4.23, and writ e the prog ram so tha t eac h gro up box is invisible
Fi . ked , the cos t of
its corr espo ndi ng che ck box is checked. Aft er the but ton is clic
on ly whe n first radi o bu tton in
te : The C hec ked pro per ty of the
t e mea l sho uld be calcu lated. (No ran tees tha t a selec-
e in its Pro perties window. Thi s gua
e ch gro up box sho uld be set to Tru mea l is calculat ed,
mad e in eac h visible gro up box . Of course, whe n the cos t of the
ti n is
be con side red. ) See Fig. 4.24 .
on ly the visible gro up boxes sho uld

m:ln!JIII Menu of Oceanside Burgers & Fries.


Dri nk s
Frie s
Bur gers
ma ll (2.3 9 ) Sod a (1 .69 )
Reg ular (4.19) Bot tled Wat e r ( 1.49 )
Medi um (3 .09)
w/ cheese (4.79)
Large (4 .99)
w/ baco n (4.79)
w/ baco n and cheese (5.39)

a~ M enu

Choices for Burgers

o Regu lar ( .1 9)
L Burgers w/ cheese ( .79)
w/ bacon ( .79)
w/ bacon and chee se (5.19)

Choices for Fries


Small (2.39)
f) Fries Medium (3. 9)
Larg e ( .99)

Compute Cost
Choices for Drinks of Meal
o Soda (1.69)
[ ] Drinks
Bottled Wat er (1. 9) Cost of meal:

6.
FIGURE 4.23 For m for P rogr amm ing P roje ct
Prog ramm ing Proje cts
• 157

Choices for Burgers

Regu lar ( .19}


.J. Burgers o w/ cheese ( .79)
w/ bacon f ..7 }
lJ •.v/ bacon and cheese (5.l9}

Fries

Choices for Drinks Ci:•mpute Cost


of Meal
Ill Drinks Soda (1.S9)
o Bottled 1Nater p .49) Cost of meal : 6. a

FIGURE 4.24 Poss ible outco me of Prog ramm ing Proje ct


6.
7. College Admissions. The ad miss ions offic
es of colleges often rely on a poin t system.
syste m simil ar to A poin t
the one in Fig. 4. 25 on the nex t page is used
Writ e a program that allows an ad miss ions by a large state univers ity.
office r to dete rmin e whe ther an appl ican
should be adm itted. The numbers in brackets t
give the poin t coun t for each respo nse. The
GPA score ente red into the text box at the
top of the form should be from 2.0 to 4.0.
poin t va lue in the brackets to the right of The
the text box is 20 times the GPA and shou
appe ar auto matically after the focus leaves ld
the tex t box. A total of at most 40 poin ts ca
earn ed for the responses be low the line. The n be
prog ram should calculate the total score and
then adm it an app lican t whose score is at least
100.
8. Man y emp loyers offer their employees a retir
eme nt pen ion plan [kno wn as a 401 (k) plan
Reti reme nt pens ion plans are usually bene ].
ficia l to an employee, since they force
emp loyee to save. In add ition, emp loye rs often the
matc h part of the emp loyee's cont ribu tion;
therefore the employee rece ives free mon ey.
(a) Writ e a program that uses the form
in Fig. 4.26( a) on the next page to ask an emp
whe ther or not they would like to participa loyee
te. Whe n the program starts, the check box
should be unch ecked and the text box shou
ld be empty. If the employee clicks on the
butt on with out checking the chec k box,
the state men t "You have opte d out of the
retir eme nt plan ." should appear in the tex t
box.
(b) Writ e a prog ram that uses the form
in Fig. 4.26 ( b) to ask an emp loyee whe ther
they would like to parti cipa te. Whe n the prog or not
ram start s, both radio butto ns should be
unch ecke d and the text box hould be emp
ty. If the employee clicks on the butto n
with out chec king a rad io butto n, the mess
age "You must make a se lection." shou ld be
disp layed in a message box. O therwise, one
of the two state men ts appear ing in the text
boxes in Fig. 4.26 (a) and (b) should appea
r in the tex t box.
Note : In part (a), optin g out is the default optio
n. A stud y 1 has show n that employees are
more likely to opt-i n for the retiremen t plan
whe n the question is posed as in part (b).
1
Gabr iel D. Carr o ll, Jame s J. C hoi, Dav id
Laibson , Brigi tte Madr ian, and Andr ew
Defaults and Active Decisions, NBER Wo rking Metr ick, OjJtimal
Pape r no. 11 074, 2005 .
158 • C hapt e r 4 Dec ision s
..,.
l = l[§)
IIJ U iversity Adm issio ns Poin t System

GPA Score : 3.5 [ 70] [ Calculate Total Score I


Difficulty of Curriculum Total Score : 134 I
S T High School Quality
-2 [-4) 2 [4) Admitted
400-920 [0]
930-1 000 [6)
0 [0) 3 [6) I

-1 [-2) 0 3[6] ~
I
0 1010-1190 [10) 1 [2) 0 4 [8)
0 [0) 4 [8)
1200-1350 [11 )
2[ 1 5 [10] 1 [2)
1360-1600 [12]

Maximum of 40points
Miscellaneous
Essay
eography
Very good [1 ] Socioeconomic
~ State resident [1 0) disadvantage [20)
o Excellent [2]
Underrepresented
I
state county [6) Outst anding [3)
Men in nursing [5}
J Underrepresented
state [2)
Leadership and Service a Scholarship athlete [20)
Alumni State [1 )
J Legacy (parents , Regional [2) Provost's discretion [20]
~ stepparents ) [4]

Other (grandparents. ol National [5]


'-- siblings) [1]

7.
FIGURE 4.25 Sam ple run of Prog ram min g Proj ect

a... Retirement Plan


a... etire 1ent Plan
Enroll in retirement plan?
l] Chec k this box to enroll in retirement plan.
- Yes Record
Decision
Record Decision Q No

plan .
You have opted out of the retirement
You will be enrolled in the retirement plan.

(b)
(a)
of Prog ramm ing Proj ect 8.
FIGURE 4.26 Poss ible outp uts for part s (a) and (b)
G en er al Pr oc ed ur es

5.1 Function Procedures 160


• User-Defined Fun ctio ns Hav ing O ne
Par ame te r • Use r-Defined Fun ctio ns
Sev eral Para met er • Use r-D efin ed Fun H av ing
ctio ns Hav ing N o Para met ers • User-D
Boo lean-Va lued Fun ctio ns efined

5.2 Sub Procedures, Part I 175


• Defining and Cal ling Sub Proced ures
• Var iables and Express ions as Arg ume
• Sub Procedures Calling Oth er Sub nts
Proced ures
5.3 Sub Procedures, Part II 190
• Passing by Va lue • Pa ing by Referen
ce • Sub Proced ures tha t Ret urn a Sin
Value • Lifetime and Sco pe of Var iabl gle
es and Con stan ts • Debugg ing
5.4 Modular Design 202
• Top -Do wn Design • Stru ctur ed Pro
gram min g • Adv anta ges of Structur ed
Progra mm ing • Obj ect- Ori ente d Prog
rammin g • A Releva nt Quo te
5.5 A Case Study: Weekly Payroll 206
• Designing the Weekly Payroll Program
• Pseudocode for the Disp lay Payroll
Procedure • Wri ting the Weekly Pay Eve nt
roll Program • The Prog ram and the
Interface Use r

Summary 214

Programming Projects 214

159
160 • Cha pt r 5 G enera l Procedures

5.1 Function Procedures


used to break
two dev ices , Fun ctio n pro ced ure s and Sub pro ced ure s, tha t are
Visual Basic has To d istingui sh the m from
blems to be so lved one at a tim e.
com plex problems into sma ll pro pro ced ure s. Gen era l
du res, Fun ctio n and Sub procedures are refe rred to a gen eral
eve nt roce focus on the tasks
allow us to writ e and read a prog ram in suc h a way tha t we first
proce ures and can be
to acc omp lish eac h tas k. The y also elim inat e repe titi ve cod e
and later on how
reused in oth er programs. used . Sub procedures are
this sect ion we sho w how Fun ctio n proced ures are defi ned and
In
prese ted in Sec tions 5.2 and 5.3. ion s are like min ia ture
fun ctio n . ln one resp ec t, fun ct
V sua l Basic h as man y bui lt-in out put . Som e fun ctio ns
y process the inp ut, and they h ave
pro gra ms. The y rece ive inp ut, the
in Tab le 5.1.
we e cou nte red earl ier a re liste d

15101. Some Visual Basic built-in functions.


Inp ut Out put
Fun ctio n Exa mpl e
num ber num ber
lnt lnt( 2.6) is 2 string
num ber
C hr Chr (65) is "A" nu mber
strin g
Asc ("A pple ") is 65 strin g
Asc 12,3 45. 6 num ber, num ber
Form atN umb er Form atN umber(I 2345 .628, 1) is

ays a sing le value. A


seve ral va lues, the out put is alw
!tho ugh the inp ut can con si t of le 5.1, we say tha t
said to retu rn its out put. For in tan ce, in the first exa mpl e of Tab
fun ctio n is eses are call ed arg ume nts.
e 2. The items inside the par enth
the lnt functi on retu rns the valu th fun ctio n has two argu-
5.1 h ave one argumen t and the four
Th first thre e fun ctio ns in Tab le ress ions. Variab les are the
ents can be liter a ls (as in Table 5.1 ), vari ab les, or exp
me ts. A rgum use of var iab l sa nd
mon type s of argu men ts. The fo llow ing lines of cod e illustrat e the
mo t com
lnt fun ctio n .
exp ress ion as argu men ts for the

Dim n uml As Dou ble 2.6


Int (num l) 'va ria ble as an arg ume nt
Dim n um2 As Dou ble

Dim num l As Dou ble 1.3


ent
Int (2 * num l) 'ex pre ssio n as an arg um
Dim num2 As Dou ble
e of num l to
of cod e abo ve is said to call the lnt fun ctio n and to pass the valu
T he seco nd line
th ' func tion. of our ow n. These n ew
ctio n , we can defin e fun ctio n
ln add itio n to using buil t-in fun used in the ame way as
ed Fun ctio n pro ced ure s or use r-de fine d fun ctio ns , are
fun ctio ns, call ngle out put tha t ca n be
fun ctio ns. Lik e bui lt-in fun ctio ns, Fun ctio n procedures hav e a si
built-in fun ctio ns.
. Fun ctio n pro ced ures are used in exa ctly the sam e way a bui lt-in
of any data type
by fun ctio n blocks of the form
F ncti on procedures are defined
As Typ el ,
F~nction Fun ctio nNa me( ByV al var l
) As Ret ur nDa taT ype
ByV al var 2 As Typ e2 , ...
sta t eme nt (s)
Vide oNo te
Ret u r n exp res sio n
Func t ion proceJures
En d Fun ctio n
5.1 Function Procedures
• 161

The variab les appea ring in the h eader a re called param


eters. If the word ByVa l is o mitted
wh en you type in the h eade r, ByVa l will be inse rted autom
atica lly by the Code Edito r when you
move th e c ursor away fro m t h e h eade r. Fo r no w, think of
ByVa l as a keywo rd an a logous to Dim;
that is, it declares a para me te r to be of a certa in type a nd
set as ide a po rtio n of memo ry to h o ld
it va lue. The scope of each param eter i limite d to
its func tio n block, as is a ny va riab le
declared inside the Func tio n proced ure.
Functi on names h ould be sugges tive of the role petfo rmed
and must confo rm to the rules fo r
na ming variab les. By conve ntio n, functio n names begin with
an uppercase letter. Retum DataType,
which specifies the type of the output , will be one of S tring,
Intege r, Do uble, Date, Boolean , and so
on . In th e preced ing gene ra l code, the Rerum statem ent specifi
es the output , which must be of type
RetumDataT ype. Functi o n proced ures can conta in seve ra l Return
sta te ments, and mu t conta in
a t least o n e.
Func tio n proced ures are typed directl y into the Code Editor
o utside an y othe r proced ure.
Afte r yo u type the h eader and then press the Enter key, the
edi tor autom atica lly inse rts the line
"End Func tio n " and a bla nk line sepa rating the two lines
of code. Also, the smart ind enting fea -
t ure of the Code Edi tor autom atica ll y indent s a ll lines in
the b lock of code be tween th e h eader
and "En d Fun c tio n " sta te me nts.

User-Defined Functions Having One Parameter


The fo llowin g two Funct io n proced ures h ave jut o ne pa
ra me ter. (Figure 5.1 ide ntifies the dif-
fe rent parts of the first func tio n 's h eade r.)

Funct ion FtoC( ByVal t As Doubl e ) As Doubl


e
'Conv ert Fahre nheit tempe rature to Celsi us
Retur n (5 I 9) * (t - 32)
End Funct ion

Funct ion FirstN ame( ByVal fullNa me As Strin


g ) As Strin g
'Extr act the first name from a full name
Dim firstS pace As Integ er
firstS pace = fullNa me.In dexOf ( " " )
Retur n fullN ame.S ubstri ng(O, firstS pace)
End Funct ion

function declaration data type of data type of


name keyword parameter parameter value returned

~~ ~ / /
Funct ion FtoC( ByVal t As Doubl e ) As Doubl
e
FIGURE 5.1 Heade r of the FtoC Functi on proced ure.

Example 1 Th e fo llow ing progra m uses the Funct io n proced ure


FtoC . The fourth
line o f the btnCo n ve rt_C lic k eve nt proced ure, celsiu
sTem p = FtoC (fahre nheitT emp) ,
ca lls the func tio n FtoC. The va lu e of the a rgume nt fahren
heitTemp is a sign ed to the pa ra-
me te r t in the Func tio n proced ure h eade r. (We say tha
t the va lu e of fahr enheit Temp is passed
to t h e pa ra m e te r t.) A fte r the Func tio n proced ure does
a ca lcu la ti o n using th e para me te r t,
162 • Chap te r 5 G e nera l Proce dure

n FtoC and is ass igned to the var iab le


the calcu lated va lu e is the outpu t of the fu nctio
celsiusTemJJ.

OBJECT PROPERTY SETTING


a C Jrwert Fahre nheit to Celsius ~~ ~ ~ ~ frmCo nve rt Text Con ve rt Fahre nheit
to Celsiu s
Tempe rature (Fahrenheit) Text Temp e ra ture
lblTem pF
(Fahr enhei t)
Convert to Celsius txtTe mpF
btnCo nvert Text Con ve rt to
Ce lsius
Temperature (Celsius) Te mpera ture
lblTe mpC Text
(Ce lsius)
txtTe mpC ReadO nly True

Hand les btnC onve rt.Cl ick


Priv te Sub btnC onve rt_ Click ( ... )
Doub le
Di fah r enhei tTern p, celsi usTe rnp As
)
fa renh e itTern p = CDbl (txtT ernpF .Text
ce l sius Ternp = FtoC (fahr enhe itTer np)
tx t Ternp C .Tex t = CStr (cels iusTe rnp)
repla ced with the sinu le line
'Note : The abov e fo r l'nes can be
ernpF .Text )))
tYtTe rnpC .Text = CStr (FtoC (CDb l(txtT
End ub

Doub le
Func t ion FtoC ( ByVa l t As Doub le ) As
Cels ius
'Con vert Fahr enhe it temp eratu re to
Re t urn (5 I 9) * (t - 32)
End Func tion
the butto n.]
[Ru , type 212 into the text box, and then click on

a Conve rt Fahre nhe it to Celsiu s l = I @) lr -~ ·J

Temperature (Fahrenheit) 212

Convert to Celsius

Temperature (Celsius)

FirstN ame. The fifth line


The follow ing program uses the Func tion proced ure ,
rstNa me. Text = First Nam e ( fullN ame)
of the btnO eterm ine_C lick event procedure, txtFi tion proce dure.
eter fullName in the Func
pas es the value of the argum ent fullName to the param
h a the same nam as the argum ent pa ed to
A lthough the parameter in the Func tion proc dur
5.1 Func tion Proced ures
• 163

it, th ey are d iffe ren t va riable s. This is an alogo


us to the situa tio n in whic h varia bles in two
e n t eve n t proce d ures h ave the same n ame, diffe r-
but separate ident ities. .
OBJECT PROPERTY SETTING
II _. Extract Firrt Nam e GJ I ~ IE![] fr mFirstN ame Tex t Extract First Name
Full name : lblNa me Tex t Full name :
txtFullName
Determine Rrs:t Name btn Determine Tex t Determine First
Name
Rrst Name : lblFirstName Tex t First Name:
tx tFirst Name Read O nly True
Priv ate Sub btnD eterm ine Clic k( ...
) Hand les btnD eterm ine.C lick
'De ermi ne a pers on's firs t name
Dim fullN ame As Strin g
fullN ame = txtFu llNa me . Text
txtF irstN ame .Tex t = First Nam e(ful
lNam e)
End Sub

Func tion First Nam e( ByVa l fullN ame


As Strin g ) As Strin g
Bxtr act the firs t name rom a tu
1 name
Dim first Spac e As Inte ger
first Spac e = fullN ame. Inde xOf( "
")
Retu rn fullN ame . Subs tring (O, first
Spac e)
End Func tion

[Run , type Fran klin Dela n o Roosevelt into


the text box, a nd then clic k o n the butto n.]

Full name : Franklin Delano Roos e ve ~

Determine First Name

Rrst Name : Franklin

In gen e ra l, cons id er a ca lling sta te me n t of


t he fo rm
Dim varl as Type l = Func tionN ame( arg)
whe re the Func t io n proce d ure h ead er h as
t h e fo rm
Func tion Func tionN ame( ByV al par
As para mete rTyp e) As Retu rnDa taTy
pe
T h e varia bles arg and par must have the
sa me d ata type , and Type l mu t be the
ReturnDat aType. In man y cases , code is eas ie r to sa me as
read whe n the same na me is used fo r the argu-
me n t a nd the pa ra me te r it is passe d to. A ltho
ugh they n eedn 't h ave the same n a me, they
h ave the same d a ta t ype . 1 must

1
There arc excep t ions to this rule. For instan ce,
if Type 1 is a nume ric data type, then parameter
have any num eri c data type that is wider th an Type can
Type / . In this book , the two da ta types will alway
same. S imila r considerations app ly to Retum Data s be the
Type and Type I
164 • Cha pt r 5 G eneral Procedures

Parameters
Us .r-Defined Functions Having Several
seco nd func tion ,
The~ llow ing two Fun ctio n proc edur
es have more than one para mete r. In the
ema tical form ulas will look
one- lette r names have beenused fo r the para mete rs so that th e math
s of thes e para-
names are not desc ripti ve, the mea ning
fa mili ar and be easy to read. Because the
men ts.
mete r are spe lled out in com men t state
Dou ble
ble , ByV al hrs As Dou ble ) As
Fun ct i on Pay( ByV al wage As Dou ove rtim e
-and -a-h alf for
'Cal cula te wee kly pay with time
Dim amo unt As Dou ble
Sel :! ct Case hrs
C3. se Is <= 40
amou nt = wage * hrs
Ca se Is > 40
*wa ge* (hr s- 40))
amou nt= (wa ge* 40) + ((1. 5)
End Sel e ct
Re t urn amo unt
End Fun ct i on
,
As Dou ble , ByV al r As Dou ble
Func t. ion Futu reV alue ( ByV al p n As Inte ge r ) As Dou ble
ByV al c As Inte ger , ByV al

'F ~ nd the futu re valu


e of a bank savi ngs acco unt
osit ed
'p prin cipa l, the amo unt dep
of inte rest in deci mal form
'r ann ual rate
is com poun ded per yea r
'c num ber of time s inte rest
'n num ber of yea rs
Di m i As Dou ble 'int ere st rate per peri od
is com poun ded
Di m m As Inte ger 'tot al num ber of time s inte rest
i = r I c
m = c * n
Re turn p * ( (1 + i) m)
A

End Func t ion


ber of argu-
rs is called, there must be the same num
Whe n a func tion with seve ral paramete the ame (and
the data types of the argu men ts must be
me ts as parameters in the function . A lso, of the form
parameters. For insta nce, in a state men t
in the same order) as the data types of the
, arg3 , arg4 )
numVar = Futu reV alue (arg l, arg2
arg3 and arg4 must be of type Integer.
arg / and arg2 mus t be of type Double, and

proc edu re Pay. H ere the argu men ts


The follo wing prog ram uses the Func tion , they have the
ndin g parameters. As requ ired , however
have diffe rent nam es than the correspo
sa e data types.
OBJECT PROPERTY SETIING

ll W eekly Pay [3]1 @) I~ frmPay Text Weekly Pay


lb!Wage Text Hourly wage:
Hourly wage : txt Wage
lblH ours Text Hours worked:
Hours worked : txtH ours
btnC alcu late Text Calc ulate Earn ings for
Calculate Eamings for the Week the Wee k
lblEarning Text Earn ing:
txtEa rnings Read Only True
Eamings:
5.1 Func t io n Proc edur es
• 165

Priv ate Sub btnC alcu late Clic


k( ... ) Han dles btnC alcu late .Cli
•cal cula te a pers on's wee kly ck
pay
Dim hour lyW age, hour sWo rked
As Dou ble
hour lyW age = CDb l (txtW age. Tex
t)
hour sWo rked = CDb l (txt Hou rs.T
ext)
txtE arni ngs .Tex t Form atCu rren cy(P ay(h ourl yWa ge, hour sWo rked )
)
End Sub
Fun ctio n Pay( ByV al wage As Dou
ble , ByV al hrs As Dou ble ) As
•cal cula te wee kly pay with time Dou ble
-and -a half for ove r ime
Dim amo unt As Dou ble
Sele ct Case hrs
Case Is <= 40
amo unt = wag e * hrs
Case Is > 40
amo unt= (wa ge* 40) + ((1. 5)
*wa ge* (hr s- 40))
End Sele ct
Retu rn amo unt
End Fun ctio n
[Run, ente r valu es into the top two tex t
boxes, and click o n the butt on.]

11 _. W e€'kly Pay l = I @) I!""' t3 J

Hourly wage : 1 .50

Hours wori< ed:

( Calculate Eamings f or the Week J

E.amings : 688.75

Example 4 The follo wing prog ram uses the Func tion
respo nses show n whe n the prog ram is run, proc edur e Futu reValue. Wit h the
the prog ram com putes the bala nce in a savi
whe n $ 100 is depos ited for fi ve yea rs at ngs acco unt
4% inte re t co mpo unde d quar terly. Inte
times per year at the rate of 1% per inte rest is earn ed four
rest period. The re wi ll be 5-4, or 20, inte
rest perio ds.
OBJECT PROPERTY
11 _. Bank Depo sit GJ I ~ IE![] frmB ank
SETTING
Tex t Bank Depos it
Amount of bank deposit : lblA mou nt Tex t A mou nt of bank depo s it:
txtA mo unt
Annu al rate of intere st : lblRa te Tex t Ann u al rate of interes t:
txtR ate
Numb er of times interest lblN umC omp A utoS ize Fa lse
is compound ed per year:
Text N umb er of tim es interest
is co mpo unde d per yea r:
Number of years : txtN um Co mp
lblN umY rs Tex t N umb er of yea rs:
Compute Balance txtN umY rs
btnC omp ute Tex t Com pute Ba lance
Balan ce : lblBa lance Tex t Bala nce:
txtB a lance Read O nl y True
166 • Cha pte 5 Gen eral Proced ures

e.C lick
ck( ... ) Han dles btn Com put
Priv a l e Sub btnC omp ute_ Cli
a ban k dep osi t
'Fi n d the futu re val ue of
Am oun t.Te xt)
Dim p As Dou ble = CDb l (txt
Rat e . Tex t)
Dim r As Dou ble = CDb l (txt
Num Com p.Te xt)
Dim c As Inte ger = Cin t (txt
Num Yrs . Tex t)
Dim n As Inte ger = Cin t (txt
ure Val ue( p, r, c, n)
Dim bal an ce As Dou ble = Fut
Cur ren cy( bala nce )
txt ala nc e.T ext = For mat
End S b
Dou ble ,
al p As Dou ble , ByV al r As
Fun ct i on Futu reV alue ( ByV al n As Inte ger ) As Dou ble
ByV al c As Inte ger , ByV
a ban k sav ing s acc oun t
'Fin d the futu re val ue of
dep osit ed
'p pri nci pal , the amo unt
of int ere st in dec ima l form
'r ann ual rate
st is com pou nde d per yea r
'c num ber of tim es int ere
'n num ber of yea rs
Dim i As Dou ble 'int ere st rate per per iod
ere st is c omp oun ded
Dim m As Inte ger 'tot al num ber of tim es int
i "' r I c
m ., c * n
Re t urn p * ((1 + i) A m)
End •un ctio n
on .]
tex t boxes, and then clic k on the butt
[Run , type 100, .04, 4, and 5 into the

mount of bank deposit :

Annu al rate of interest :

Number of times interest


is compound ed per year:

Number of years : 5

Compute Balance

Balance : ~1 22.

Parameters
User-Defined Functions Having No
any para met ers.
A Fun ctio n procedu re needn't have

ral
on to dete rmine the tota l cost of seve
Example 5 The follo win g prog ram allo ws a per then clic ks on
The user ente rs the data for a pu rcha se in th top two text box es and
pL rchases. furt her pur chase . Aft er
use r can con tinu e to ente r data for
t e Purchase This Item butt on. The
5.1 Fu nctio n Proc edur es
• 167

all purc h ases hav e been mad e, the user


clic ks on the Calculate Total Cos t butt
sum of the cost s of the purc hases plus on to display the
th e sales tax.

OBJECT PROPERTY SETTING


o ... Total Cost [£]1 0 I~
frm Cost Tex t Tota l ost
Price of item: lblPri ce Tex t Price of item:
txtPri ce
Quantity purch ased : lblQ uant ity Tex t Q uant ity pu rchased:
txtQ uant ity
Purch ase This ~em
btnP urch ase Text Purc ha e Th is Item
btnC a lcula te Tex t Calculate Tota l Cos t
lblTo tal Text Tota l cost:
Calculat e Total Cost
txtTota l Read O nly True
Tota l cost :

Dim sub Tot al As Dou ble


Con st SALES TAX = 0.05

Priv ate Sub btnP urch ase Clic


k( ... ) Han dles btn Pur cha se.C
sub Tot al += Cos tOfi tem () lick
txtP rice .Cl ear ()
txtQ uan tity .Cle ar()
txtP rice .Fo cus ( )
End Sub

Priv ate Sub btn Cal cula te_ Clic


k( ... ) Han dles btn Cal cul ate.
Dim tota lCo st As Dou ble = Cli ck
sub Tot al + (SALES_ TAX * sub
txtT ota l.Te xt = For mat Cur Tot al)
renc y(to talC ost)
End Sub

Fun ctio n Cos tOfi tem ( ) As Dou


ble
Dim pric e As Dou ble = CDb l
(txt Pric e.T ext )
Dim qua ntit y As Inte ger =
Cin t (txt Qua ntit y . Tex t)
Dim cos t = pric e * qua ntit
y
Ret urn cos t
End Fun ctio n

[Run, ente r 5 and 2, clic k on the Purc


hase button, ente r 6 and 1, clic k on the
and clic k on the Calc ulate button.] Purc hase butt on,
$16 .80 is di splayed in the "To tal cost"
tex t box.

User-Defined Boolean-Valued Functio


ns
So far, the valu es retu rned by Fun ctio
n proc edu res hav e been num bers or
Fun ctio n procedu re can also retu rn a strin gs. However, a
Boo lean value-t hat is, True or Fa! e.
gram uses a Boo lean -valued func tion The follo win g pro-
and demonst rates an imp orta nt fea ture
dure : nam ely, a Functio n procedu re of Fun ctio n proce-
can con tain more than on e Retu rn stat
first Ret urn stat eme nt is enco unte red eme nt. Wh en the
, it dete rm ines the func tion valu e, and
cod e in the fun ctio n bloc k term inat es. the exec utio n of
168 • Cha pter 5 General Procedures

whe ther
lean -va lued functi on to dete rmi ne
Ex mple 6 The foll owing program uses a Boo e exa mpl es of vowel
t by the user is a vow e l wo rd- tha t is, con ta ins eve ry vowe l. Som
a word inpu ure IsVo welWo rd exam-
"d ialogue". The Fun ctio n pro ced
words are "seq uoia", "facetious", and l is fou nd to be missi ng.
the wor d for vow e ls one at a time and term inates whe n a vowe
ines
erm ine . Cli ck
_ Cli ck( ... ) Han dle s btn Det
Pri v te Su b btn Det erm ine
Di wor d As Str ing
per
wo d = t xtW ord .Te xt.T oUp
ord ) The n
If IsV owe lWo rd(w vow el."
t xtO u t pu t.T ext wor d & " con tain s eve ry
El o e eve ry vow el."
_xtO utp ut. Tex t wor d & " doe s not con tain
En If
End Sub
lean
al wor d As St rin g ) As Boo
Fun ctio n IsV owe lWo rd( ByV
If wor d .Ind exO f( "A" ) =
- 1 The n
Ret ur n Fal se
E d If
- 1 The n
I [ wor d .Ind exO f( "E" )
Ret ur n Fal se
En d If
- 1 The n
I wor d .Ind exO f( "I " )
Ret urn Fal se
E'ld If
- 1 The n
I f wor d . Ind exO f( "O" )
Ret u rn Fal se
En d I f
- 1 The n
If wo r d. Ind exO f ( "U" )
Ret u rn Fal se
nd I f
etu rn Tru e 'Al l vow els are pre sen t.
End Fun c tio n
box , and click on the but ton.]
[Ru n, type a word into the top text

a;} Vowe l Wor ds l·= I·@) I. .n. ~I


Enter a word : education

Det ermine WWord


Contains Every Vow el

EDUCATIO N cont ains every vow el.

Comments
you call the fun ct ion.
bee n defin ed, Inte lliS ens e helps
1. A fter a Fun ctio n proced ure has di plays the fun c-
ctio n' nam e, and Parame ter ln~
fun
Wo rd Complet ion helps type the the arguments, a
met ers. As soo n as you type in the left par enth esis precedi ng
tion 's para , names, and type s of
ing info rma tion abo ut the num ber
Pa ram eter lnfo ban ner appears giv
5.1 Func tion Proce dures
• 169

the param eters req ui red by the func tion . See


Fig. 5.2. A syn tax erro r occu rs if the num ber
of argum ents in the calli ng state ment is d iffere
nt from th e num ber of param eters in the
calle d Func tion pt:oce dure. A lso, h aving an argum
ent of a data type that can not be ass igned
to the co rrespond ing parameter is a sy ntax error
. Para mete r Info helps you preve nt both of
these kind s of syn tax erro r .

Priv ate Sub btnS alar y_ Clic k( . . . )


Hand les btnS alar y.Cl ick
Dim wage As Doub le = 15.7 5
Dim hrs As Doub le = 45
txtS alar y.Te xt = Form atCu rrenc y(Pa
y(l
I'P-ay::...(..:.:.
w_a_g_e_A_s_D
_o_u_b_l_
e.- h- r-s -A-s_D_o_u_b_le..,-)_A_s_D_o_u_b---:-1
1el

FIGURE 5.2 The P aram eter Info help featu re.

2. l n th is text, Func t ion proce dure names begin


with uppe rcase lette rs in orde r to d ist inguish
them from varia ble names. Like varia ble name
s, h owever, th ey can be wr itten with an y
comb ination of uppe rcase and lowe rcase lette
rs.

1. S uppose a program cont a ins the li nes

Dim n As Doub le , x As Strin g


lstO utpu t.Ite ms.A dd(A rc (n, x))

Wha t types of inpu ts (n umeric o r st ring) and


outp ut does the func t io n A rc have?
2. Dete rmin e the erro r in the foll o wing prog
ram.
Pr i vate Sub btnO utpu t_ Clic k( .. . )
Hand les btnO utpu t.Cli ck
Dim num As Inte ger = 3
Dim word As Strin g = "Vis ual"
Mess ageB ox . Show ("Th e thir d lett er
of the word is " &
Find Lett er(w ord, num) & " . ")
End Sub

Func tion Find Lette r(By Val num As


Inte ger, ByVa l word As Strin g) As
Retu rn word . Subs tring (num Strin g
1, 1)
End Func ti o n

In Exer c ises 1 t hrou gh 10 , deter mine the outp


ut displ ayed when th e butto n is click ed.
1. Priv ate Sub btnC onve rt Clic k( . . . ) Hand
les btnC onve rt . Clic k
'Con vert Cels ius to Fahr enhe it
Dim temp As Doub le = 95
txtO utpu t.Te xt = CStr (Cto F(tem p))
End Su b
170 • C hapt er 5 Gen eral Procedur es

ble) As Dou ble


Fun cti on CtoF (ByV al t As Dou
Retu r n ((9 I 5) * t) + 32
End Fun ctio n

... ) Han dles btnD ispl ay.C li ck


2. Priv at e Sub btnD ispl ay_ Clic k(
lot
Dim a cres As Dou ble 'Num ber of acre s in a park ing
acre s = 5
res) & "ca rs."
txtO u tput .Tex t "You can park abo ut" & Car s(ac
End Sub
ble) As Dou ble
Fun cti o n Cars (ByV al x As Dou
can be park ed
'Number of cars that
Retu r n 100 * x
End Fun ct i on
. ) Han dles btnD ispl ay.C lick
3. Priv at e Sub btnD ispl ay_ Clic k( . .
'Rul e of 72
Dim p As Dou ble
ulat ion grow th as a perc ent
p = CDb l(txt Pop Gr.T ext) 'Pop
ion wil l dou ble in " &
txtOutpu t.Te xt = "The pop ulat
Dou blin gTim e(p) & "ye ars ."
End Su b
x As Dou ble) As Dou ble
Fun ct i on Dou blin gTim e(By Val
a pop ulat ion to dou ble
'Es t ima te time requ ired for
'a t a grow th rate of x perc ent
Retu rn 72 I x
End Fu ncti on
s the num ber 3.)
(Ass ume the text box txtPopG r con tain
ick
. .. ) Han dles btnD eter min e.Cl
4. Priv ate Sub btnD eter min e_ Clic k( ble
Dim num One, numT wo, num Thre e, num Low est As Dou
n umO ne CDb l(txt One .Tex t)
n umTwo CDb l(txt Two .Tex t)
t)
n umT hree = CDb l(txt Thre e . Tex
ne, numT wo, num Thre e)
n umL owe st = Find Low est(n umO
est)
tx t Low est.T ext = CStr (num Low
End Sub
As Dou ble, ByV al y As Dou ble,
Func t ion Find Low est(B yVa l x
ByV al z As Dou ble) As Dou ble
bers den oted by x, y, and z
' Find the low est of thre e num
Dim low est As Dou ble
l owe st = x
I f y < low est Then
low est = y
En d If
I f z < low est Then
low est = z
En d If
Re turn low est
End Fun ctio n
n the num bers 7, 4, and 3.)
(Assume the first three tex t boxes co ntai
5.1 Fun ctio n Procedures
• 171
5. Pr iva te Sub btn Ou tpu
t_ Cl ick ( ... ) Ha ndl es
btn Ou tpu t.C lic k
Dim num As Int eg er = 27
If IsE ven (nu m) Th en
Me ssa geB ox. Sho w(n um
& 11
is an eve n nw nbe r. 11
)
Els e
Me ssa geB ox. Sho w(n um
& 11
is an odd nw nbe r . 11
)
End If
End Sub

Fu nct ion IsE ven (By Va


l n As Int eg er) As
Bo ole an
If n Mod 2 = 0 Th en
Re tur n Tru e
Els e
Re tur n Fa lse
End If
End Fu nct ion

6. Pr iva te Sub btn Di spl ay_


Cl ick ( ... ) Ha ndl es
Dim d btn Di spl ay .C lic k
As Da te = #12 /4/ 201
1#
txt Ou tpu t.T ex t = Mo
nth Ab br( d)
End Sub

Fu nct ion Mo nth Ab br(


By Va l d As Da te) As
Str i ng
Dim str As Str ing =
Fo rm atD ate Tim e(d , Da
Dim n As In teg er= teF orm at.L ong Da te)
str .In de x0 f( 11 11 )
Re tur n str .Su bs tri ng
(n + 1, 3)
End Fu nct ion

7. Pr iva te Sub btn Ou tpu


t Cl ick ( ... ) Ha ndl es
Dim tax btn Ou tpu t.C lic k
abl ein com e As Do ubl
e = 500 0
Me ssa geB ox. Sho w( 11 Yo
ur sta te inc om e tax
is 11 &
Fo rm atC urr enc y(S tat eT
End Sub ax( tax abl ein com e)) & 11 11
, )

Fu nct ion Sta teT ax( By


Va l inc om e As Do ubl
e) As Do ubl e
'Ca lcu lat e sta te tax
for a sin gle res ide
Se lec t Ca se inc om e nt of Co nn ect icu t

Ca se Is <= 100 00
Re tur n 0.0 3 * inc om
e
Ca se Els e
Re tur n 300 + (0. 05
* (in co me - 100 00) )
End Se lec t
End Fu nct ion

8. Pr iva te Sub btn Di spl


ay_ Cl ick ( ... ) Ha ndl
es btn Di spl ay .C lic k
'Tr ipl e a nw nbe r
Dim num As Do ubl e
5
lst Ou tpu t . Ite ms .Ad d(T
rip le( nu m) )
lst Ou tpu t.It em s.A dd (nu
m)
End Sub
u res
172 • Ch apt er 5 G ene ral Proced

Do ub le
al x As Do ub le) As
Fu nc tio n Tr ipl e(B yV
3
Dim num As Do ub le
Re tur n num * x
En d Fun cti on
lic k
nd les btn Ou tpu t.C
tpu t_ Cl ick ( . . . ) Ha
9. Pr iva t e Su b btn Ou
g "b eau ty"
Dim wo rd l As St rin
g = "ag e" wo rd2 ))
Dim wo rd2 As St rin e" & La st( wo rdl ,
ho w( Fir st( wo rdl , wo rd2 ) & "b ef or
Me ss a ge Bo x.S
En d Sub
g
As St rin g) As St rin
st( By Va l wl As St rin g, By Va l w2
Fu nc ti o n Fir
If wl < w2 Th en
Re tur n wl
El s e
Re tur n w2
En d If
En d Fu nc tio n
g
As St rin g) As St rin
st( By Va l wl As St rin g, By Va l w2
Fu nc tio n La
If wl > w2 Th en
Re tur n wl
El s e
Re tur n w2
En d If
En d Fu nc tio n
lic k
nd les btn Ou tpu t.C
tpu t Cl ick ( ... ) Ha
10. Pr iva te Su b btn Ou
er 84
Dim num l As In teg
er 96
Dim num 2 As In teg
2) Th en
If IsA nA (nu ml , num
Sho w ("A av era ge ")
Me s sag eB ox .
El se
ot an A av era ge ")
Me ssa geB ox .Sh ow ("n
En d If
En d Su b
As Bo ole an
Va l n2 As In teg er)
tio n IsA nA (By Va l nl As In teg er, By
Fu nc
>= 89 .5 Th en
If ((n l + n2) I 2)
Re tur n Tru e
Els e
Re tur n Fa lse
En d If
En d Fu nc tio n

, ide nti fy the err ors .


In Ex erc ise s 11 and 12 lic k
nd les btn Di sp lay .C
te Su b btn Di sp lay_ Cl ick ( ... ) Ha
11. Pr iva
'Se lec t a gr ee tin g
er
Dim an sw er As In teg
ox ("E nte r 1 or 2.
11 ) )

an sw er= Ci nt( Inp utB


r))
CS tr( Gr ee tin g(a ns we
txt Ou tpu t.T ex t =
En d Su b
5.1 Func t ion Proced ures
• 173

Fun ctio n Gree t i ng(B yVa l x As


Inte ger) As Inte ger
Retu rn "he lloh i ya" . Sub strin
g(5 * (x - 1) , 5)
End Fun ctio n

12. Pr ivat e sub btnD ispl ay _ Clic k (


.. . ) Han dles btnD ispl ay.C lick
Dim word As Stri ng
word = Inpu tBox ( "Wh at is you
r fav orit e wor d?")
t x tOu tput .Tex t = "Wh en the word
is wri tten twic e , " &
Twi ce(w ord) & " lett ers are
used ."
End Sub

Fun ctio n Twi ce (ByV al wAs Stri


ng) As Inte ger
' Com pute twic e the leng th of
a stri ng
Dim len As Inte ger
Retu rn len = 2 * w . Len gth
End Fun ct i on

In Exe rcise s 13 t hrou gh 23, cons truc


t user-def ined fun ctio ns to carr y out
task (s) of the prog ram . the primary

13. To dete rmine the num ber of sq uare


cent imet ers of tin need ed to make a tin can, add the squa re
of the radiu s of the can to the product of
the radiu s and height of the can, and then
th is urn by 6.283. Wri te a prog ram that mu ltiply
requests the radius and heigh t of a tin can
te rs as inpu t and disp lays the num ber of squa in cent ime-
re cent imeters of tin requ ired to make the
14. Tab le 5. 2 gives the Saffir- S imps can.
on scale fo r ca tego rizin g hurr ica nes. Wr
requests a wind speed in miles/ho ur and ite a prog ram that
disp lays the catego ry of the storm .

I@:JIIfW Rating of hurricanes.


Win d Spee d (in mph )
Rati ng
74 to 95 Cate go ry O ne
96 to 110 Category Two
111 to 130 Cate gory Three
13 1 to 155 Category Four
Ove r 155 Category Fi ve

15. The fede ral gove rnm ent deve lope d


t he body ma s index (BM I) to dete rmin
Body mass inde x is calculat ed as 703 t e idea l we ights .
imes the weight in po unds, divided by
the h e ight in inch es, and then ro und th e squa re of
ed to the neares t who le num ber. Wr ite
t hat acce pts a person's we ight and h eigh a prog ram
t as inpu t and gives the perso n's body mass
Not e: A BMI of 19 to 25 corr espo nds to index .
a heal thy we ight .
16. In o rder for exe rc ise to be bene ficia
l to the card iovascula r syste m, the hear t
hear t beat s per minu te ) must exceed a rate (num ber of
valu e calle d the training heart rate, T HR.
THR can be calc ulated from their age and A person's
res ting heart rate (pu lse rate whe n first awa
as fo llows: keni ng)

(a) Ca lcula te the max imum hear t rate as


220 - age.
(b) S ubt ract the re ring hear t rate fro
m the max imum hea rt rate .
(c) Mu ltipl y the res ult in step (b) by 60%
, and then add the resting h eart rate .
Wri te a prog ram to request a person's age
and res ting hea rt rate as inpu t and d isp
THR . (Test the prog ram with an age of lay the ir
20 and a rest ing hea rt rate of 70, and then
min e your tra ining hea rt rate. ) dete r-
174 • Cha pter 5 Gen eral Proced ures

corn, butt er ubst i-


thre e com pon ents for a serv ing of popcorn at a mov ie thea ter are pop
17. The items and the price
that req uests the cost of these three
tute, and a bucket. Write a program re popcorn costs
lays the profit. (Test the program whe
of the serv ing as inpu t and then disp selling price is $5.)
s, the bucket costs 25 ce nts, and the
5 cen ts, butt er substitute costs 2 cent
fina l exa m and then
num eric grade on a midterm and a
18. Wri te a program that requests the The final exa m
a Fun ctio n proc ed ure to assig n a semeste r grade (A, B, C, D, or F).
uses sho uld be round ed
mid term exa m, the emeste r ave rage
sho uld cou nt twice as muc h as the d by the following
the se mester grade sho uld be ass igne
up to the nea rest whole number, and rounds non integer
.. . Use a func tion call ed Ce il that
criteria: 90-100 (A) , 80-89 (B), . = - Int( -x) .
up to the nex t int ger. The func tion Ceil can be defined by Ce il( x)
num bers ts for eac h add i-
orig inal cost of airm ail lette rs wa 5 cen ts for the first oun ce anc ll O cen
19. The ight is give n by the
mpu te the cos t of a lette r whose we
tion al oun ce. Wri te a progra m to co num bers up to the
call ed Ce il that rounds non intege r
u er in a text box. Use a func tion . (Test the program
be defined by Ceil( x) = - lnt( -x)
nex t integer. The function Ce il can
ces.)
with the weights 4, 1, 2.5, and .5 oun
each mon th into a sav-
ey is depos ited at the beg inni ng of
20. Suppos e a fi xed amo unt of mon dep osit is made,
compound ed mon thly. Afte r each
ings acco unt paying 6% inte rest unt]. Wri te a
bala nce one mon th ago ] + [fixed amo
[new balance] = 1.005 * [prev ious plays the bala nce
ram that requ ests the fixe d amo unt of the deposit as inpu t and di
prog
wn below is the outc ome whe n 100
0 is typed into
each of the first four dep osit s. Sho
after
ed each mon th.
the text box fo r the amo unt deposit
Mon th 1: $1,0 00.0 0
Mon th 2: $2,0 05.0 0
Mon th 3: $3,0 15.0 3
Mon th 4: $4,0 30 . 10
inpu t and display the
name of a Uni ted Stat es se nato r as
21. Wri te a progra m to reque t the parts, and use a
the sena tor. Ass ume the nam e has two
address and salutat ion for a lette r to Sm ith is typed
to dete rmin e the se nato r's last name. The outc ome whe n Rob ert
func tion
the senator's nam e fo llows.
into the inpu t dial og box req uest ing
th
The Hon ora ble Rob ert Smi
Uni te d Sta tes Sen ate
Was hi ngt on, DC 200 01

Dea r Sen ato r Smi th,


ed-o ut clay of the week
22 . Wr ite a prog ram that req uests
a date as inpu t and th en give the pell
following header.
for that date as output. The prog ram sho uld use a func tion with the
d As Dat e) As Str ing
Fun ctio n Day OfW eek( ByV al
or not the year is a leap
yea r as inpu t and then te lls whe ther
23. Wri te a prog ram that request a r. Hin t: Use the
lea n-va lue func tion nam ed lsl eap Yea
year. The program sho uld use a Boo
Dat eDi ff function.

Solu tions to Practice Problems 5.1


there fore,
argumen t, x, take a S tring va lue ;
lue of type Do uble and th e seco nd
1. The first argum ent, n takes a va h ere, th ere is no way to dete rmin e the
a strin g. From the two lines sh own
the inpu t cons ists of a num ber and of the func tion.
dete rmin ed onl y by look ing at the defini tion
type of the outp ut. This can be
5.2 Sub Procedures, Part I
• 175
2. The two argum ents in Find Lette r (word
, num) a rc in th e wrong o rd er. S ince the two param
heade r for the Functi on proced ure have types Intege eters in the
r and tring, in th at o rd er, the argum ents must have
sa me types and order when the Functi on proced ure the
is called . The functi on ca ll should be Find Let ter
word ) . Visua l Bas ic match es a rgum ents to parameters (num,
based on their positio ns, not on th e ir names.

5.2 Sub Procedures, Part I


S ub proce dures share seve ra l featu res with Func tio
n proce du res.
• Both are writt en as as parat e block of code that
can be ca lled to perfo rm a specifi c task.
• Both are used to break co mp lex problems into
small problems.
• Both are used to elimi nate repe titive code.
• Both can be reuse d in other programs.
• Both make a progr am eas ier to read by separ ating
it into log ical un its.
• Both have param eters that are decla red in a heade
r.
S ub proce dures , however, do not retur n a va lue a
soc iated with the ir name. The most com-
mon u es of Sub proce dures are to rece ive input,
process input , o r disp lay o utput.

Defining and Calling Sub Procedures


Sub proce dures are defin ed by blocks of the form

Sub Proc edur eNarn e( ByVa l parl As Type Video Note


l,
ByVa l par2 As Type2 , Sub
proccJu res

ByVa l parN As TypeN )


state ment (s)
End Sub

In the block above , o ne o r more of the ByVa ls ca


n be rep laced with the keyw o rd ByRef. (The
use of ByRe f will be discussed in the next ectio n.)
Like Funct ion procedure names, the names of Sub proce
dures must confo nn to d1.e rules for nam-
ing variables. By conve ntion, Sub procedure names
begin with an uppercase letter and descri be its pur-
pose. In this sectio n all parameters will be preceded
by the keywo rd ByVal. The primary d ifference will
be that Sub procedures wi ll petfo rm some task (such
as d isplay ing output) rathe r than retu rn a va lu
Sub proce dures are ca lled by state ments of the form

Proce dureN ame ( a r gl , a r g 2, .. . , argN)

Whe n a S ub proce du re is called, the va lue of each


argum ent is assigned to t he corre spond -
ing param eter, the state ment (s) inside the proce
du re block are ca rr ied out, and execu tion con-
t inues with the state ment fo llowi ng the call ing statem
n t.
H ere is an exa mp le of a S ub proce dure.

Sub Displ aySu m (ByV al numl As Doub le


, ByVa l num2 As Doub le )
Dim z As Doub le
z = numl + num2
lstO utpu t . Item s . Add (z )
End Sub

W hen a statem ent such as

Disp lay Sum(3 , 4 )


s
176 • Ch apt er 5 Ge neral Procedure

am ete r num l, the num ber


nt pro ced ure , the num ber 3 is ass ign ed to the par
is exe c uted in an eve S ub pro ced u re blo ck
am ete r num 2, and the thr ee sta tem ent s ins ide the
4 is ass ign ed to the par num bers 3
the num ber 7 is dis played in the li t box. W e say tha t the
are carried out. As a res ult,
pro cedure. See Fig. 5.3.
and 4 are pas sed to the S ub
argum ents
~
Dis pla ySu m( 3, 4)

al num 2 As Do ubl e )
num l As Do ubl e , ByV
Sub Dis pla ySu m( ByV al

L___ _ parameters - - - - - '

ure .
FIGURE 5.3 Pas sing arg um ent s to a pro ced

Arguments
Variab les and Expressions as ),
can be lite rals (as in Fi g. 5.3
h fu nct ion calls, the arg um ent s in S ub pro ced ure calls
Jus t as wit
va riab les, o r express ion .

S ub pro ced ure Dis-


an exp a nde d ver sio n of the
Example 1 Th e fo llowing program calls tim e the arg um ent s
Th e firs t tim e the arg um ents are li tera ls, the sec ond
playS um thr ee times. of Display-
e the arg um ent s are exp ress ion s. In the sec o nd call
tim
are va riab les, and the thir d . In the thir d call, the exp res-
va lues of the var iab les are pa sed to the S ub pro ced ure
S um , the to the Sub pro ced ure.
re ulti ng num bers are passed
sions are eva lu ate d and the
um ber s.C lick
ber s_ Cli ck( .. . ) Ha ndl es btn Ad dN
Pri va te Sub btn Ad dN um
Di spl a ySu m( l, 2)
Dim x As Do ubl e = 3
Dim y As Do ubl e = 4
Di spl a ySu m(x , y)
+ 5)
Dis pl a ySu m(2 * x, y
End Sub
al num 2 As Do ubl e )
num l As Do ubl e , ByV
Sub Dis pla ySu m( ByV al
Dim z As Do ubl e
z = n um l + num2 and 11 & num 2 &
sum of 11 & num l &
11

tpu t.It em s.A dd ( 11


The
lst 0u & 11.11 )
II iS 11 & z

End Sub
.]
[Run, and clic k on the but ton

c Sums l = I@) I.....&S J

I-_- OispiO)' Three Sum s )


The sum of 1 and 2 is J.
The sum of J and 4 is 7.
The sum of 6 and 9 is 15.
5.2 S ub Proc ed ures, Part I
• 177

Example 2 The following program passes a strin g I


and two num ber to a Sub procedur e.
Wh en the Sub procedu re is first called,
the strin g para met er state i ass ign d the
and the num eric para met ers pop and area valu e "Hawa ii",
are ass igned the va lue 12 751 94 and 64
The Sub procedure then uses these para 71, respectiv ely.
meters to carr y out the task of calculat
density of H awa ii . The seco nd calling ing the popu latio n
state men t assigns diffe rent valu es to the
para met ers.
OBJECT PROPERTY
a... Den~itie~ GJ[§J ~
SETIING
frmD ens it ies Tex t Den siti es
[ Display Demo graphics btnD isp lay Text Disp lay
J
Dem ogra phics
lsrD ensiry

Priv ate Sub btn Dis play_ Clic


k( ... ) Han dles btn Dis play .Cli
Cal cula te the pop ulat ion den ck
siti es of stat es
lstD ens ity. Item s.C lear ()
Dim sta te As Stri ng , pop As
Dou ble , area As Dou ble
sta te = "Ha wai i"
pop = 127 519 4
are a = 6471
Ca1 cula teD ens ity( stat e, pop
, area )
1stD ens ity. Item s.A dd( " ")
sta te = "Al aska "
pop = 6636 61
area = 5910 00
Cal cul ateD ens ity( stat e, pop
, area )
End Sub

Sub Cal cula teD ens ity( ByV al


sta te As Stri ng ,
ByV al pop As Dou ble , ByV al
'The den sity (num ber of peo area As Dou ble )
ple per squ are mile )
'wi ll be disp laye d roun ded
to one dec ima l pla ce.
Dim den sity As Dou ble
den sity = pop I area
lstD ens ity. Item s.A dd( "The
den sity of " & sta te & " is"
lstD ens ity. Item s.A dd( For mat )
Num ber( den sity , 1) & "pe opl
End Sub e per squ are mil e." )

[Run , and then clic k on the butt on.]

o... Oens i ies l = I @) -r,:-:~ 1


( Display Demographics )
......
The density of Hawa ii is
197.1 peop le per square mile .

The density of AJask a is


1 .1 peop le per square mile .
178 • Cha pter 5 Gen era l Procedures

Not ice tha t in the calling sta tement


pop , are a)
Cal cul ate De nsi ty( sta te,
er as in the
s hav e the ord er Stri ng, Dou ble, and Double; the same types and ord
the vari able type g stat eme nt can not be
is es enti a!. For instance, the ca llin
Sub proced ure hea der. Thi s ord er
wri tten a
a, sta te)
Cal cul ate Den sity (po p, are
same name some-
mpl e 2 the argu men ts and para meters have the same name. Usi ng
In Exa g parameters
pro gram easier to read . How eve r, argume nts and thei r corr e pon din
times makes a argumen ts
t nam e . Wh at mat ters is tha t the order, number, and types of the
ofte n hav e differen va lid revision of the
anc e, the following cod e is a
and parameters match. For inst how argumen ts are passed
ispl ay_ Clic k eve nt pro ced ure in Example 2. (Fig ure 5.4 hows
btnD
to par ame ters with this cod
e.)

pla y .Cl i ck
Cli ck( ... ) Han dles btn Dis
Pri vat e Sub btn Dis pla y_ sta tes .
den siti es of
'Ca lcu late the pop ula tion
lstD ens ity. Item s.C lea r()
ble , a As Dou ble
Dim s As Str ing , p As Dou
s "Ha wa ii 11
p = 12 7 519 4
a = 64 7 1
a)
Cal cul a teD ens ity( s, p,
dd( "" )
1stD ens ity. Item s.A
s "Al ask a"
p =
663 661
a = 591 000
a)
Ca1 cul ate Den sity (s, p,
End Sub

arg uments

rl---la}
Cal cula teD ens ity( s, p,

a As Dou ble
pop As Dou ble , ByV al are
al sta te As Stri ng , ByV al
Sub Cal cula teD ens ity( ByV

parameters

FIGURE 5.4 Pass ing argu men ts to a proc edu re.

eters
Sub Procedures Having No Param
hav e any par ame ter . A
pro ced ur s, a re not req uired to
Sub pro ced ure s, li ke Fun ctio n vid e a des crip tion of a
ame terl ess Sub pro ced ure can be use d to g ive inst ruc tio ns o r pro
par
pro gra m.
5.2 Sub Proced ures, Part I
• 179

Example 3 T h e following variat ion of Examp le 2 gives th e popu lation


density of a single
state. T he param eterless Sub proce dure Descr ibeTask
gives an ex plana tion of the progra m.

Priva te Sub btnD ispla y_ Click ( ... ) Hand


les btnD ispla y.Cli ck
Desc ribeT ask ()
Calcu lateD ensit y( "Haw aii" , 12751 94, 6471)
End Sub

Sub Desc ribeT ask ( )


lstOu tput . Item s.Cle ar()
lstOu tput . Items .Add ( "This progr am displ
ays the" )
l s tOutp ut.Ite ms.A dd( "pop ulatio n dens ity
of the last state " )
lstOu tput . Items .Add( "to becom e part of
the Unite d State s." )
End Sub

Sub Calcu lateD ensity( ByVa l state As Strin


g,
ByVa l pop As Doub le , ByVa l area As Doub
le )
Dim dens i t y As Doub le
dens i t y = pop I area
l stDe nsity . Items . Add( " ")
lstDe ns ity .Item s . Add ( "The dens ity of "
& state & " is" )
lstDe nsity .Item s.Add (Form atNu mber (dens
ity, 1) & "peo ple per squar e mile. " )
End Sub

[Run , and then click on the butto n .]

~:~ ~ Densi y of a State t=i@J ' ~ I

Display Density

~
is program displays the
p1Jiation density of the last state
become part of the United States .

The density of Hawaii is


19 7.1 people per square mile.

Sub Procedures Calling Other Sub Procedures


A Sub procedure can call anoth er Sub procedu re. If so,
after the End S ub statem en t at the end
of the called S ub proce dure is reach ed, execut ion cont
inues with the li ne in the ca ll ing Sub
proce dure following the ca ll ing tatem ent.

Example 4 In the following progra m, the Sub proce dure FirstP art
calls the, Sub proce-
dure Secon dPart. After the statements in Secon dPart
are executed, execu t ion cont inu es with
the remai ning statem ents in the ub proce dure Fi rstPa
rt before return ing to the eve nt proce-
dure. The form co ntain s a butto n and a list box.

Priva te Sub btnD i splay_ Click ( ... ) Hand


les btnD ispla y. Click
Dem• >n"tr "lte l "1 1 '1 ot e Su proce dures
First Par t ()
180 • C hapte r 5 Gene ral Proce dures

even t proc edur e" )


lst0 utpu t.Ite ms.A dd(4 & " from
End Sub

Sub Firs t Part ()


Firs tPar t" )
lstO utpu t . Item s . Add (l & " from
Seco ndP a rt ( )
Firs tPar t" )
lstO u t p u t . Item s. Add( 3 & " from
End Sub

Sub Seco nd Part ()


Seco ndPa rt" )
ls t 0utp u t.Ite ms.A dd(2 & " from
End Sub
is displayed in the list box. ]
[Run , and cl ick on the butto n. T he follo wing
1 f r om Fi r stPa rt
2 from Sec ondP art
3 from Fi r stPa rt
4 from eve nt p r oced ure

Comments
r the
s on the main flow of a comp lex task and defe
1. Sub procedur es allow prog ramm ers to focu is meth od of prog ram
use them liberally. Th
details of impleme ntati on. Mod ern programs edur e shou ld
own design. As a rule, a Sub proc
construction is known as mod ular or top-d smal l.
ed tasks, and should be kept relative ly
perform on ly one task, or seve ral close ly relat
r-
a commen t state men t desc ribin g the task pe
2. The first line insid e a Sub proc edure is often this
seve ral commen t state men ts are devo ted to
fo rmed by the Sub procedur e. If necessary, all varia bles used by
also reco mme nds that
purpose. Con vent iona l prog ramm ing prac tice this tex t , we
men ts with their mea nings. In
the Sub procedu re be listed in com men t state -
adhe re to it on ly whe n the varia bles are espe
give seve ral examp les of th is prac tice, but
ciall y num erous or lack desc ripti ve name .
tion
ion and Para mete r Info help us write a func
3. In Sect ion 5. 1, we saw that Word Complet S ub proc edur e calls . (Of
same ass istan ce for
call. T hese Inte lliSe nse features prov ide the Sub proc ed ure has
Info work only whe n the
course, Word Completi on and Para mete r
already been crea ted.) See Fig. 5.5 .

,
k(By Val send er As Sy stem . Obje ct
Priv ate Sub btnA ddNu mber s Clic
Di splay Sum ( l , 2)
Dim x As Dou ble 3
Dim y As Dou ble = 4
Disp lay Sum <I
As Dou ble) !
IDi splay Sum (num l As Dou ble, num2

FIGURE 5.5 The Para mete r Info help fea ture.

the
called Sub procedur es had to be writt en in
4. In early versions of Bas ic, state men ts that
fo rm
, ... , argN )
Ca l l Proc edur eNam e(ar gl, arg2
es are often referred to as Call state men ts.
The refore, state men ts that call Sub procedur
5.2 Sub Proced ures, Part 1 • 181

1. What is the d ifference between an even t procedu re and a S ub procedu


re?
2. What is wrong with the fo llow ing code?
Privat e Sub btnDis play_ Click( ... ) Handle s btnDis play.C
lick
Dim phone As String
phone = mtbPho neNum. Text
AreaCo de(phon e)
End Sub

Sub Area Code ()


txtOut put.Te xt "Your area code is " & phone. Substri ng(O, 3)
End Sub

In Exercis es 1 through 20, determi ne the output displaye d when the button
is clicked .
1. Private Sub btnDis play_ Click( ... ) Handle s btnDis play.C lick
Piano (88)
End Sub

Sub Piano(B yVal num As Intege r)


txtOut put.Te xt = num & " keys on a piano"
End Sub

2. Privat e Sub btnDis play_ Click( ... ) Handle s btnDis play.C lick
'Openin g line of Moby Dick
FirstL ine ("Ishm ael")
End Sub

Sub FirstLi ne(ByV al name As String)


'Displa y first line
txtOut put.Te xt = "Call me " & name &
End Sub

3. Privat e Sub btnDis play_ Click( ... ) Handle s btnDis play.C


lick
Dim color As String
color = InputBo x("Wha t is your favori te color?" )
Flatter y(colo r)
End Sub

Sub Flatter y(ByV al color As String)


txtOut put . Text "You look dashing in " & color &
End Sub

(Assum e the response is blue.)


4. Privat e Sub btnDis play_ Click( ... ) Handle s btnDis play.C lick
Dim num As Double = 144
Gross(n um)
End Sub
182 • Chapte r 5 G eneral Procedu res

Sub Gross (ByVa l amoun t As Doubl e)


"
txtOu tput.T ext = amoun t & " items in a gross
End Sub
.Click
5. Priva te Sub btnDi splay_ Click ( ... ) Handl es btnDi splay
Dim hours As Doubl e
hours = 24
Minut es(60 *hou rs)
End Sub

Sub Mi n utes(B yVal num As Doubl e)


txtOu tput.T ext = num & " minut es in a day"
End Sub
.Click
6. Priva te Sub btnDi splay_ Click ( ... ) Handl es btnDi splay
Dim s tates , senat ors As Doubl e
stat e s = 50
sena t ors = 2
Sena t e(sta tes * senat ors)
End Sub

Sub Sen ate(By Val num As Doubl e)


is " & num
txtBo x.Tex t = "The numbe r of U.S. Senat ors
End Sub
.Click
7. Priva t e Sub btnDi splay_ Click ( ... ) Handl es btnDi splay
Quest ion ()
Answe r()
End Sub

Sub Answe r ()
ted in the north ern")
lstOu tput.I tems. Add(" Becau se they were inven
als go clock wise. ")
lstOu tput.I tems. Add(" hemis phere where sundi
End Su b

Sub Qu estio n ()
wise? ")
lstOu tput.I tems.A dd("W hy do clock s run clock
lstOu tput.I tems. Add(" ")
End Su b
btnDi splay .Click
8. Priva t e Sub btnDi splay_ Click ( ... ) Handl es
Answe r()
Que s tion ()
End Su b

Sub Answe r ()
lstOu tput.I tems. Add(" The answe r is 9W.")
)
lstOu tput.I tems. Add(" What is the quest ion?"
End Sub

Sub Quest ion()


'No te: "Wagn er" is prono unced "Vagn er"
5.2 Sub Procedures , Part l
• 183
lstO utpu t.Ite ms. Add ("D o you
spe ll you r nam e wit h a V,"
)
lstO utp ut. Item s .Add ("M r. Wag
ner? ")
End Sub
9. Priv ate Sub btn Dis play_ Clic k(
... ) Han dles btn Dis play .Cli
ck
'Beg inni ng of Tal e of Two
Cit ies
Tim es ("be st")
Tim es ("w orst ")
End Sub

Sub Tim es(B yVa l wor d As Stri


ng)
'Dis play sen tenc e
lstO utp ut . Item s.A dd( "It was
the " & wor d & " of tim es."
)
End Sub

10. Priv ate Sub btn Dis play_ Clic


k( ... ) Han dles btn Dis play .Cli
'Sen tenc e usin g num ber, thin ck
g, and plac e
Sen tenc e (168 , "ho ur", "a wee
k")
Sen tenc e(76 , "tro mbo ne", "the
big para de" )
End Sub

Sub Sen tenc e(B yVa l num As


Dou ble, ByV al thin g As Stri
ng,
ByV al whe re As Stri ng)
lstO utpu t.Ite ms. Add (nu m &
" " & thin g & "s in " & whe
End Sub re)

11. Priv ate Sub btnD ispl ay_ Clic


k( ... ) Han dles btn Dis play .Cli
'The fate s of Hen ry the Eig ck
hth 's six wiv es
Com mon Fate s ()
lstO utp ut. Item s .Add ("di ed"
)
Com mon Fate s ()
lstO utp ut. Item s .Add ("su rviv
ed" )
End Sub

Sub Com mon Fate s()


'The mos t comm on fate s
lstO utp ut.I tem s.A dd( "div orc
ed")
lstO utp ut . Item s .Add ("be hea
ded ")
End Sub

12. Priv ate Sub btn disp lay_ Clic


k ( . .. ) Han dles btn disp lay .
Clic k
Dim pre s, col leg e As Stri ng
pre s = "Bu sh"
col leg e = "Ya le"
Pres Alm aMa ter( pres , coll ege
)
pre s = "Oba ma"
col leg e = "Co lum bia"
Pres Alm aMa ter( pres , coll ege
)
End Sub

Sub Pres Alm aMa ter(B yVa l pre


s As Stri ng, ByV al coll ege
lstO utp ut.I tem s.A dd( "Pr esid As Stri ng)
ent " & pre s & " is a gra dua
te of " &
col leg e & " • ")
End Sub
184 • C hap ter 5 Gen eral Procedures

pla y . Cli ck
Cli ck( ... ) Han dles btn Dis
13. Pri vat e Sub btn Dis pla y_
HowMan y(2 4)
.")
lstO u t put .Ite ms .Ad d(" a pie
End Sub

Int ege r)
Sub How Man y(B yVa l num As
Wha t (num)
ked in" )
lstO u tpu t.It em s . Add ("ba
End Sub

ege r)
Sub Wha t(B yVa l num As Int
& " bla ckb ird s")
lstO u tpu t.It em s.A dd( num
End Sub
pla y.C lick
Cli ck( ... ) Han dles btn Dis
14. Pri vat e Sub btn Dis pla y_
'Go od adv ice to foll ow
Adv i c e()
End Sub

Sub Adv ice ()


coo l, but don 't fre eze .")
lst Out put .Ite ms . Add ("K eep
Sou r ce ()
End Su b

Sub So urc e () .")


rce : A jar of may onn aise
lst Out put .Ite ms. Ad d(" Sou
End Sub
pla y . Cli ck
Cli ck( ... ) Han dle s btn Dis
15. Pri vat e Sub btn Dis pla y_
As Int ege r
Dim wor d As Str ing , num
wor d = "Vi sua l Bas ic"
num = 6
Fi r stP art( wo rd, num)
End Sub
As Int ege r)
As Str ing , ByV al dig it
Sub Firs tPa rt(B yV al term
" let ter s are " &
tx t Ou tpu t.Te xt "Th e fir st " & dig it &
& " "
term .Su bst ring (O, dig it)
End Sub
pla y . Cli ck
Cli ck( ... ) Han dle s btn Dis
16. Pri vat e Sub btn Dis pla y_
Dim d As Dat e = Tod ay
Dis play Typ eOf Day (d)
End Sub

Val d As Dat e)
Sub Dis play Typ eOf Day (By
I f IsW eek end Day (d) The n
."
txtO utp ut.T ext "To day is a wee ken d day
El se
txtO utp ut.T ext "To day is a wee kda y . "
En d I f
End Sub
5.2 Sub Proce du res, Part I
• 185

Func tion IsWe ekend Day(B yVal d As Date)


As Bool ean
Dim when As Strin g= Form atDa teTim
e(d, Date Form at.Lo ngDa te)
If when .Star tsWi th("S aturd ay") Or when
.Star tsWi th("S unda y") Then
Retu rn True
Else
Retu rn False
End If
End Func tion
17. Priv ate Sub btnD ispla y_ Click () Hand les
btnD ispla y.Cl ick
Dim cost As Doub le = 250
Disp layB ill(c ost, Ship ping Cost (cost
))
End Sub

Func tion Shipp ingC ost(B yVal costO fGoo


ds As Doub le) As Doub le
Sele ct Case costO fGoo ds
Case Is < 100
Retu rn 10
Case Is < 500
Retu rn 15
Case Else
Retu rn 20
End Sele ct
End Func tion

Sub Disp layB ill(B yVal cost As Doub


le, ByVa l adde dCos t As Doub le)
lstOu tput. Item s.Ad d("C ost: " & Form
atCu rrenc y(co st))
lstOu tput. Item s.Ad d("S hipp ing cost :
" & Form atCu rrenc y(add edCo st))
lstOu tput. Item s.Ad d("T otal cost : "
& Form atCu rrenc y(cos t + adde dCos t))
End Sub

18. Priv ate Sub btnD ispla y_ Click () Hand


les btnD ispla y.Cl ick
Dim langu age As Strin g = "Vis ual Basic
"
Show Word (lang uage)
End Sub

Sub Show Word (ByV al word As Strin g)


If word .Len gth < 5 Then
txtO utpu t.For eCol or Colo r . Red
Else
txtO utpu t.For eCol or Colo r.Blu e
End If
txtO utpu t.Tex t word
End Sub

19. Priv ate Sub btnD ispla y_ Click () Hand les


btnD ispla y . Click
Dim grad e= CDbl (Inpu tBox ("Wh at is
your nume ric grad e?", "Gra de"))
Show Resu lt(gra de)
End Sub

Sub Show Resu lt(By Val grad e As Doub


le)
If Passe dExa m(gr ade) Then
txtO utpu t.Tex t = "You passe d with a
grad e of " & grad e &
186 • Chap ter 5 Gene ral Proced ure

Else
txtO utpu t.Tex t "You faile d the exam ."
End If
End Sub

Doub le) As Bool ean


Func ti o n Passe dExa m (ByV al grad e As
Sele c t Case grad e
Ca s e Is >= 60
Retu rn True
Ca s e Else
Retu rn False
End Sele ct
End Fun ction

(Assume the response is 92.)


btnD ispla y.Cl ick
20. Priv at e Sub btnD ispla y_ Click () Hand les
Dim anyD ate As Date
. (mm/ dd/yy yy)") )
anyD ate = CDat e(Inp utBo x("In put a date
Show Centu ry(an yDat e)
End Sub

Sub Show Centu ry(By Val anyD ate As Date)


Sel e ct Case anyD ate
Ca se Is > = #1/1/ 2000 #
ry"
txtO utpu t.Tex t = "twe nty- first centu
Ca se Is >= #1/1/ 1900 #
txtO utpu t.Tex t "twe ntiet h centu ry"
Ca se Else
txtO utpu t.Tex t "prio r to the twen tieth centu ry"
End Sele ct
End Su b

(Assume the response is 6/5/1955.)

In Exerc ises 21 throu gh 24, find the error s.


les btnD ispla y.Cl ick
21. Priv ate Sub btnD ispla y_ Click ( ... ) Hand
Dim n As Integ er = 5
Al p habe t ()
End Sub

Sub Alpha bet(B yVal n As Integ er)


ng(O , n)
tx t Outp ut.Te xt "abc defg hijkl mnop qrstu vwxy z".Su bstri
End Sub
les btnD ispla y.Cl ick
22. Priva te Sub btnD ispla y_ Click ( . .. ) Hand
le
Dim word As Strin g, numb er As Doub
wo r d = "seve n"
numb er = 7
Disp lay(w ord, numb er)
End Sub
5.2 S ub Procedur es, Part l
• 187

Sub Dis play (By Val nurn As Dou


ble, ByV al term As Stri ng)
txtO utp ut . Tex t = nurn & " "
& term
End Sub
23. Priv ate Sub btn Dis play_ Clic k(
... ) Han dles btn Dis play .Cli
ck
Dim nam e As Stri ng
nam e = Inpu tBo x ("Na me" )
Han dles (nam e)
End Sub

Sub Han dles (By Val mon iker


As Stri ng)
txtO utp ut.T ext = "Yo ur nam
e is " & mon iker
End Sub

24. Priv ate Sub btn Dis play_ Clic k(


... ) Han dles btn Dis play .Cli
Dim nurn As Inte ger ck
= 2
Tea( nurn )
End Sub

Sub Tea ()
txtO utp ut.T ext "Tea for " & nurn
End Sub

In Exe rcis es 25 thro ugh 28, rew rite


th e prog ram with the outp ut perf orm
Sub proc edu re. ed by a call to a

25. Priv ate Sub btnD ispl ay_ Clic k(


... ) Han dles btn Dis play .Cli
'Dis play a luck y num ber ck
Dim nurn As Inte ger = 7
txtO utp ut.T ext = nurn & " is
a luck y num ber. "
End Sub

26. Priv ate Sub btn Dis play_ Clic k(


... ) Han dles btnD ispl ay . Clic
'Gre et a frie nd k

Dim nam e As Stri ng = "Jac k"


txtO utp ut.T ext = "Hi , " &
nam e
End Sub

27. Priv ate Sub btn Dis play_ Clic k(


... ) Han dles btn Dis play .Cli
'Inf orm atio n abo ut tree s ck
Dim tree As Stri ng, ht As
Dou ble
tree = "red woo d"
ht = 362
lstB ox.I tem s.A dd( "Th e tall
est " & tree &
" tree in the U.S . is " & ht & " fee t.")
tree = "pin e"
ht = 223
lstB ox.I tem s.A dd( "Th e tall
est " & tree &
" tree in the U.S . is " & ht & " fee t.")
End Sub

28. Priv ate Sub btn Dis play_ Clic k(


.. . ) Han dles btnD ispl ay .C lick
Dim city As Stri ng, sala ry As
Dou ble
lstO utp ut.I tem s.C lear ()
city = "San Jose "
188 • Cha pter 5 G enera l Procedures

sal ar y = 830 89
for " & cit y &
200 8, the ave rag e sal ary
lstO u tpu t.It em s . Add ("In & "." )
ma tCu rren cy( sala ry, 0)
" res ide nts was " & For
cit y = "Ha rtfo rd"
sal ar y = 460 00 for " & cit y &
200 8, the ave rag e sal ary
lstO u tpu t.It em s.A dd( "In & "." )
ma tCu rren cy( sala ry, 0)
" res ide nts was " & For
End Sub
put sho wn in a list box.
es 29 thro ugh 32, wri te a pro gra m tha t displays the out
In Exe rcis pro ced ure s usin g
two line s of the out put sho uld be displaye d by one or mor e Sub
The last
eve nt pro ced ure .
data passed by variables from an
29. (Assume tha t the following
is disp laye d.)
tak en by the Hig her
vey of col leg e fres hme n
Acc ord ing to a 200 8 sur
te:
Edu ca t ion Res ear ch Ins titu
y inte nd to maj or in bus ine ss.
16 . 7 p erc ent sai d the sci enc e.
nd to maj or in com put er
1 per c ent sai d the y inte
"W hat is you r date
e tha t the curr ent date is 12/3 1/2010, the labe l for txtB ox read
30. (Assum is clicked.)
1984 into txtB ox before btn Display
of birt h ?", and the user ent ers 2/3/
.
You are now 26 yea rs old
for 982 4 day s.
You h ave liv ed
the user types
t the labe l for txtB ox read s "W hat is your favorite num ber?", and
31. (Assume tha
ked. )
7 into txtBox before btn Display is clic
num ber wit h its elf is 14.
The s um of you r fav ori te is 49.
ori te num ber wit h its elf
The p rod uct of you r fav
disp laye d.)
32. (Assu me tha t the fo llow ing is
In a rec ent yea r, Spa nis h
den ts too k a cou rse in
823 tho usa nd col leg e stu Fre nch
den ts too k a cou rse in
206 tho usa nd col leg e stu
. " The prim ary verse,
a prog ram to disp lay thre e ve rses of "Old Mc Don ald H ad a Farm
33. Wri te in a Sub proce-
les sub stit uted for the anim als and sounds, sho uld be con tain ed
wit h var iab to the Sub procedure:
foll owing anim al and sou nd pa irs
dure. The prog ram sho uld pass the uld be
k. The first verse of the out put sho
lam b, baa; duck, quack; firefly, blin
. Eyi eyi oh.
Old McD ona ld had a farm
had a lam b. Eyi eyi oh.
And on his farm he
a baa baa the re.
Wit h a baa baa her e, and
, eve ryw her e a baa baa .
Her e a baa , the re a baa
ld had a farm . Eyi eyi oh.
Old McD ona
est the per-
ram to com pute tips for serv ices rend ered . The program sho uld requ
34. Wr ite a prog t and pass this info rma -
bill , and the percent age tip as inpu
son 's occ upation, the amo unt of the run is sho wn in Fig. 5.6.
the person and the tip. A sample
tion to a Sub procedure to display
e grades to a
ram tha t requ ests thre e grad es as inp ut and the n passes the thre
35. Wri te a prog Fig. 5.7.
displays the high est two grade . See
Su b proced ure tha t dete rmines and
num eric grad e on
a pro gram tha t requ ests a stud ent 's first name, last name and the
36. W rite e and se me ter
ms, and the n uses a Sub pro ced ure to display the stud ent 's nam
three exa
5.2 Sub Proce dure , Part l
• 189

a G atu it ies a G ad es

Person 's occup ation : taxi dnver Rrst grade : So

~mount of the bill : 2 . Secon d grade : S

Percentage t ip : 15 Tllird grade : 87

Compute Tip Determine Highest Two Grades

Tip the taxi driver S3.


The highest t'o\'O grades are S and 87.

FIGURE 5.6 Samp le run of Exerc ise 34. FIGURE 5.7 Samp le run of Exerc ise 35.

grad e (A, B, C , D, o r F). A Func ti on proc


edur e (ca lled by the S ub proc ed ure) sho uld
be used to ca lcula te the se mes te r grad e.
The lo wes t grad e h o uld be d ro pped , t h e
se mes ter ave rage sh o uld be ro und ed to the
n ea res t who le num be r, and the se mes te r
grad e sh o uld be ass ign ed using the fo llow ing
crite ria : 90- 100 (A) , 80-8 9 (B) , .... See
Fig. 5 .8.

a .. G ades

Name : Robert Smith

a ~ o.rd:;
Rrst grade : 8,3

Secon d grade : 8 Rrst '•"••ord : beaut>,'

Third grade : 7 Secon d word : age

r Determine Semester Grade .1\iphabetize l.'JJords

Robert Smith : B

FIGURE 5.8 Samp le run of Exerc ise 36.


FIGURE 5.9 Samp le run of Exerc ise 3 7.

37. Write a prog ram that requ ests two word s


as inpu t and then passes the word s to a S ub
ced ure that displ ays the word s in alpha betica pro-
l order. See Fig. 5.9.
38. Writ e a prog ram that asks a quiz show cont
estan t to se lect one of the num bers 1, 2, or 3 and
then calls a S ub proce dure that asks the ques
t ion h aving that num ber and requests the
answe r. The Sub proce dure sh ould then call anot
her S ub proce dure to te ll the cont estan t if
the answer is correc t. Use the follo wing three
ques tions:
1. W h o was the on ly living artist to have his
work d isplayed in the G rand Ga llery of the
Louv re?
2. Who sa id , "Com pute rs are useless. They can
on ly give you answers."?
3. By wh at name is Pab lo Blas ia bette r know
n?
Note : These ques tions h ave th e sa me answer,
Pablo Picasso.
190 • C hapt er 5 G enera l Procedures

Solutions to Practice Problems 5.2


are provided aurom arica lly by
para mete rs (such as e and se nd er) thar
1. The head er of an eve nt proce dure has the othe r hand, a Sub proce dure is
whe n an even r is ra ised. On
Visua l Basic, and th e proced ure is in voked re.
name of the Sub procedu
invok ed by a line of code conta ining the
al phon e As S tri n g ) .
must be rep laced by Sub Area Cod e (ByV
2. The state menr Sub Area Cod e () param ete r to receive the va lue.
d ure, the Sub state ment must prov ide a
Whe neve r a va lue i passed ro a Sub proce

5.3 Sub Procedures, Part II


show h ow to
ed to S ub proc edur es. In this sect ion we
In the previo us secti on va lu es were pass
pass valu es back from S ub procedures.

Passing by Value
the wo rd ByVal,
g in S ub proc edur e were prec eded by
In Sect ion 5.2, all para mete rs appe arin we ay that th e
ich stan ds for "By Valu e." Wh en a variable is passed to such a para mete r,
wh a l va lue after
that is passed by va lue will reta in its o rigin
varia ble is "passed by valu e." A variable e of the corr e-
of wha t chan ges are mad e to the valu
the Sub proc edur e term in ate -reg ardl ess
edure. Examp le 1 ill ustrates this feature.
spon ding para mete r inside the S ub proc

fact that chan ges to the valu e of a


Example 1 The following program illustrates the ing state men t.
t on the value of the argu men t in the call
pa rame ter passed by value have no effec
( .. . ) Han dles btnD ispl ay .Cli ck
Priv ate Sub btnD ispl ay_ Cl ic k
'Ill ust rate that a ange in va ue of para m ter
the argu men t
'doe s not alte r .he valu e of
Dim amt As Dou ble = 2
from even t proc edu re" )
lstR e sul ts .I tems . Add (amt & "
Trip l e (amt )
from even t proc edu re" )
ls t Re s u lt s. Item s . Add (amt & "
End Sub

)
Sub Tr iple ( ByV al num As Dou ble
'Tri ple a num ber
from Sub proc edu re" )
lstRe s u l ts.It ems .Ad d(nu m & "
n um = 3 * num
from Sub proc edu re" )
lstRes ult s .Item s.Ad d(nu m & "
End Sub
wing is disp layed in the list box. ]
[Run , and then click the butt on. The follo
2 from e v ent proc edu re
2 f rom Sub proc edu re
6 from Su b p r oced u re
2 f rom e v ent proc e dure

s the
ory loca tion s are invo lved. Figure 5.10 show
Whe n a varia ble is passed by value, two mem time the Sub proc e-
ram in Example 1 exec utes. At the
statu s of the memory loca tion s as the prog the Sub pro-
loca tion for the para mete r is set as ide for
dure i called, a temp orary seco nd mem ory Afte r the com pleti on of
t is copied into that loca tion.
cedure's use and the valu e of the argumen in it is lost.
loca tion is released, and the va lue
the Sub procedure, the temporary memory
5.3 Sub Proced ure , Part ll
• 191

variable in event procedure _____.. amt amt amt amt


Memory -12 1
location~

parameter 1n Sub Triple - ---+n um num


(a) (b) (c) (d)
Before Sub Triple After Sub Triple After After Sub Triple
is called is called num = 3 * num is exited
is executed
FIGURE 5.10 Passi ng a varia ble by valu e to a Sub proc
edur e.

Passing by Reference
Ano the r way to pass a varia ble to a S ub
proc edur e is "By R efe re n ce." In this case
is prec eded by t h e k eywo rd ByR ef. S uppo the pa ra me te r
se a varia ble, ca ll it arg, ap pears a a n
p roce dure ca ll, and its co rresp ondi ng pa a rgum e nt in a
ra m e te r in the S ub proc edur e 's h eade r,
ced ed by ByR ef. Afte r the S ub proc edur ca ll it par, is pre-
e h as bee n exec uted , arg will h ave wha
h ad in th e S ub p roce dure. teve r va lu e par
In Exam ple 1, if the h ead e r of the S ub
proc edur e is ch a n ged to
Sub Trip le(B yRe f num As Dou ble)

the n the last num be r of the o utp ut will


be 6. Alth o ugh t his fea ture may be surpr
g la n ce, it prov ides a vehi cle fo r pass ing ising at first
va lues from a S ub proc edur e back to the
whic h t h e S ub p roce dure was calle d . D p lace fro m
iffe re nt n a mes m ay be used fo r a n a rgum
respo ndin g pa ra me te r, but o nly o e nt a nd its cor-
n e m e m o ry loca ti o n is invo lved .
btn O isp lay_ C li ck() eve n t proc edur e a Init ia lly, th e
lloca tes a m e m o ry loca tio n to h o ld the
(Fig. S. ll (a )) . Whe n the S ub proc edur va lu e of amt
e is ca ll ed , the pa ra me te r num beco m es
d ure's n a m e fo r this m e mo ry loca tio n the S u b proc e-
(Figu re S.ll( b)) . Whe n the valu e of num
va lue in t h e m e mo ry loca tio n beco m es is t ri p led , the
6 (Figu re 5 .11 (c )) . Afte r the com p letio
ced ure , t h e para m e te r n a me num n of th e S ub p ro-
is fo rgott e n ; h owev e r, its va lu e lives
(Figu re S. ll( d )). The va riab le amt is sa on in amt
id to be pass ed by refe renc e .

vanable 1n event procedure .. amt amt amt amt


Memory --- [D
location
parameter in Sub TrT 1e
0 OJ OJ
-nu m num
(a) (b) (c) (d)
Before Sub Triple After Sub Triple After After Sub Triple
is ca lled is called num = 3 * num is exited
is executed
FIGURE 5.11 Passi ng a varia ble by refer ence to a Sub proce
dure .

Note : The S ub proc edur e Trip le discussed


a bo ve i o lely fo r illust ra tive purp oses a nd is n
re prese nta tive of the way S ub p roce dure ot
s a re used in prac t ice. Exa mp les 2 a nd
uses of S u b proc ed ures. 3 sh ow t yp ica l
Chap ter 5 G e ne ra l Proc edur es
192 •
ure to acquire the input. The var i-
..; Example 2 The fo llow ing program uses a Sub proced Therefore,
r to the exec utio n of the first proced ure call.
ab les x and y are not ass igned va lues prio call is exe-
have the va lue 0. Afte r the procedure
before the proced ure call is exec uted, they then are passed
red into the text boxes. These va lues
cuted, how ever, they have the va lues ente
procedure Oisp layS um.
by the second procedure ca ll to the Sub

PROPERTY SETTING
OBJECT

a:;l Add Tw o Num bers ~I ~ l[ru frmA dd Tex t Add Two


Num bers
Rrst numb er: lblFirstN um Text First num ber:
txtFi rstN um
Second numb er: Text Seco nd num ber:
lblSe co ndN um
Compute Sum txtSe cond N um
btnC omp ute Text Co mpu te Sum
txtR esul t Read On ly True

k
. . . ) Han dles btnC omp ute. Clic
Priv ate Sub btnC omp ute Clic k(
bers and
'Thi s prog ram requ ests two num
and the ir sum.
'dis play s the two num bers
Di m x, y As Dou ble
GetN umb ers(x , y)
Dis play Sum (x, y)
End Sub

ble , ByR ef y As Dou ble )


Sub GetN umb ers( ByR ef x As Dou
the text box es
'Rec ord the two num bers in
x = CDb l (txt Firs tNu m.T ext)
y = CDb l (txtS econ dNu m.T ext)
End Sub
)
Dou ble , ByV al num2 As Dou ble
Sub Disp layS um( ByV al num l As
ir sum
'Dis p l ay two num bers and the
Dim sum As Dou ble
sum = num l + num2
" &
txtR e s ult. Tex t "The sum of " & num l & " and
num2 & " is " & sum & "."
End Sub
then click on the butt on.]
[Run, type 2 and 3 into the text boxes, and

a:;l Add Two Num be rs l = I @] j..,..ES ·J

Rrst numb er: 2

Second numb er: 3

Compute Sum

The sum of 2 and J is 5.


5.3 Sub Procedures, Part II
• 193

Example 3 The fo llo win g prog ram a lph abet izes


two wo rds.

OBJECT PROPERTY SETTING


[I ~ Alph abet ize GJ [ID [}[ ] frmWords Tex t Alph abe tize
Rrst word : lbiFirst Tex t First word:
txtF irst
Second 'o'I'Ord : lbiSecond Text Seco nd word :
txtSecond
Sort and Display Nords
btn Ort Tex t Sort and Disp lay Words
txtO utpu t ReadOnly True

Priv ate Sub btn Sor t Clic k(


... ) Han dles btn Sor t.Cl ick
Dim wor dl As Stri ng = txtF
irst .Te xt
Dim wor d2 As Stri ng = txtS
eco nd.T ext
If (wo rd2 < wor dl ) The n
Swa pWo rds (wo rdl, wor d2)
End If
txtO utp ut.T ext = wor dl & 11
bef ore 11 & wor d2
End Sub

Sub Swa pWo rds( ByR ef wor dl


As Stri ng , ByR ef wor d2 As
Dim temp As Stri ng Stri ng )
temp = wor dl
wo r dl wor d2
wor d2 = temp
End Sub

[Run , en ter word s in the top two text


boxe s, a nd cl ick o n the butt on.]

o_. Al ph~betize l = I @] j..,. t3 ,j


First word : beaut}•
Second word : age

[ Sort and Oispl ~· Nords


J
age before beaut}•

Sub Procedures that Return a Single


Value
A Sub proc ed ure h av ing the By R ef
keyw ord in its list of pa ram eters can
ing va lue to the ca lling stat eme nt. be th o ugh t of as retu rn-
In Exa mp les 2 and 3, th e ub proc edur
ues to the eve nt proc ed ure. S ub es re turn ed two va l-
proc edu res a lso ca n be used to re
H o we ve r, good prog ra mm ing prac turn just a sing le va lu e.
tice d ic tate s that un less the S ub proc
ju t retu rn a sing le va lue, it sho uld edur e does mor e th at
be rep lace d with a Fun ct io n proc ed
sid e r th e follo wing proc edur e ca ll ure. Fo r inst an ce, con -
and S ub proc edur e com bina tion whe
retu rns a sing le va lue, nam e ly the sum re th e S ub proc edur e
of two num be rs.
194 • Cha pter 5 Gen eral Proced ures

Ca lcu late Sum (x, y, s)


num2 As Dou ble ,
num l As Dou ble , ByV al
Sub Cal cul ateS um ( ByV al
ByR ef sum As Dou ble )
l and num2
'Ad d the val ues of num
sum = num l + num2
End Sub
mb ina tion
It sho uld be repl ace d wit h the co
s Cal cul ate Sum (x, y)
= ble
al num2 As Dou ble ) As Dou
n Cal cul ate Sum ( ByV al num l As Dou ble , ByV
Fun ctio
Dim sum As Dou ble
sum = num l + num2
Ret urn sum
End Fun ctio n

and Constants
lifetime and Scope of Variables
ced ure wit h a Dim
or con stan t is dec lare d insi de a Functio n, Sub , or eve nt pro
Wh en a vari ab le portion of mem -
of mem ory is set as ide to hol d the valu e of the va riable. Th at
stat eme nt, a por tion nt is reac hed . The life tim e
s End Functio n or End Sub stat eme
ory is rele ased whe n the procedure' ory. (A vari able 's va lue can
or con stan t is the peri od dur ing whi ch it rem ains in mem
of a vari able able or con stan t is the
life tim e, but it alw ays hol ds some va lue. ) The scope of a vari
cha nge ove r its ced ure wit h a
m tha t can refe r to it. A vari able or con tan t declared in a pro
portion of the progra l con stan t and is said to have
Val , or ByR ef key word i a local var iabl e or a loca
Dim , Ca nst, By ables or con stan ts dec lare d
can not be acc esse d out side the proced ure .) Wh en vari
local sco pe. (It two differe nt obj ects.
t pro ced ures hav e the ame name, Visual Bas ic trea ts the m a
in two differen s-le vel sco pe and can be
d out side of a pro ced ure has clas
A var iab le or con stan t declare de an If o r a Select Cas e blo ck
pro ced ure. A var iab le or con stan t declare d insi
refe rred to by any od progra mm ing practice
el sco pe and can not be accesse d o utside the blo ck. Go
has block -lev r a variab le, this
sco pe of a vari able o r con stan t be as sma ll as poss ible . Fo
d icta te th at the inco rrec tly or acc ide nta lly.
whi ch its valu e can be mo difi ed
redu ces t he num ber of places in

to the par t
the fact tha t variab les are loca l
Example 4 Th e follow ing progra m illu stra tes the variable x in
whi ch the y res ide. Th e variab le x in the eve nt pro ced ure and
of th e progra m in han dles the m as if the ir nam es
differe nt variab les. Visual Bas ic
th e Sub proced ure are trea ted as tim e the Sub pro ced ure i
ara te, suc h as xbt nD ispl ay_ C lick and xTrivial. A lso, eac h
we re sep 0.
de the Sub proced ure is rese t to
call ed, the valu e of variab le x insi
Dis pla y .C lic k
Cli ck( ... ) Han dle s btn
Pri vat e Sub btn Dis pla y_
nat ure of var iab les
'De mo nst rate the loc al
Dim x As Dou ble = 2
& " eve nt pro ced ure " )
lstR e sul ts.I tem s.A dd( x
Tri via l()
& " eve nt pro ced ure " )
lstR esu lts. Ite ms .Ad d(x
Tri via l()
& " eve nt pro ced ure " )
lst Res ult s.It em s.A dd( x
End Sub

Sub Tr ivi al ()
Dim x As Dou ble
& " Sub pro ced ure " )
lst Res ult s.It em s.A dd( x
5.3 Sub Procedures, Part ll
• 195

X = 3
lstRe sults .Item s.Ad d(x & " Sub proc edur e" )
End Sub

[Run , and then click on the butto n.]

Displcrl Resu~s

: event procedure
: Sub procedure
., : Sub procedure
: event procedure
: Sub procedure
J : Sub procedure
: e\rent procedure

Debugging
Progr ams with S ub proce dures are eas ier to debu
g. Each S ub proce dure can be check ed indiv id -
ually before being place d into the program. VideoN ote
In Appe nd ix 0, the sectio n "Step ping through a Debugg ing
Program Cont ainin g a Gene ra l Proce dure:
Chap ter 5" uses the Visua l Basic debugge r to trace proceJu res
the flow through a program and observe the
interp lay b tween argum ents and param eters.

Comments
1. In this textb ook, passing by refe rence is used pr
imar ily to acquire input .
2. Whe n an argum ent that is a litera l or an expre
ss ion is pa sed to a proce d ure, there is no d if-
feren ce betw een passing it by refere nce and passin
g it by va lue. Only a var iable argum ent
can po ibly have its va lu e chan ged by a S ub proce
dure.

1. In Exam ple 3, chan ge the heade r of the Sub proce


dure to
Sub SwapW ords (ByR ef word l As Strin
g , ByVa l word2 As Strin g )
and deter m ine the o utput when the input is beaut
y and age.
2. Whe n the following progr am in entered, Visua
l Bas ic will disp lay a gree n wavy line unde r
the argum ent state in the fourt h line. H owev e r,
there is no wavy line und er the argum ent
pojJ. Wha t do you think the reaso n is for Visua
l Bas ic 's conc ern ?
Priv ate Sub btnD ispla y_ Click ( ... )
Hand les btnD ispla y .C lick
Dim state As Strin g
Dim pop As Doub le
Inpu tDat a(s tate , pop)
txtO utpu t.Tex t = sta te & " has popu
latio n " & Form atNum ber(p op, 0)
End Sub
196 • Chap ter 5 G enera l Proce dures

g, ByRe f pop As Doub le)


Sub Inp utDa ta(B yRef stat e As Strin
stat e = "Cal iforn ia"
pop = 3488 8000
End Sub

EXERCISES 5.3

ut displayed when the butto n is click ed on.


In Exercises 1 throu gh 10, deter mine the outp
les btnD ispla y.Cl ick
1. Priv at e Sub btnD ispla y_ Clic k( ... ) Hand
Dim n ame As Strin g
Dim y ob As Inte ger
GetV i ta(na me, yob)
in the year " & yob &
txtO u tput .Tex t = name & " was born
End Sub

ByRe f yob As Inte ger)


Sub Ge t Vita (ByR ef name As Strin g,
name = "Gab riel"
yob = 1980 'Yea r of birt h
End Sub
les btnD ispla y.Cl ick
2. Priv ate Sub btnD ispla y_ Clic k( ... ) Hand
Dim coun try As Strin g =
Dim pop As Doub le
GetF acts (cou ntry , pop)
" is abou t " &
txtOutpu t.Te xt "The popu latio n of " & coun try &
Form atNu mber (pop , 0) & " "
End Su b

g, ByRe f pop As Doub le)


Sub Ge tFac ts(B yRef coun try As Strin
coun try = "the Unit ed Stat es"
pop = 3130 0000 0 'pop ulati on
End Su b
les btnD ispla y.Cl ick
3. Priv ate Sub btnD ispla y_ Clic k( ... ) Hand
Dim stat e As Strin g = ""
Dim flow er As Strin g = ""
Ge t Fact s(sta te, flow er)
tx t Outp ut.T ext "The stat e flow er of " & stat e &
" is the " & flow er & " "
End Sub

g, ByRe f plan t As Strin g)


Sub GetF acts( ByR ef plac e As Strin
pl a ce "Ala ska"
pl a nt = "For get Me Not"
End Sub
les btnD ispla y.Cl ick
4. Priv a te Sub btnD ispla y_ Clic k( ... ) Hand
Dim film As Strin g =
Dim year As Inte ger
Ge tFac ts(fi lm, year ) It
awar d in " & year &
II

t x tOut put.T ext = film & " won the


End Sub
5.3 Sub Procedu re , Part ll
• 197

Sub GetF acts (ByR ef mov ie As Stri


ng, ByR ef yr As Inte ger)
mov ie = "Slu mdo g Mil lion aire "
yr = 2009
End Sub

5. Priv ate Sub btnD ispl ay_ Clic k(


... ) Han dles btnD ispl ay.C lick
Dim word As Stri ng = ""
Dim num As Inte ger
GetF acts (wo rd , num)
txtO utpu t.Te xt "The firs t " & num & " lett ers
of " & word &
" are " & BegO fWo rd(w ord, num)
& " "
End Sub

Sub GetF acts (ByR ef wAs Stri ng,


ByR ef n As Inte ger)
w Inpu tBox ("En ter a word :")
n Cint (Inp utBo x("E nter a num ber
less than the leng th of the wor
End Sub d:") )

Fun ctio n BegO fWor d(By Val word


As Stri ng, ByV al num As Inte ger)
As Stri ng
Retu rn wor d.Su bstr ing( O, num)
End Fun ctio n

(Assume the two responses are EDUCAT ION


and 3. )
6. Priv ate Sub btnD ispl ay_ Clic k(
... ) Han dles btnD ispl ay.C lick
Dim pric e, mark down , sale sTax
, fina lCo st As Dou ble
Inpu tDa ta(p rice , mark down , sale
sTax )
fina lCo st = Cos tOfi tem (pri ce,
mark down , sale sTax )
Disp layO utpu t(pr ice, fina lCos
t)
End Sub

Sub Inpu tDat a(By Ref pric e As Dou


ble, ByR ef mark down As Dou ble,
ByR ef sale sTax As Dou ble)
pric e CDbl (Inp utBo x("P rice of item :"))
mark down CDbl ( Inpu tBox ("Pe rcen tage disc
oun t:"))
sale sTax CDb l(Inp utBo x("P erce ntag e stat
e sale s tax: "))
End Sub

Fun ctio n Cost Ofit em(B yVa l pr


As Dou ble, ByV al md As Dou ble,
ByV al st As Dou ble) As Dou ble
Dim redu cedP rice , cost As Dou
ble
redu cedP rice = pr ((md I 100) * pr)
cos t= redu cedP rice + ((st I
100) * redu cedP rice )
Retu rn cost
End Fun ctio n

Sub Disp layO utpu t(By Val amo unt,


ByV al cust ome rCos t)
lstO utpu t.Ite ms.A dd(" Orig inal
Pric e: " & Form atCu rren cy(a mou
lstO utpu t.Ite ms.A dd(" Cos t: " nt))
& Form atCu rren cy(c usto merC ost))
End Sub

(Assume the three respo nses are 125 , 20, and


6.)
198 • Cha pter 5 Gen era l Proced ures

7. Dim inv ento ry As Inte ger = 5


ck
k( ... ) Han dles btn Dis play .Cli
Priv at e Sub btnD ispl ay_ Clic
y As Inte ger
Dim n umP urch ased , new inve ntor
to be pur cha sed :"))
ox( "En ter num ber of item s
num Purc hase d = Cin t(In putB
y, num Purc hase d)
Upd atei nve ntor y(n ewi nve ntor
inv ento ry = new inve ntor y
inv ento ry: " & inv ento ry
txtOutp ut.T ext = "Cu rren t
End Sub

new inve ntor y As Inte ger ,


Sub Up date inve ntor y(B yRe f
ger )
ByV al num Purc hase d As Inte
Sel e ct Cas e num Purc hase d
Ca se Is <= inv ento ry
num Purc ha sed
new inve ntor y = inv ento ry -
If new inve ntor y = 0 The n
rem aini ng." )
Mes sage Box . Show ("No i tern s
End If
Ca se Is > inv ento ry ed." )
t inv ento ry, pur cha se can cell
Mes sag eBo x.Sh ow( "Ins uffi cien
new inve ntor y = inv ento ry
End Sel ect
End Sub
with the response 3 give n each time.)
(Assu me btnO isplay is pressed twice

8. Dim b alan ce As Dou ble = 100


Clic k
k( ... ) Han dles btnD ispl ay .
Priv a te Sub btnD ispl ay_ Clic
Bala nce As Dou ble
Dim dep osit , with draw al , new
unt of dep osit :"))
dep osi t= CDb l(In putB ox(" Amo
Amo unt of wit hdr awa l:") )
wi t hdr awa l= CDb l(In putB ox("
draw al, new Bala nce)
Upd ateB alan ce(d epo sit, with
bala nce = new Bala nce
e)
t x tOu tput .Te xt = CSt r(ba lanc
End Sub
al As Dou ble,
osit As Dou ble, ByV al with draw
Sub Upd ateB alan ce(B yVa l dep
ByR ef new Bala nce As Dou ble)
Se lec t Cas e with draw al
Cas e Is = bala nce + dep osit
lete d.")
Mes sage Box .Sho w(" Acc oun t dep
new Bala nce = 0
Cas e Is > bala nce + dep osit ")
rdra wn. Wit hdra wal den ied.
Mes sage Box .Sho w(" Acc oun t ove
osit
new Bala nce = bala nce + dep
Cas e Else
bala nce + dep osit - with draw al
new Bala nce
End Sel ect
End Sub
)
(Assume the respo nses are 90 and 200.
5.3 Sub Proced ures, Part II
• 199

9. Priv ate Sub btnD ispl ay_ Clic k( ..


. ) Han dles btnD ispl ay.C lick
Dim a, b, s, d As Inte ger
Inpu tDa ta(a , b)
Com bine (a, b, s, d)
Dis play Res ults (s, d)
End Sub

Sub Inpu tDat a(By Ref num l As


Inte ger, ByR ef num2 As Inte ger)
num l 3
num2 1
End Sub

Sub Com bine (ByV al x As Inte ger,


ByV al y As Inte ger,
ByR ef sum As Inte ger, ByR ef
diff eren ce As Inte ger)
sum = x + y
diff eren ce x - y
End Sub

Sub Disp layR esul ts(B yVa l s As


Inte ger, ByV al d As Inte ger)
lst0 utpu t.Ite ms. Add ( 11 sum = 11
& s)
lst0 utpu t.Ite ms. Add ( 11 diff eren
ce II & d)
End Sub

10. Priv ate Sub btnC alcu late _ Clic


k( ... ) Han dles btnC alcu late .Cli
Dim who lesa leCo st, sale Pric e, ck
perc entC omm issio n,
sale sTa x, pro fit As Dou ble
Inpu tDa ta(w hole sale Cos t, sale
Pric e, perc entC omm issio n)
Calc ulat eSo meV alue s(w hole sale
Cos t, sale Pric e, perc entC omm
issio n,
sale sTa x, pro fit)
Disp layD ata ( sale sTa x, pro fit)
End Sub

Sub Inpu tDat a(By Ref who lesa leCo


st As Dou ble, ByR ef sale Pric
e As Dou ble ,
ByR ef perc entC omm issio n As Dou
ble)
who lesa leCo st = 100
sale Pric e = 300
perc entC omm issio n 5
End Sub

Sub Calc ulat eSo meV alue s(By Val


who lesa leCo st As Dou ble,
ByV al sale Pric e As Dou ble, ByV
al perc entC omm issio n As Doub
ByR ef sale sTa x As Dou ble, ByR le,
ef pro fit As Dou ble)
sale sTa x = 0.06 * sale Pric e
pro fit = sale Pric e who lesa leCo st
sale Pric e * (per cent Com miss ion
I 100)
End Sub

Sub Disp layD ata( ByV al sale sTa


x As Dou ble, ByV al pro fit As
lst0 utpu t.Ite ms. Add ( 11 sale s tax: 11 Dou ble)
& Form atCu rren cy(s ales Tax ))
lst0 utpu t.Ite ms. Add ( 11 pro fit: 11
& For mat Cur renc y(pr ofit
End Sub ))
200 • Cha pter 5 Gen eral Proced ures

curr ent ann ual


es ts a perso n's first name, last name, and
11. Wri te a pay- raise prog ram that requ $40 ,000 wi ll
for nex t yea r. Peo ple earn ing less than
sala ry, and then disp lays their salary plus 2%
,000 or more wi ll rece ive a raise of$2 ,000
rece ive a 5% raise, and those earn ing $40 a Fun ctio n pro-
proced ures fo r inpu t and outp ut, and
of the amo unt ove r $40 ,000. Use ub
Fig. 5.12.
cedure to calc ulat e th e new salary. See

a-} Cred it Card


l= i@J i.
od Pay Raise
Old balance : 2
Rrst name : John
Charges : 150 Cred its :
Last name : Doe

8 0 Calculate New Balance


CUrrent salary:
and Minimum Payment

Display New Salary


New balance : S253 .

New salary for John Doe : 550.160.0


0 Minimum payment : ..: 3.3

FIGURE 5.13 Poss ible outp ut fo r Exe rcise 12.


FIGURE 5.12 Poss ible outp ut fo r Exercise 11.
cred it ca rd state -
Wri te a prog ram to calc ulat e the bala nce and min imum pay men t for a
12. Fig. 5.14. The
ld use the eve nt proced ure how n in
men t. See Fig. 5.13. The progra m shou less, the min imu m
nce. If the new bala nce is $20 or
finance cha rge i 1.5% of the o ld bala t should be
nce. O therwise, the min imu m pay men
payment should be the enti re new bala
balance above $20.
$20 plus 10% of the amo unt of the new
Cli ck
k( ... ) Han dles btn Cal cul ate.
Priv ate Sub btn Cal cula te_ Clic Pay men t As Dou ble
dits , new Bala nce, min
Dim oldB alan ce, cha rges , cre
, cre dits )
Inp utD ata( oldB alan ce, cha rges min Pay men t)
lanc e, cha rges , cre dits , new Bala nce,
Cal cula teN ewV alue s(ol dBa
Pay men t)
Dis play Dat a(ne wBa lanc e, min
End Sub
FIGURE 5.14 Eve nt proc edur e for Exer cise 12.
tgage. See Fig. 5. 15.
Wri te a prog ram to calculat e the mon thly va lues assoc iated with a mor
13. paid each
edure shown in Fig. 5. 16. The inte rest
The program hould use the even t proc
l = I [§) I. . f l .. 1

Annual rate of Interest: 5

Monthlypayment : 1932 .56

Beg . of month balance : 3578 19.11

Calculate Data for Month

Interest paid for month : S1,490.91

Reduction of princi pal: 5441.65

End of month balance : 5357.377.4 6

FIGURE 5.15 Sample outp ut for Exer cise 13.


5.3 Sub Procedures, Part ll • 20 1

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


Dim annualRateO finterest, monthlyPayme nt, begBalance As Double
Dim intForMonth, redOfPrincip al, endBalance As Double
InputData(an nualRateOfin terest, monthlyPayme nt, begBalance)
Calculate(an nualRateOfin terest, monthlyPayme nt, begBalance,
intForMonth, redOfPrincip al, endBalance)
DisplayData( intForMonth, redOfPrincip al, endBalance)
End Sub

FIGURE 5.16 Event procedure for Exercise 13.

mon th is the monthly rate of interest applied to the balance at the beg inning of the month.
Each month the redu ctio n of principa l eq ua ls the monthly payment minus th e in terest
pa id. A t an y time, th e ba lance of th e mo rtgage is the amo unt sti ll owed; that is, the a mo unt
req uired to pay off the mortgage. The end of month ba lance is ca lculated as [beg inning of
mo n t h ba lance] - [redu ction of principal] .
14. Write a program to determine a person 's weekly pay, wh re they rece ive ti me-and -a- halffo r
overtime wo rk beyo nd fo rty hours. See Fig. 5.17. The p rogram should use the event proce-
dure shown in Fig. 5. 18 .

g .J Weekly Pay

Hours worked: 42 Hourly pay :

Calculate Overtime Hours and Week's Pay

Overtime hours worked : 2

Week's pay : 30.

FIGURE 5.17 Sample o utpu t for Exercise 14.

Private Sub btnCalculate Click( ... ) Handles btnCalculate .Click


Dim hours, payPerHour, overtimeHour s , pay As Double
InputData (hours, payPerHour)
CalculateVal ues(hours, payPerHour, overtimeHour s , pay)
DisplayData( overtimeHour s, pay)
End Sub

FIGURE 5.18 Event procedure for Exercise 14.

Solutions to Practice Problems 5.3

1. age bef o re age

2. S ince scme is a stri ng va ri ab le, its d eFa ult va lu e is the keywo rd Noth ing. Th e ass ignme n t oF Nothing roa n a rgu-
ment makes Visua l Basic ne rvo us. ThereFore, to keep Visua l Basic happy, we will ass ign th e empty st ring to
S tring va ri ab les t hat a re p<~ssed to proced ures . That is, we will c ha nge the FirsL lin e ins id e th e eve nt procedure
to Dim state As String = " .. .

S ince the deFa ul t va lue oF the n ume ri c va ri ab le /JO/J is 0, Visua l Bas ic has no iss ue wit h pass in g tha t va lu e ro
a S ub proced ure.
202 • Cha pter 5 Ge nera l Procedures

5.4 Modular Design

Top-Down Design
an eve nt proced ure
soft war e usu all y req uire s larg e programs. Wr itin g the cod e for
Ful l-fea tured pro gra mm ers
ic pro gra m mig ht pos e a com plic a ted pro ble m. On e me tho d
in uch a Visual Bas div ide it into sma ller, less co m-
a com p lica ted pro ble m mo re und erst and able i to
use to mak e bre ak up a large prob-
s. Rep ea ted ly usin g a "div ide- a nd -co nqu e r" app roach to
plex subp rob lem ent is par t of a
sub pro blem s is call ed step wis e refi nem ent . Ste pwi se refinem
lem into ma ller , in wh ich the mo re ge neral
gra ms kno wn as top -do wn des ign
large r met hod ology of writ ing pro nem ent occ ur be low. Top-
top of the des ign and tasks rep rese ntin g the ir refi
tasks occ ur nea r the anc e progra mm ing pro-
stru ctu red pro gra mm i ng eme rged as tec hn iques to enh
dow n des ign and in. Th ey also pro duc e
use lead s to pro gram s tha t are eas ier to read and ma inta
ductivity. The ir and correc t.
few er init ial erro r , wit h the se erro rs bei ng eas ier to find
programs con tain ing like lih ood of intr odu cin g new
en suc h pro gram s are late r mo difi ed , the re is a mu ch sma ller
Wh
erro rs. or mo dul es, tha t
top -do w n des ign is to bre ak a pro ble m into ind ivid ua l tasks,
Th e goa l of m. First, a pro ble m is re rate d
udo cod e, flow cha rts, or a progra
ca n eas il y be tran crib ed into pse t rem a in too co mp lex are
ple r pro ble ms dep icte d as mod ules. An y mod ules tha
as sev e ral sim sma lles t mo dul es can
her. Th e pro cess of refi ning mo dul es con tinu es unt il the
bro ken dow n furt tion of wh at task s
. Eac h stag e of refi nem ent add a mo re comple te spe c ifica
be cod ed directly the ge ner al to the spe cifi c.
in top -do wn des ign is to go from
mu st be perfo rmed. Th e ma in idea be pic ture d using a hie rarc hy
pro cess of div idin g and o rgan izing a pro ble m into tasks ca n
Thi s :
ign, cer ta in criteria sho uld be met
cha rt. Wh en using top -down des
le size .
able and em pha size mall mo du
1. Th e des ign hould be eas ily read ch art.
l to specifi c a you read down the
2. Mo du les proceed from gen era
Tha t is, the y sho uld perfo rm
e mod u les, as mu ch as pos s ible, sho uld be single min ded.
3. Th
on ly a sing le we ll-defin ed ta k. , and any re lati ons hip s
sho uld be ind epe nde nt of eac h oth er as mu ch as poss ible
4. Mod ules
ed.
amo ng mod ules shou ld be specifi
tes th is process.
Th e follow ing exa mpl e illu stra

m tha t giv es
1 5. 19 is the beg inn ing of a hie rarc h y ch art for a pro gra
-./' Examp le Figu re
loan , the dur atio n (in years),
e inp uts are the am oun t of the
info rma t ion abo ut a car loan. Th t and the amo unt of inte rest
rate . Th e out put con sist s of the mo nth ly pay men
and the inte rest a ining the inp u t, mak-
t mo nth . In the bro ade st se nse , the progra m call s for obt
paid fo r the firs as the first row of a
, and disp lay ing the out put . Fig ure 5.19 shows these task s
ing calcu lati ons
hie rarc hy cha rt.
Car
loan

Display
Make
Get results
calculations
input
for the car loan pro gram .
FIGURE 5.19 Beg inn ing of a hier arch y cha rt
5.4 Mod ular Des ign
• 203

Each task can be refin ed into more spec ific


ubtas ks. (See Fig. 5.20 for the fina l hiera rch y
char t.) Most of the ubtas ks in the third row
are stra ightfo rward and do no t requi re furth
refin emen t. Fo r insta nce, the first mon th's inter er
est is comp uted by mult iplyi ng the amo unt of
the loa n by one- twe lfth of the annu al rate of
interest. The mo t co mpli cated subtask, th com-
putat io n of t he mon thly paym ent, has bee n
broken down furth er. Thi task is carri ed out
apply ing a stand ard fo rmul a foun d in finan ce by
book s; howe ve r, the formula requi res the num
of paym ents. ber

Car
loan

Get Make Display


input calculations results

Get Get Get Compute Compute Display Display


amount duration interest monthly 1st month 's headings amounts
rate payment interest

I
Calculate Apply
number of payment
month s formula
FIGURE 5.20 Hiera rchy chart for the car loan progr am.

It is clear fro m the hiera rchy chart that the


top modu les manipu late the modu les benea th
them . Whi le the highe r-leve l modu le cont ro
l the fl ow of the program, the lowe r-leve l modu
do th actua l wo rk. By des igning the top modu les
les first, we can de lay specific processing decis
io ns.

Structured Programming
A prog ram is sa id to be struc tured if it meet
s mode rn tand ards of prog ram de ign. A ltho
there is no fo rmal defin iti on of the term struc ugh
tured prog ram, co mput er cient i t agree that
such prog rams should have modu lar des ign and
use only the three types of logic al struc tures di
cussed in C h apter 1: eque nces , dec ision s, and s-
loops.
Sequ ence s: S tatements are exec uted one after
ano th er.
Decisions: O ne of seve ral blocks of program cod
is exec uted based on a test for some cond ition
.
Loops (itera tion) : O ne or more state ments are exec
uted repea tedly as lo ng as a spec ified cond i-
t ion is tru e.

O ne majo r short co ming of the earlie t prog


ramm ing languages was the ir relian ce on the
Go To state ment . This tate ment was used to
bran ch (that is, jump ) fro m o ne line of a prog
to anot her. It was comm on fo r a program to ram
be composed of a convo luted tang le of jumps
bran ches that produced co nfusing code referr and
ed to as spag hetti code . At the hea rt of struc tured
prog ramm ing is th e asse rti on of E. W. O ijkstr
a that G oTo state ment s sho uld be e limin ated
entir e ly beca use they lead to co mplex and confu
sing prog rams. Two Italia ns , C. Bohm and G.
Jaco pini , we re ab le to prov e that Go To state ment
s are not need ed and that any program ca n be
writt en using o nly th e three types of logic struc
tures disc ussed befo re.
204 • Cha pter 5 Gene ra l Procedures

s, decisions,
a ll prog rams be writ ten using sequence
S tru ctu red prog ramm ing requires that such a GaT os,
is allowed. All o ther logic a l cons truc ts,
and loops. Nes ting of such state men ts char t that flows
ed prog ram can be pictu red using a flow
are no t allowed. The logic of a stru ctur of a fl ow-
ruct ured bran chin g (G aTos ). The port ion
smo othl y from top to bott om with out unst ther efor e, is not
equivale nt of a GoTo state men t and,
char t sh own in Fig. 5.2l (a ) cont ains the s from the top
of the flow char t in whic h the log ic flow
struc ture d . A correctly struc ture d vers ion
to the bott om appe ars in Fig. 5.21 (b).

Let Let
b= a + c a = b+ c

Let
b= a + c
No

Let
b= a + c

a GoT o state men t.


FIGURE 5.21 Flow char ts illus tratin g the remo val of

g
Advantages of Structured Programmin
to crea te corr ect prog rams that are
easy to writ e, debug,
The goal of struc ture d prog ramm ing is a lo ng with a
a close r look at the way mod ular des ign,
unde rstan d , and chan ge. Let us now take
ribu tes to atta inin g these goals.
limi ted num ber of log ical struc tures, cont

1. Easy to write .
to look at
er's prod uctiv ity by allow ing him or her
Mod ular design increases the prog ramm ng, the prog ramm er
ils later. Duri ng the actu a l codi
the big pictu re first and focus on the deta t an enti re
prog ram and does not have to thin k abou
works with a man agea ble chun k of the
com plex program.
ility for a
le large program, ach taki ng respo nsib
Seve ral programmers can work on a sing
spec ific mod ule.
writ e than
rams requ ire sign ifica ntly less time to
Studies h ave show n that struc ture d prog
stan dard programs.
iring the
ram can be reu ed in o th er prog rams requ
Ofte n , procedures writ ten for one prog d, beca use
ing a prog ram, but reliab ility i enh ance
ame task. N ot only is time aved in writ be used m
d and debu gged. A proc edur e that can
reused procedur es wi ll already be teste
man y programs is said to be reus able .
5.4 Mod ular Design
• 205

2. Easy to debug.
Because each procedure is pecialize d
to perform just one task or seve ral rela
cedu re can be checked indi vidu ally to ted tasks, a pro-
dete rmin e its reliab ility. A dum my prog
driver, is set up to test the procedure. ram, ca lled a
The driv er con tains the min imu m defi
to call the proc edur e to be tested. For nitio ns needed
insta nce, if the procedure to be tes ted
the driver program ass igns d iverse va is a func tion ,
lues to the arguments and then exam
spond ing func tion retu rn va lu es. The ines the corre-
argumen ts should con tain both typical
ca e va lues. and spec ial-
The program can be tested and debugged
as it is bein g des igned with a tech n ique
stub programming. In th is tech niqu kno wn as
e, the key even t procedures and perh
sma ller procedure are cod ed first. Dum aps som e of the
my procedures, or stub s, are wr itten for
ing procedu res. Init ially, a stub procedu the remain-
re might con sist of a message box to
the proc edu re has been called, and ther indi cate that
eby conf irm that the procedure wa
right t ime. Late r, a stub migh t simply call ed at the
disp lay va lues passed to it in orde r to con
that the procedure was call ed, but also firm not only
that it rece ived the co rrec t valu es from
proced ure. A stub also can ass ign new the calling
va lues to one or more of its para met ers
eith er inpu t or co mpu tat ion. Thi s prov to imulate
ides grea ter con trol of the con ditio ns
The stub proced ure is alway simpler be ing tes ted.
than the actual procedure it rep rese nts.
stub prog ram is only a skeleton of the Alth oug h the
fina l program, the program's stru ctur
deb ugged and tested. (Th e stub prog e can sti ll be
ram con sists of some coded procedur
procedu res.) es and the stub
O ld -fa hion ed unst ruct ured program
s con ist of a sequence of inst ru ctio
grouped for specific tasks. The logic of ns that are not
such a prog ram is clut tere d with deta ils
difficu lt to follow. Nee ded tasks are and therefore
easily left out and cru cial details eas
Tricky parts of the program ca nno t be ily neglected.
isolated and exa min ed. Bugs are diffi
becau e they mig ht be present in any cult to loca te
part of the program.
3. Easy to understand.
The inte rcon nec tions of the proced ures
revea l the modu lar design of the prog
ram.
The mea ning ful procedure names, alon
g with re leva n t com ments, ide ntify the
formed by the modules. tasks per-
The meaningful var iab le names help
the prog rammer to reca ll the purpose
4. Easy to change. of each va riab le.

Because a stru ctur ed program is elf-d


ocum enti ng, it can easily be dec iphe
programmer. red by ano ther
Modifying a stru ctur ed program ofte
n amo unts to inserting or alte ring a
rath er than revising an entire complex few procedure
program. The programmer doe not eve
look at most of the program . Thi s is n hav to
in sharp con trast to the situ at ion with
programs, where one must und ersta nd unst ruct ured
the enti re logic of the prog ram before
can be made with con fide nce. any cha nges

Object-Oriented Programming
An obje ct is an encapsul at ion of data
and code that ope rates on the data. Like
hav e prop erties, respond to met hod s, con trols, objects
and raise eve n ts. The mos t effe ctive type
for com plex prob lems is call ed obje of prog ram min g
ct-oriented design. A n obje ct-o rien
viewed as a coll ection of coop e ratin g ted prog ram can be
object . Man y mod ern prog ramme rs use
tion al stru ctur ed prog ram min g alon g a blend of tradi-
with obj ect-orie nted des ign.
Vi ual Basic. NET was the first vers ion
of Visua l Basic that was truly obje ct orie
every ele men t such as a con trol or a strin nted; in fact,
g is actually an object. Thi s book illustrate
s the building
206 • Cha pter 5 Gen eral Procedures

toge th e r u ing o bj ect- o rien ted


rly ch apte r and the n puts the m
bloc ks of Visu a l Ba ic in the ea app roac h i take n whe n eve r
ho ut the boo k, an obje c t-orien ted
tech niqu es in C h apte r 11. Thr oug
feas ible .

A Relevant Quote
Dirk Gen tly's Holistic Detective Age
ncy, by Do u-
io n wit h a few para grap hs from
W e end this sect
198 7:
glas Ada m , S imo n & Sch uster,
to teac h any thin g to anybody?"
"W hat rea lly i the poin t of tryin g up and dow n the
murmur of ymp athe tic approva l from
Thi quest ion eemed to provoke a
table. and somethi ng, the
i th at if you rea lly wan t to und erst
Richard con tinu ed, "Wh at l mea n ort it out in your own mind.
is to try and exp lain it to som eon e else . Tha t forces you to
best way th ings down into
mor e low and dim -w itted your pupil , the more you have to brea k
And the By the time you've
mor e simp le idea s. And that 's rea lly the esse nce of prog ram ming.
more and e can dea l with , you've
littl e steps that eve n a stup id mac hin
sorted out a complicated idea into y lear ns more than the pupil.
ly lear ned som ethi ng abo ut it yourself. The teac her u uall
ce rtain
Isn't that true?"

5.5 A Case Study: Weekly Payroll


de. Tab le 5.3 sh ows
y proc esse s a wee kly pay ro ll usin g the 200 9 Em p loye r's Tax Gui
Thi s case stud ldin g a llow an ce is som etim es
payro ll offi ce. (No te: A wit hho
typi ca l data used by a com pa n y's the info rma tio n in Ta ble 5.4
as an exem JJtio n.) The se data a re pro cessed to pro d uce
refe rred to prog ra m sh o uld requ est
p lied to eac h emp loye e a lo ng wit h his o r h er pay ch eck . The
tha t is sup to tha t in Tab le 5.4.
Tab le 5.3 fo r an indi v idua l as inp ut and pro duc e o utp ut simil ar
the data fro m

lltN!II. Employee data .


Prev ious
Mar ital Year-to-Date
Hou rly Hou rs Wit hholding
Stat us Ear ning s
Wage Wo rked Allowan ces
Nam e
Married $88,600.00
38 4
A I Cla rk $45.50 $68,200.00
3 Married
$44.00 35
An n Mi ller 1 Single $30,604 .75
$ 17.95 50
Joh n Smith 2 Single $36,295 .50
$25.50 43
Sue Taylor

Payroll information .
IliN IIt • Yr. to FIC A Inco me C heck
Cu rren t Tax W h. A mou nt
Dat e Ea rnin gs Tax
Nam e Ea rn ings
$ 163.44 $ 1,433.29
$90,329 .00 $132.27
A l C lark $1,729.00

ca lcul ated as fo llows:


The item s in Tab le 5 .4 sh o uld be
-a- h a lf afte r 40 ho urs)
t Ear nin gs : ho urly wag e tim es h o urs wo rked (wi th tim e-an d
Cur ren
ea rnin gs
r-to -da te earn ing plu curr ent
Year- to-Date Earnings: prev io us yea
ings (soc ia l secu rity ben -
: sum of 6.2% of earn ings if part of the first $ 106 ,800 of earn
FIC A Tax
(Me d icar e tax )
efit s tax) and 1.45 % of earn ings
5.5 A Case Stud y: Weekly Payroll
• 207

Fede ral Inco me Tax Wit hheLd: subt ract $


70.19 from the c urren t earn ings for each
allow ance a nd use Tab le 5.5 o r Tab le 5.6, with ho lding
depe ndin g on mari tal sta tus
Che ck Amo unt: [c urren t earn ings] - [FIC
A taxes ] - [inco me tax with he ld]

lt4:J!IJW 2009 Federal income tax withheld for a single perso


n paid weekly.
Adj usted Week ly Income Income Tax Withheld
$0 to 138 $0
Over $138 to $200 10% of amou nt over $138
Over $200 to $696 $6.20 + 15% of amou nt over 200
Ove r 696 to 1,2 79 $80.60 + 25% of amou nt over $696
Over $1,279 to $3,338 $226.35 + 28% of amou nt over $1,279
Over $3,338 to 7,2 12 $802.87 + 33% of amou nt over $3,338
Ove r 7,212 $2,08 1. 29 + 35% of amount ove r 7,212

lt!1:J!IW 2009 Fede ral income tax withheld for a marri ed perso
n paid weekly.
Adjusted Weekly Income Income Tax Withheld
$0 to $303 $0
Over $303 to $4 70 10% of amou nt over $303
Over 4 70 to 1,455
$ 16.70 + 15o/oofa moun t over $470
Ove r $1,455 to $2,272
164.45 + 25% of amou nt ove r 1,455
Over $2,272 to 4,165
$368.70 + 28% of amount ove r 2,2 72
Over $4,1 65 to$7 ,321
898.74 + 33% of amou nt over $4,1 65
Over 7,321
1,940.22 + 35% of amou nt over $7,32 1

Designing the Weekly Payroll Program


Afte r the data for an e mp loyee from Ta ble
5.3 h ave been inpu t, the prog ram must com
five a mo unts appe a ring in Tab le 5.4 a nd pute the
then displ ay the payr o ll info rmat io n. The
puta tions form the basic tasks of the prog se fiv e co m-
ram:
1. Com pute c urren t earn ings.
2. Com pute year- to-da te ea rnin gs.
3. o mpu te FICA tax.
4. Com pute fede ral inco me tax with held .
5. Com pute payc heck amo unt (tha t is,
take -hom e pay) .
Task 1, 2, 3, a nd 5 a re fairly imp le. Each
invo lves app lying a form ula to give n data.
insta n ce, if h ours work d are at mos t (Fo r
40, then [C urre nt Earn ings] = [H o urly
[Ho urs Wor ked] .) Thu s, we won 't brea k W age] time s
dow n these tasks an y furth er. Task 4 is mo
cated , so we cont inu e to divid e it in to sma re co mpli -
ller subtasks.
4. Compute federal income tax withheld
. First, the e mplo yee's pay is adju sted fo r with
a llow an ces, a nd then the a mou nt of inco h o lding
me tax to be with he ld is com pute d. The
tion of the inco me tax with he ld differs for co mpu ta-
marr ied and sing le indiv idu a ls. Task 4 is,
fore, divid ed into the fo llow ing subt asks: there-

4.1 Com pute pay ad justed by with ho lding


a llow ances.
4.3 Com pute inco me tax with held fo r sing
le e mp loyee.
208 • Cha pter 5 Gen e ra l Procedur es

ried emp loyee.


4.3 Com pute inco me tax with he ld for mar
lem.
s the tepwise refinem ent of the prob
The hierarch y cha rt in Fig. 5.22 show

Give payroll
inform ation

Compute Compute Display


Compute Compute Compute
Validate income tax take- home info
current tot aI ea rni ngs FICA tax
and input withh eld pay
data ea rn ings to date

Adjust pay Withh eld Withh eld


(single) (married)
by withholding
allowances
oll prog ram.
FIGURE 5.22 H ierar ch y char t for the wee kly payr

nt Procedure
Pseudocode for the Display Payroll Eve
VAL IDA TE data (Fun ctio n Dat aOK)
Inpu tDa ta )
INP UT emp loyee data (Sub procedu re
(Fun ctio n Gross_Pay)
CO MP UTE CU RRE NT GRO SS PAY
DATE (Fun ctio n Tota l_Pay)
CO MP UTE TOT AL EAR NIN GS TO
A_Tax )
CO MP UTE FIC A TAX (Fun ct ion FIC
WIT HH ELD (Fun ct ion Fed_ Tax )
COM PUT E INC OME TAX
Adjust pay for with hold ing allowa nces
If emp loyee is sing le The n
ELD (Fun ctio n Tax S ingle)
CO MP UTE IN CO ME TAX WIT HH
Else
D (Fun ctio n Tax Mar ried)
CO MP UTE INC OM E TAX W ITH HEL
End If
(Fun cti on Net _Ch eck )
CO MP UTE PAYCHEC K AM OU NT
(Sub procedur e Sho wPa yroll )
DISPLAY PAYROLL INF ORM ATI ON

Writing the Weekly Payroll Program


. Tab le 5. 7 h aws
ca lls a sequ ence of seve n proc edur e
The btnD ispl ay_C lick eve nt proced ure
o rm the tasks.
the tasks and the procedur es that perf

IM:J!IW Tasks and their procedures.


Proc edur e
Task
Data OK, lnpu tDat a
0. Va lidat e and inpu t employee data
Gros s_ Pay
1. Com pute current ea rnin gs.
Tota i_Pay
2. Com pute year-to-d ate ea rnin gs . FICA _Tax
3. Com pute FICA tax. Fed_Tax
.
4. Com pute federa l inco me tax with held Fed_ Tax
4.1 Com pute adju sted pay.
le emp loyee. TaxS ingle
4.2 Compu te amo unt with held for sing
lJ for marr i d employee . Tax Marri ed
4.3 omp ute amo unt wirh h
Net_C heck
5. Com pute payc heck amo unt. S how Payro ll
6. Disp lay payroll infor mation.
5.5 A Case S tud y: Weekl y Pay ro ll
• 209

The Program and the User Interface


Figur e 5. 23 a nd Ta b le 5.8 d e fin e th e use r inte
rface fo r the W eekl y Payro ll Progr a m . Figur e
5. 24
h a ws a sa mple o utput .

l\leekly Pay roll


~I I~
ll _,
§
..---
Employee name: ls.::;l. esu lt:s

Houm•wage :

Number of hours worked:

Number of withholding
allowances:
Total pay prior to this week:

Marital Status
Single Married
I
I
Display Payroll Next Employee Quit

FIGURE 5.23 Form for weekl y payro ll progr am.

lf;1:J!JJ:M Objects and initial properties for the weekly payroll program.
Objec t Prope rty Settin g
frmPay ro ll Tex t Week ly Pay ro ll
lblN ame Text Emp loyee name :
txtN ame
lblWage Text Hourl y wage:
txt Wage
lblHo urs Tex t Numb er of hours worked:
txtHo urs
lblAII owan ces Au toS ize False
Tex t Numb er of wi thh o lding all owan ces:
txtAll owan ces
lbiPri orPay Tex t Tota l pa y pri o r to this week:
txtP riorPay
grpM arita l Tex t Marit a l S tat us:
radS ingle Tex t S ingle
radM arri ed Tex t Marri ed
btnOi splay Tex t Display Pay ro ll
brnN ex t Text ex t Employee
brnQu it Tex t Qu it
lstRes ults Fo nt Couri er New
210 • Chap ter 5 Gene ral Proced ure

a .. Week ly ayroll
l = I @] /-t:S d
~

~ a y roll r e::ml "t3 ::or Al Adall13


Employee name : .AJ A.dams

Gro3 3 p a y -chi3 p e=io d : $1,7 29 . 00


Hourly •Nage: 5.5
Year - -co - da-ce e arnin g3 : $9 0,32 9 _0 0
Number of hours worked :
lB
$132 ~ 27
FICA "tax -chi3 p e riod :
Number of withholding
allo•Nances : $1f3 . 44
Income tax with he ld :
Total pay prior to this week : BBSGO
Ne -e pay •, chec k amou nt ): $ 1,43 3.29
Marital Status
Single .g Married I

[ Display Payroll ) [ Next Employee


I [ Quit
I
FIGURE 5.24 Sample outpu t of weekl y payro ll probl em.

) Hand les btnD ispla y.Cl ick


Priv ate Sub btnD ispla y_ Clic k( ...
Dim empName As Strin g = 'Nam e of empl oyee
Dim hrWa ge As Doub le 'Hou rly wage
Dim hrsW orke d As Doub le 'Hou rs work ed this week
s
Dim allow ance s As Inte ger 'Num ber of with hold ing allow ance
for empl oyee
Doub le 'Tot al pay for year excl udin g this week
Dim prev Pay As for Mar ried
Dim mSta tus As Strin g
II U 'Mar ital stat us: S for Sing le; M
'Thi s week 's pay befo re taxe s
Dim pay As Doub le week
Dim tota lPay As Doub le 'Tot al pay for year inclu ding this
'FICA tax for this week
Dim ficaT ax As Doub le week
Dim fedT ax As Doub le 'Fed eral incom e tax with held this
'Pay chec k this week (take -hom e pay)
Dim chec k As Doub le
'Ver~fy and obta in data , comp ute payr oll, disp lay resu lts
If Not DataO K() Then &
piec e of requ este d data is miss ing"
Dim msg As Strin g = "At leas t one
" or is prov ided impr oper ly."
Mess ageB ox .Show (msg )
Else 'Task 0
, allow ance s, prev Pay, mSta tus)
Inpu tData (emp Nam e, hrWa ge, hrsW orked 'Task 1
)
pay = Gros s_ Pay( hrWa ge, hrsW orked 'Task 2
total Pay = Tota l_ Pay( prev Pay, pay)
'Task 3
total Pay)
ficaT ax = FICA_ Tax( pay, prev Pay, 'Task 4
s, mSta tus)
fedT ax = Fed_ Tax( pay, allow ance 'Task 5
fedT ax)
chec k = Net_ Chec k(pa y, ficaT ax, 'Task 6
Pay, ficaT ax, fedT ax, chec k)
Show Payro ll(em pNam e, pay, total
End If
End Sub

les btnN ext.C lick


Priv ate Sub btnN ext_ Clic k( . . . ) Hand
radi o butt ons for next emp loye e's data
'Cle ar all text boxe s and
txtN ame. Clea r ()
txtW age. Clea r()
txtH ours .Cle ar()
5.5 A Case Study: Weekly Pay roll
• 211

txtAl lowan ces.C lear()


txtPr iorPa y.Cle ar()
radSi ngle . Check ed = False
radMa rried. Check ed = False
lstRe sults. Items .Clea r()
txtNam e. Focus ()
End Sub

Priva te Sub btnQu it Click ( . .. ) Handl es btnQu


it.Cli ck
Me. Close ()
End Sub

Funct ion DataO K() As Boole an


'Task 0: Valid ate data
If (txtNa me.Te xt = "" ) Or (Not IsNum eric(t
xtWag e.Tex t)) Or
(Not IsNum eric(t xtHou rs.Tex t)) Or (Not IsNum
eric(t xtAllo wance s.Tex t)) Or
(Not IsNum eric(t xtPrio rPay. Text) ) Or
(( Not radSin gle.C hecke d) And (Not radMa rried.
Check ed)) Then
Retur n False
Else
Retur n True
End If
End Funct ion

Sub Input Data( ByRef empName As Strin g, ByRef


hrWag e As Doubl e ,
ByRef hrsWo rked As Doubl e , ByRef allow ances
As Integ er ,
ByRef prevP ay As Doubl e , ByRef mStat us As
Strin g )
•~ask 0: Input data
empName = txtNa me.Te xt
hrWag e = CDbl (txtW age.T ext)
hrsWo rked = CDbl (txtH ours.T ext)
allow ances = Cint (txtAl lowan ces . Text)
prevP ay = CDbl ( txtPri orPay .Text )
If radMa rried. Check ed Then
mStat us "M"
Else
mStat us "S"
End If
End Sub

Funct ion Gross Pay( ByVal hrWag e As Doubl e


,
ByVal hrsWo rked As Doubl e ) As Doubl e
Task 1: Compu te weekl y pay befor e taxes
If hrsWo rked < = 40 Then
Retur n hrsWo rked * hrWag e
Else
Retur n 4 0 * hrWag e + (hrsW orked - 40) * 1.5
* hrWag e
End If
End Funct ion

Funct ion Total _ Pay( ByVal prevP ay As Doubl


e , ByVal pay As Doubl e ) As Doubl e
'Task 2: Compu te total pay befor e taxes
Retur n prevP ay + pay
End Funct ion
212 • Chap ter 5 Gene ral Procedu res

le , ByVa l prevP ay As Doub le ,


Func tion FICA_ Tax( ByVa l pay As Doub
ByVa l total Pay As Doub le ) As Doub le
'Tas 3 Comp ute soc al se• r t a d Medi care tax
'Soc ial secu rity tax for this week
Dim soci alSe curit y As Doub le
'Med icare tax for this week
Dim medi care As Doub le
'Sum of abov e two taxes
Dim sum As Doub le
Cons t WAGE BASE As Doub le = 10680 0
If total Pay <= WAGE _ BASE Then
soci alSe curit y = 0.062 * pay
Else if prevP ay < WAGE BASE Then
- prevP ay)
soci alSe curit y = 0.062 * (WAGE BASE
End If
medi care = 0.014 5 * pay
sum = soci alSe curit y + medi care
'Roun d to near est cent
Retu rn Math .Roun d(sum , 2)
End Func tion

le , ByVa l allow ance s As Integ er ,


Func tion Fed_ Tax( ByVa l pay As Doub
ByVa l mSta tus As Strin g ) As Doub le
with held round ed to 2 decim al plac es.
'Task 4· Compu e fede ra i come tax
Dim adjPa y As Doub le
Dim tax As Doub le 'Unro unde d fede ral tax with held
'Task 4.1
adjPa y = pay - (70.1 9 * allow ance s)
If adjPa y < 0 Then
adjPa y = 0
End If
If mSta tus = "S" Then
tax TaxS ingle (adjP ay) 'Task 4.2
Else
tax = TaxM arrie d(adj Pay) 'Task 4.3
End If
Retu rn Math .Rou nd(ta x, 2) 'Roun d to near est cent
End Func t i on

Doub le ) As Doub le
Func tion TaxS ingle ( ByVa l adjPa y As
'~ask 2: Comp ute fede ra ax 1thh eld for cing le perso n .
Sele ct Case adjPa y
Case 0 To 138
Retu rn 0
Case 138 To 200
Retu rn (0.1 * (adj Pay- 138))
Case 200 To 696
Retu rn 6.2 + 0.15 * (adjP ay - 200)
Case 696 To 1279
Retu rn 80.6 + 0 .25 * (adjP ay - 696)
Case 1279 To 3338
1279)
Retu rn 226.3 5 + 0.28 * (adjP ay
Case 3338 To 7212
Retu rn 802.8 7 + 0.33 * (adj Pay- 3338)
Case Is > 7212
7212)
Retu rn 2081 .29 + 0.35 * (adjP ay -
End Sele ct
End Func tion
5.5 A Case Stud y: Wee kly Payroll
• 213

Fun ctio n Tax Mar ried ( ByV al adjP


ay As Dou ble ) As Dou ble
'Tas k 4.3: Com pute fede ral tax
with held for mar ied pers on.
Sele ct Case adjP ay
Case 0 To 303
Retu rn 0
Case 303 To 470
Retu rn 0 . 1 * (ad jPa y- 303)
Case 470 To 1455
Retu rn 16.7 + 0.15 * (adj Pay 470)
Case 1455 To 2272
Retu rn 164 .45 + 0.25 * (adj Pay
- 1455 )
Case 2272 To 4165
Retu rn 368 .7 + 0.28 * (adj Pay
- 2272 )
Case 4165 To 7321
Retu rn 898 . 74 + 0 . 33 * (adj Pay
- 4165 )
Case Is > 7321
Retu rn 194 0.22 + 0.35 * (ad
jPa y- 7321 )
End Sele ct
End Fun ctio n

Fun ctio n Net_ Che ck( ByV al pay


As Dou ble , ByV al fica Tax As
Dou ble ,
ByV al fedT ax As Dou ble ) As Dou
ble
'Tas k 5: Com pute amo unt of mon
ey paid to emp loye e
Dim chec kAm ount As Dou ble =
pay - fica Tax - fedT ax
Retu rn chec kAm ount
End Fun ctio n

Sub Sho wPa yrol l( ByV al empName


As Stri ng , ByV al pay As Dou
ble ,
ByV al tota lPay As Dou ble , ByV
al fica Tax As Dou ble ,
ByV al fedT ax As Dou ble , ByV
al chec k As Dou ble )
'Tas k 6: Dis play resu lts of
pay roll com puta tion s
lstR esu lts . Item s.Cl ear( )
lstR esu lts.I tem s.A dd( "Pa yrol
l resu lts for " & empN ame)
lstR esu lts . Item s . Add ( "" )
lstR esu lts.I tem s.A dd( "Gro ss
pay this peri od:" & " " &
Form atCu rren cy(p ay))
l stRe sult s.Ite ms. Add ( "" )
l stR esu lts . Item s . Add ( "Ye ar-t
o-da te earn ings :" & " " &
Form atCu rren cy(t otal Pay ))
lstR esu lts.I tem s.A dd( "" )
lstR esu lts . Item s.Ad d( "FIC A tax
this peri od:" & " " &
Form atCu rren cy(f icaT ax))
lstR esu lts.I tem s.A dd( "" )
lstR esu lts . Item s.Ad d( "Inc ome
tax with held :" & " " &
Form atCu rren cy(f edT ax))
lstR esu lts.I tem s . Add ( "" )
lstR esu lts.I tem s.A dd( "Ne t pay
(che ck amo unt) :" & " " &
Form atCu rren cy(c heck ))
End Sub
214 • Cha pter 5 Ge nera l Procedures

Comments
a l secu rity ben efit
bee n take n to avo id co mpu ting soci
1. In the func tion FIC A_Tax , care has makes sure an
inco me in exc e s of $10 6 ,800 per yea r. The logic of the prog ram
tax on ng a give n wee k is
cro ses th e $ 106,800 thresho ld duri
empl oyee whose inco me fo r the year -date ea rnin gs.
$ 106,800 and the ir previous yea r-to
taxe d only on the diffe renc e betw een
inco rpo rate t he tax
TaxS ingle use Se lect Case bloc ks to
2. The two func tion s Tax Married and tax with held . The
fo r the amo unt of fed eral inco me
brac kets give n in Tables 5.5 and 5.6 C ase clause . Thi s
er limi t of each Cas e clau se is the sa me as th e lower li mit of the nex t
upp func ti on, will be
ay, such as 138.50 in the Tax Sin gle
ensures th at frac tion a l va lue fo r adjP
er sala ry rang
prop erly trea ted as part of the high

CHAPTER 5 SUMMARY
procedu res or oth er
a prog ram that is acce ssed by eve nt
1. A general procedur e is a po rtio n of procedur es and Sub
of gen eral proc edu res are Function
gen eral proc edu res. The two types
procedures .
ders and end ing with
bloc ks beg inni ng with Fun ctio n hea
2. Fun ction procedur es are defined in e in an exp ress ion and
ti on is exe cuted by a refe renc
End Fun ctio n stat eme nts. A func
retu rns a valu e.
end ing with End S ub
Sub proc edur es are defi ned in bloc ks beg inni ng with Sub headers and
3. of the na me of
nts. A Sub proc edu re is acce ssed (called) by a tate men t con sisti ng
stat eme
the proc edu re.
t must mat ch the
4. ln any proc edu re, the argumen
ts app eari ng in the ca lling tate men
The y nee d not
eme nt in num ber, type , and orde r.
parameters of the ub o r Functio n stat
h ave the sam e names.
ins in memo ry. (Th e
t i the peri od duri ng whi ch it rem a
5. The lifetime of a vari able or con stan s some valu e. )
ove r its lifetim e, but it alw ays hold
valu e of the vari able might cha nge
that can re~ r to it. A vari-
6. The scope of a va riable or con
stan t is the po rtio n of the prog ram
ha local scope and is
o r con stan t dec lare d insid e a Functio n, Sub , o r eve nt proc edu re
able
visible only inside the procedu re.
s into sma ller sub prob-
u lar design to refin e large prob lem
7. Structured fJrogramming uses mod e , dec isio ns, and
thre e log ical stru ctur es of sequ enc
lem s. Prog rams are cod ed using the
loop s.

JECTS
CHAPTER 5 PROGRAMMING PRO ld ente r the
prog ram to dete rmi ne a stud ent' s GPA . See Fig. 5.25 . The use r hou
1. Wri te a then clic k on the
ber of cred it hours for a co urse, and
grad e (A, B, C, D, or F) and the num r all his or her
sho uld then repe at this process fo
Record This Course butto n. The user k on the Calculate
bee n reco rded, t he user sho uld clic
courses. Aft er all the cour es hav e ality po ints fo r a
butt on. A Fun ctio n proc edu re sho uld be used to calc ulate the qu
G PA
to Exa mpl e 5 in Sec tion 5.1.
course. Hin t: Thi s prog ram is sim ilar
ks ($ 1.25) . Wri te a
s ($1.75) , fries ($2.00) , and soft drin
2. A fas t-fo od vendor sells pizza slice the qua ntit y of eac h
bill. The prog ram ho uld requ est
prog ram to com pute a cust ome r's ctio n proc edu re, and
ca lcul ate the tota l cost with a Fun
item o rd ered in a ub procedu re, in Fig. 5.26 .
ized bil l. A sample outp ut is sho wn
use a S ub procedu re to disp lay an item
Prog ram min g Proj ects
• 215

ll ,.. estauran Bi ll l= I §) l....t3 l


Grade (A.B. ...): _ Ho•.11 many pizza slices? 3
Credit hours : How many fries '> Compute
Total Cost
[ Record This Course How many soft drinks? 5
rr:::M QUA lUII Y p:;nc:::
Calculate GPA piz za .3li ce3 3 $3 . 25
:=r i e3 4 ,;;;8 .00
GPA : .3o: :t drin k3 ,; $6.2 .:.
IOil l..L
-¥ 19.~

FIGURE 5.25 For m design fo r FIGURE 5.26 Sample outp ut


Pro gram min g P roje ct 1. for
P rogr amm ing P roje ct 2.

3. A furn itur e man ufa ctur er mak


es two type s of furn itur e-c ha irs
is $35 0, the cos t per sofa is $92 5, and sofas. The cos t pe r cha ir
and the sales tax rate is 5%. Wr ite
inv oice form for an ord er. See Fig. a pro gram to crea te an
5.27 . Aft er the data o n the left
ent ered , the use r can disp lay an sid of Fig. 5.27 are VidcoN otc
invo ice in a list box by press ing
The use r can clic k o n the Clear th e Proc ess Order but ton. Ha rdwa re
Order Form but ton to clea r a ll tex t
and ca n clic k on the Quit but ton box es and the list box, ~ to re

to ex it the program. The invo ice (Hom ewor k)


cap ita lized first two lett ers of the num ber con s ists of the
custom er's las t nam e, fo llowed by
zip code. The cus to mer name is the last fo ur d igits of the
inp ut with the last name fir t, foll
space, and the first name. H owe owed by a com ma, a
ver, th e nam e is d isplaye d in the
ord er. The gen erati on of the invo invo ice in the pro per
ice num ber and the reord erin g of
sho uld be ca rrie d out by Fun ctio the first and last nam es
n pro ced ures .

D,. Furn iture Ord er Form

Customer name:
(Last , First) Smith. William
Inv oi ce Num ber : SM4 .:.01

Nam e : Ylill iam Sm ith


Address: 123 Geary Street
Add r e3s : 123 Gea r y Str
eet
Cit y : Ala med a, CA 94.: .01
Oty, State. Zip : AJam eda . CA 94501
Num ber a:: Cha ir3 : 4
Num ber a:: So:' :a3: 9
Number of
chairs ordered:
Ccs t: $9,7 2.:. . 00
Sal e3 Iax : $48 6.25
Number of
sofas ordered: Ict al Co3 t : $ 1 0 ,211 .2.:.

Process Order
Oear Order Form
Quit

FIGURE 5.27 Sam ple run fo r Prog ram min g Pro


ject 3.

4. Tab le 5.9 con ta ins seve n pro


ve rbs and thei r trut h values. Wri
thes e pro verb s one at a tim e and te a program tha t pres ents
asks the use r to eva lu ate th em as
gram sh ould the n tell th e use r how tru e o r fa lse. The pro-
man y que stio ns were answered co
rrec tly and display o ne
216 • Cha pte r 5 Gen era l Proced ure

lij1:JIID Seven pro verbs.


Tru th Val ue
Pro ver b
Tru e
se.
The sq ueaky whee l ge ts the grea Tru e
ry and yo u cry a lo ne. False
Opp osit es attract. Fa lse
d.
pare the rod and spo iI the chil Tru e
ds .
Act ions spe ak loud er tha n wor False
Famil iarity bree ds con tem pt. Tru e
re.
Ma rry in haste, repe nt at leisu
hology Today, A pri ll 988 .
rce: "You Know Wh at They Say ... ,"by A lfi e Koh n, Psyc
Sou

t (5 or 6 correc t), Yo u might


Perfec t (all correc t) , Exc e llen
of the fo llow ing eva lua tion s:
(less tha n 5 correc t).
co nsid er tak ing Psycho logy 101
ge the com put er to
up Sticks. Wr ite a pro gra m tha t allo ws the use r to cha llen
5. Five, Six, Pick num be r of
tick s. H ere is how the ga me is played. Th e use r ch ooses the
a gam e of Pic k-up-S com put er chooses wh o will go
firs t .
tch sti cks (fro m 5 to 50 ) to pla ce in a pile. Th en, the the pile . Th e
ma stic ks from
tur n , the con tes tan t can rem ove one, two, or thr ee ma tch
A t eac h 5. 28.
last ma tch stic k lose . See Fig.
con test an t wh o rem oves the

l!'r~J
g~ Five, Six, Pick up 5 ick5
= @] Hoo ray

] '--[_ _Be_g_in_a_N _a_m_e_- --'


_e_w_G I sele ct 2 m atc hstic ks. I win .
[ Give the Rules of the Game

How many matchsticks


would you like to pick up?
Current ~1 at us I OK I
of the pile: III

mm ing Pro j ect 5.


FIGURE 5.28 A possibl e out com e of Pro gra

ere the num ber of


r sho uld ma ke the use r alw ays sele ct from a pile wh
Th e co mp ute r init iall y chooses
a rem ain der of 1 wh en di vid ed by 4. For inst ance, if the use
ma tch sti cks has ided by 4, the n th e com put er
has a rema ind r of 1 wh en div
a num be r of ma tch stic ks tha t go firs t and rem ove th e prope
r
uld h ave the use r go firs t. O the rwi se, the com put er sho uld d 4).] Aft er
sho ide d by 4 is (n Mo
Th e remain der wh en n i div
num ber of ma tch stic ks. [Note: and obse rve tha t the com put er
pro gra m, play a few gam es wit h the com put er
wri ting the
alway wins.
R ep et it io n

6.1 Do Loops 218


• Pre test Form of a Do Loop • Pos ttes
t Form of a Do Loop
6.2 For . .. Next Loops 230
• Gen eral Form of a For ... Nex t Loo
p • Nes ted For .. . Nex t Loo ps
• Local Type Inference
6.3 List Boxes and Loops 243
• Som e Properties, Methods, and Eve
nts of List Boxes • List Boxes Pop ulat
• List Boxes Populated with Numbers ed with Strings
• Searching an Ordered List
Summary 251

Programming Projects 251

217
218 • Chap ter 6 Repetition

6.1 Do l oop s
t a seq uenc e of
ctur es in programming, is used to repea
A loop , one of the most impo rtan t stru variables
repe titio n, or pass, the sta teme nt ac t upon
state men ts a num ber of time s. At each
whose values are chang ing. cond ition
men t eith er as long as or unti l a ce rta in
The Do loop repeats a seq uenc e of state t foll ows the
ence of state men ts, and a Loop state men
is true. A Do state men t precedes the sequ ile" or the word
, preceded by either th e word "Wh
seq uenc e of state men ts. The cond ition
"Loop".
"Un til", follows the word "Do" or the word

Pretest Form of a Do Loop


of the form
Whe n Visual Basic enco unte rs a Do loop

Video ote Do Whi le con diti on


Do loops stat eme nt (s)
Loop
insid e the
. If condition is false, th en the state men ts
it first chec ks the truth value of condition r th e state men t Loop. If
co ntin ues with the line afte
loop are not execu ted, and the program state men t Loo p
e the loop are exec uted . Wh en the
condition is true, th en the state men ts insid ition in the Do
ated , begi nnin g with the test ing of cond
is enco unte red, the enti re process is repe uted a
men ts inside the loop are repe atedly exec
Whi le state men t. In othe r words, the state and flowchart
tru e. Figure 6.1 cont ains the pseud ocod e
long a (tha t is, whil e) the cond ition is
for this loop.

No
condition

Execute
Do Whi le c ondi ti on is t rue state ments
stat eme n t ( s ) within
Loop the loop

Execute
statements
that follow
the loop

with the cond ition tested at the top.


FIGURE 6.1 Pseudocode and flowchart for a Do loop
6.1 Do Loops
• 219

.; The follo wing prog ram, in whic h the cond


ition in the Do loop is "nun> <= 7",
d isplays the nu mbers fro m 1 thro ugh
7. (Af ter the Do loop term inat es, th e vhlu
be 8.) e of num will

Priv ate Sub btn Dis play_ Clic


k( .. . ) Han dles btn Dis play .Cli
'Dis play the num bers from ck
1 to
Dim num As Inte ger = 1
Do Whi le num <= 7
lstN umb ers . Item s.Ad d(nu m)
num += 1 'Add 1 to the valu e of num
Loo p
End Sub

[Run , and clic k on t he butt on. The follo


w ing i displaye d in the list box .]
1
2
3
4
5
6
7

Do loops can be used to en ure that a prop


er response is rece ived from the lnpu tBox
funct ion.

Example 2 Th e fo llow ing prog ram requ ires the use


The Do loop repe ats the request unti r to ente r a num ber from 1 t hrough 3.
l the use r gives a prop e r respo nse.

OBJECT PROPERTY
a:} 6-1 -2 GJ1 8 I~ frm Mov ie
SETTING
Text 6-1-2
btnD isp lay Text Disp lay a Mov ie Q uota tion
Display a Movie Quot ation
txtQ uota ti on Read Only True

Priv ate Sub btn Dis play_ Clic


k( ... ) Han dles btn Dis play .Cli
Dim resp ons e As Inte ger , quo ck
tati on As Stri ng = ""
resp ons e= Cin t (Inp utB ox( "En
ter a num ber from 1 to 3." ))
Do Whi le (res pon se < 1) Or
(res pon se > 3)
resp ons e= Cin t (Inp utB ox( "En
ter a num ber from 1 to 3." ))
Loo p
Sel ect Cas e resp ons e
Cas e 1
quo tati on "Pl asti cs."
Cas e 2
quo tati on "Ro sebu d."
220 • Cha pter 6 Repetiti o n

Cas e 3
ks. "
quo tati on= "Th at's all fol
End Sel ect
on
txtQ uot a ti on. Tex t = quo tati
End Sub

[Run, and click on the butt on.]

C ~' 6-1-2 ~~ @)
-
~

J
l Disp lay a Movi e Quotation

l~~J
6-l- 2

Enter a number from 1 to 3. I OK I


[ Canc el l

OK button .]
[Type 3 into the box and clic k on the

cj 6-1 -2

Display a Movie Quotation

That 's all folks .

inpu t from a fi le or from the use r.


Do loops ofte n are used to process data

red
age of a sequ enc e of num bers ente
Example 3 The follow ing prog ram find s the aver - 1 to indicate the end
The user sho uld type in the num ber
by the user from inpu t dialog boxes. ente red , there is the pos-
ialog box appears before the loop is
of data entry. S ince the first inpu t d
ped.
sibility that the enti re loop will be skip
e.C lick
ck( ... ) Han dles btn Com put
Pri vat e Sub btnC omp ute_ Cli
Dim num As Dou ble = 0
Dim cou nt As Inte ger = 0
Dim sum As Dou ble = 0 " &
ter a non neg ativ e num ber.
Dim prom pt As Str ing = "En te ent erin g num ber s."
"En ter -1 to term ina
))
num = CDb l (Inp utB ox( pro mpt
Do Wh ile num <> -1
cou nt += 1
sum += num
))
num = CDb l (Inp utB ox( pro mpt
6.1 Do Loops
• 22 1

Loop
If cou nt > 0 Then
Mes sage Box .Sho w( "Av erag e: "
& sum I coun t)
Else
Mes sage Box . Show ( "No num bers
were ente red. " )
End If
End Sub

[Run , click on the butt on, and respond to


the requests for inpu t with 80, 90, and -1
ing i d isplayed in the me sage box. ] . The follow-

Ave rage : 85

ln Exa mple 3, the varia ble count is calle


d a coun ter variable, the vari able sum is
accu mul ator variable, the num ber - 1 called an
i called a sent inel valu e, and the loop
hav ing sent inel -con troll ed repe titio n. is referred to as

Posttest Form of a Do Loop


In Example 1 and 2, the cond ition was
chec ked at the top of the loop- that is,
state men ts we re exec uted . A ltern ative ly, befo re the
the cond ition can be chec ked at the bott
loop whe n the Loo p state men t is reac hed. o m of the
Wh en Visual Ba ic enco unte rs a Do loop
of the fo rm
Do
st atem ent (s)
Loop Unt il con diti on

it exec utes the state men ts insid e the


loop and then chec ks the truth va lue
condition is true, then the prog ram cont inue of condition . If
s with the line after the Loo p state men t.
is fa lse, then the enti re process is repeated If condition
begi nning with the Do state men t. In othe
the sta teme nts in ide the loop are exec r words,
uted once and then are repea ted ly exec
cond it ion is true . Figure 6.2 shows the pseu uted until the
d ocod e and flowchart for this type of Do
loop.

Execute
state ment s
within
the loop

Do
stat eme nt ( s)
Loop Unt il con diti on is true No
condition

Execute
state ments
that follow
the loop
FIGURE 6.2 Pseu doco de and flowchar t for a Do loop
with the cond ition tested at the botto m.
222 • Cha pter 6 Rep et iti on

to Exa mp le 2, exce pt that the con


di-
Example 4 The fo llow ing program is equi va lent
:
tion is tested at the bott om of the loop
ck
k( ... ) Han dles btn Dis play .Cli
Priv ate Sub btnD ispl ay_ Clic ""
tati on As Stri ng =
Dim resp ons e As Inte ger , quo
Do
ter a num ber from 1 to 3." ))
resp ons e = Cin t (Inp utB ox( "En
And (res pon se <= 3)
Loo p Unt il (res pon se >= 1)
Sel ect Cas e resp ons e
Cas e 1
quo tati on "Pl asti cs."
Cas e 2
quo tati on "Ro sebu d."
Cas e 3
s."
quo tati on= "Th at's all folk
End Sel ect
on
txtQ uot atio n.T ext = quo tati
End Sub

le formula.
tities for whic h we migh t not know a simp
Do loop s allow us to calc ulate useful quan

ings acco unt and let it accu mul ate


Example 5 Suppose yo u dep osit mon ey into a sav you will be a
rest com pou nd ed ann u ally. The fo llow ing program dete rmin es whe n
at 6% inte
milliona ire:

PROPERTY SETTING
OBJECT

a':} 6% Inter est ~[@] [}[] frmMi llion aire Text 6% lnter est
lblA mou nt Text Amo un t depo sited :
Amount deposited : txtA mou nt
btnC alcu late Tex t Calc u late Years to
Beco me a Mi ll iona ire
Calculate Years to Become a Millionaire
txt Whe n Rea dOn ly Tru e

Cli ck
k( ... ) Han dles btn Cal cul ate.
Priv ate Sub btn Cal cula te_ Clic
be orne a mill~onair
'Com pute yea rs re~ ~red to
num Yea rs As Inte ger
Dim bala nce As Dou ble ,
t.Te xt)
bal anc e= CDb l (txt Am oun
Do Whi le bala nce < 1000 000
bala nce += 0.06 * bala nce
num Yea rs += 1
Loo p
txtW hen .Tex t "In " & num Yea rs &
lion dol lars ."
" yea rs you wil l hav e a mil
End Sub
6.1 Do Loops
• 223

[Run, type 1000 00 into the text box, and


click on the butt on.]

a ... 6% Interes

Amount deposited : I}

Calc:ulate Years to Become a Millionaire

In years you will ha'll'e a million dollars .

Comments
1. Be care ful to avo id infin ite loops-t
hat is, loops that are neve r ex ited . The
is infin ite, because the fo llow ing loop
cond ition "balance < 1000" wi ll always
can be avo ided by initi alizing intRate with be true. This logic erro r
a valu e grea ter than 0.
Priv ate Sub btnB utto n_ Clic k(
... ) Han dles btnB utto n.C lick
An 1nf1 n1te loop
Dim b a l ance As Dou ble = 100,
intR ate As Dou ble
Do Whi le bala nce < 1 000
bal a nce = (1 + intR ate) * bala
nce
Loop
t x tBa l ance .Tex t = Fo rma tCu rren cy( bala nce)
End Sub

Impo rtan t: Wh ile an infin ite loop is exec


utin g, the program can be term inat ed by
on the Stop Debugging butt on on the Too click ing
lbar.
2. Vi ual Basic prov ides a way to brea
k out of a Do loop befo re the loop cond ition
the state men t Exi t Do is met. Whe n
is enco unte red in the body of a loop, exec
to the state men t following the Loop state utio n jum ps immed iate ly
men t.
3. A va riab le declared insid e a Do loop
has block- leve l scope; that is, the va riab
referred to by code outs ide of the loop. le cann ot be
4. Visual Basic allows th e use of the word
s "While" and "Un til" at eith er the top
a Do loop. For insta nce, the fourth line or bott om of
in the program in Exam p le 1 ca n be rep
laced with
Do Unt i l num > 7

and the fifth li ne of the program in Exam


p le 4 can be replaced with
Loop Whi le (res pon se < 1) Or
(res pon se > 3)

Practice Problem 6.1

1. How do you deci de whe ther a co


ndit ion shou ld be chec ked at the top of
bott om ? a loop or at the

2. C hang e the fo llowing code segment


so that the loop wi ll exec ute at least once
:
Do Wh i le con tinu e = "Yes "
answ er = Inpu tBox ( "Do you wan
t to con tinu e? (Y or N) " )
224 • Chapter 6 Repetition

n
If ans wer .To Upp er = "Y" The
con tinu e = "Ye s"
Els e
con tinu e "No "
End I f
Loo p

EXERCISES 6.1
but ton is clic ked on.
ne the out put disp laye d whe n the
In Exe rcises 1 thro ugh 6, dete rmi
lick
. .. ) Han dles btn Dis pla y.C
1. Pri vat e Sub btn Dis pla y_ Cl i ck(
Dim num As Inte ger = 3
Do Wh ile num < 15
num + = 5
Loo p
txtO utp ut.T ext CSt r(nu m)
End Sub
lick
.. . ) Han dles btn Dis pla y.C
2. Pri vat e Sub btn Dis pla y_ Cli ck(
Dim num As Inte ger = 3

Do
num = 2 * num
Loo p Un til num > 15
txtO utp ut.T ext CSt r(nu m)
End Sub
lick
. . . ) Han dles btn Dis pla y.C
3. Pri vat e Sub btn Dis pla y_ Cli ck(
Dim tot al As Dou ble = 0
Dim num As Inte ger = 1

Do Wh ile num < 5


tot al += num
num += 1
Loo p
txtO utp ut.T ext CS tr(t ota l)
End Sub
y.C lick
ck( ... ) Han dles btn Dis pla
4. Pri vat e Sub btn Dis pla y_ Cli
Dim tot al As Dou ble = 0
Di m num As Inte ger = 1
Do
tot al += num
num += 1
Loo p Un til num >= 5
l)
txtO utp ut.T ext = CS tr(t ota
End Sub
lick
... ) Han dles btn Com put e.C
5. Pri vat e Sub btnC omp ute_ Cli ck(
Dim num As Dou ble 0
Dim max As Dou ble = - 1
" &
ter a non neg ativ e num ber.
Dim pro mpt As Str ing = "En erin g num ber s."
"En ter - 1 to term ina te ent
6.1 Do Loops
• 225
num = CDb l(In putB ox(p rom pt))
Do Whi le num > = 0
If num > max The n
max = num
End If
num CDb l(In putB ox(p rom pt))
Loo p
If max < > -1 The n
Mes sage Box .Sho w("M axim um
num ber: " & max )
Els e
Mes sage Box .Sho w("N o num bers
wer e ente red . ")
End If
End Sub

(A s ume that the responses are 4, 7, 3, and


- 1.)
6. Priv ate Sub btn Dis play_ Clic
k( . . . ) Han dles btn Dis play
.Cli ck
Dim num Trie s As Inte ger
Dim yr As Inte ger
Dim msg As Stri ng "In wha t yea r did the Bea
tles inva de the U. S.?"
Do
num Trie s += 1
y r = Cin t (Inp utB ox(m sg, "Try #" & num Trie s))
Sel ect Cas e yr
Cas e 1964
Mes sage Box .Sho w(" The y app
eare d on the Ed Sul liva n
show in " &
" Feb ruar y 196 4." & "Yo u
answ ered the que stio n " &
"co rrec tly in " & num Trie
s & " trie s." , "Co rrec t")
Cas e Is < 1964
Mes sage Box .Sho w(" Late r than
" & yr & ".")
Cas e Is > 1964
Mes sage Box .Sho w(" Ear lier
than " & yr & ".")
End Sel ect
Loo p Unt il (yr = 1964 ) Or
(num Trie s = 7)
If yr <> 1964 The n
Mes sage Box .Sho w(" You r 7 trie
s are up, the answ er is 196
End If 4.", "So rry" )
End Sub

(Ass ume that the responses are 1950,


1970, and 1964 .)
In Exe rcises 7 thro ugh 10, iden tify
the erro rs.
7. Priv ate Sub btn Dis play_ Clic k(
... ) Han dles btn Dis play .Cli
Dim q As Dou ble ck
= 1
Do Whi le q > 0
q=3*q-1
lstO utp ut.I tem s.A dd( q)
Loo p
End Sub

8. Priv ate Sub btn Dis play_ Clic


k( .. . ) Han dles btn Dis play
. Clic k
'Dis play the num bers from
1 to 5
Dim num As Inte ger
226 • Cha pter 6 Rep et ition

Do Wh ile num <> 6


num = 1
lstO utp ut.I tem s.A dd( num )
num += 1
Loo p
End Sub
pla y.C lick
Cli ck( ... ) Han dles btn Dis
9. Pri vat e Sub btn Dis pla y_
se is giv en
'Re pea t unt il a yes res pon
"N"
Dim ans wer As Str ing =
Loo p N)? ")
dow n the che rry tre e (Y/
ans wer Inp utB ox ("D id you cho p
= "Y" )
Do Un til (an swe r.To Upp er
End Sub
y.C lick
ck( ... ) Han dle s btn Dis pla
10. Pri vat e Sub btn Dis pla y_ Cli
'Re pea t as lon g as des ired
As Str ing
Dim n As Int ege r, ans wer
Do
+= 1
n
lstO utp ut.I tem s.A dd( n) ")
wan t to con tinu e (Y/ N)?
ans we r= Inp utB ox( "Do you
"N"
Un til ans wer .To Upp er =
End Sub
h an equ iva len t
11 thro ugh 20, rep lace eac h phr ase con tam mg "Un til" wit
In Exe rcis es ase (Un til sum = 100 )
vice vers a. For inst anc e, the phr
phr ase con tain ing "W hile ", and
<> 100 ).
wou ld be rep lace d by (Wh ile sum
11. Un til num < 7

12. Un til nam e =


11
Bob 11
nyu
13. Wh ile res pon se =
14. Wh ile tot al = 10
15. Wh ile nam e <>
16. Un til bal anc e >= 100
17. Wh ile (a > 1) And (a < 3)
18. Un til (an s 1111) Or (n = 0)

19. Un til Not (n = 0)


20. Wh ile (an s "Y" ) And (n < 7)
sam e task as the
21 and 22, wri te sim pler and clea rer cod e tha t per form s the
In Exe rcis es
give n cod e.
y.C lick
ck( ... ) Han dle s btn Dis pla
21. Pri vat e Sub btn Dis pla y_ Cli
Dim nam e As Str ing
a nam e: ")
nam e = Inp u tBo x ("E nte r
lstO utp ut.I tem s.A dd( nam e)
a nam e:")
nam e = Inp utB ox ("E nte r
lstO utp ut.I tem s.A dd( nam e)
a nam e: ")
nam e = Inp u tBo x ("E nte r
6.1 Do Loops
• 227

lstO utpu t.Ite ms. Add (nam e)


End Sub

22 . Priv ate Sub btn Dis play_ Clic


k( ... ) Han dles btn Dis play .Cli
Dim loop Num As Inte ger , answ ck
er As Stri ng = ""
Do
If loop Num >= 1 The n
answ er Inpu tBo x("D o you wan t to con
tinu e (Y/N )?")
answ er answ er.T oUp per
Els e
answ er "Y"
End If
If (ans wer = "Y") Or (loo pNu
m = 0) The n
loop Num += 1
txtO utp ut.T ext = CSt r(lo opN
um)
End If
Loo p Unt il (ans wer <> "Y")
End Sub

23. Wri te a prog ram that di plays a Cel


sius-to- Fah renh eit con vers ion tab le in
in the tab le should range from 10 to a list box . Entr ies
95 degrees Cel ius in incr eme nts of 5
The formu la f = (9/5 *c ) + 32 con vert degrees. Not e:
s Cels ius to Fah renh eit.
24. The coefficient of restitution of a ball
, a num ber betw een 0 and 1, spec ifies
is con se rved whe n a ball hits a rigid how mu ch ene rgy
surface. A coefficie nt of .9, for inst ance
bou nc ing ball will rise to 90% of its , mea ns a
prev io us he igh t aft er eac h bo unce. Wri
to inpu t a coeffic ient of rest itut ion and te a prog ram
an initi al he ight in met ers, and repo
t imes a ba ll bou nces whe n drop ped rt how man y
from its ini ti al he ight befo re it rises
les than 10 ce n t ime ters. A lso repo to a heig h t of
rt the tota l dist ance t rave led by the
po int. The coef ficie nts of res titu tion ba ll befo re th is
of a tenn is ball , ba ketb a ll , supe r ball
a re .7, .75, .9, and .3, resp cti ve ly. , and softball
25. Wri te a prog ram th at req ues ts a
word co nta inin g the two lette rs ran
dete rmi nes whi ch of the e app ears d n as inpu t and
first. If the word does not co ntai n both
prog ram sho uld so adv ise the use r. lette r , the
(Tes t the prog ra m with the word s
"me rrim en t.") "co lon el" and
26. Wri te a prog ram that find s the
sma lles t num ber in a sequ ence of non
entered by the user fro m inpu t d ialog neg ative num bers
boxes. Th user should be to ld to type
- 1 to ind icate that the entire sequence in the num ber
has bee n ente red.
27. Wri te a prog ram that find s the rang
e of a seq uenc e of non nega tive num bers
use r from inpu t dialog boxes. (Th e rang ente red by the
e is the difference betw een the larges t and
est num bers in the seq uen ce.) The use the sma ll-
r hould be told to type in the num ber
that the enti re seq uen ce has bee n en tere - 1 to indi cate
d.
In Exe rcis es 28 and 29, writ e a prog
ram corr espo ndin g to the flow cha rt.
28. The flow cha rt in Fig. 6.3 on the
nex t page req uest s a who le num be r
inpu t and factors it into a prod uct of grea te r than 1 as
prim e num bers. Not e: A num ber is prim
factors a re 1 and itse lf. e if its only
Video Note
29. The flowcha rt in Fig. 6.4 on the
nex t page find s the grea tes t com mon
intege r that d ivides both ) of two pos divi sor (the largest Si eve of
it ive integers inpu t by the use r. W rite Eratosthen es
co rre pon d to the flowcha rt. a program that (Homework)
228 • Cha pter 6 Rep e ti tion

Start

Set
F= 2

Set
T= N

Set
N = M mod N

Increase Set
F by 1 M= T

Set
N = N/F

End
End
FIGURE 6.4 G reat est com mon divi sor.
FIGURE 6.3 Prim e fact ors.
ses the butt on , val-
trat e the grow th of mon ey in a savi ngs acco unt . Wh en the user pres
30. Illus to calculat e the
are obta ined from text boxes and used
ues fo r A mou nt and Inte rest Rat e w.
bles . U se the form design sho wn belo
num ber of years unti l the mon ey dou nce, whe re r is
yea r is ( 1 + r ) times the prev ious bala
Not e: The bala nce at the end of each
l form .
the ann u al rate of inte rest in dec ima
PROPERTY SETTING
OBJECT

D Com p ou nd Inte rest GJI 8 lrnJ frml nterest Tex t Com pou nd
Inte rest
Tex t Am o un t:
Amount : lblA mou nt
txtA mou nt
Interest rate : A utoS ize Fa lse
[Allnual) lblR ate
Tex t Inte rest rate:
Determine Years [A nnu al]
txt Rate
Doubling time : Tex t Dete rmin e Year s
btnD eter min e
[Years) A uto ize Fa l e
lblD oubl
Tex t Dou blin g time :
[Yea rs]
Rea dO n ly True
txtD oub le
6.1 Do Loops
• 229
In Exe rcis es 31 throug h 38, wri
te a progra m to answer the que
stio n.
31. A person bor n in 198 0 can
claim, "I will be x yea rs old in
the yea r x squared." Wh at is the
va lue of x?
32. Th e world pop ula tion reac
hed 6.83 bill ion peo ple in Jan uar
rate of 1.1 2% eac h yea r. Ass um y 201 0 and was grow ing at the
ing tha t the popu lati on wi ll con
rate, wh en will the pop ula tion tinu e to gro w at the sa me
rea ch 10 bill io n ?
33. Str ont ium -90 , a rad ioac tive
e lem ent tha t is par t of the fall o
a half-life of 28 years. Thi s mea ut from nuc lea r exp los ion s, has
ns tha t a give n qua ntit y of tron
tive par ticl es and decay to one- tium -90 wi ll em it rad ioac-
half its size eve ry 28 yea rs. H ow
100 gra ms of st ron tium -90 to dec man y yea rs are req uired fo r
ay to less tha n 1 gra m ?
34. The consum er price index (CP
I) ind ica tes the ave rage price
serv ices. It is cus tomaril y tak en of a fix ed ba ket of goods and
as a measur e of infl at ion and is
pen sion s. Th e C PI was 9.9 in July freq uen tly used to adju st
1913 , was 100 in Ju ly 1983, and
Thi s mea ns tha t $9. 90 in Ju ly 191 was 215.35 in July 2009.
3 had the sa me pur cha sing pow
and the sam e pur cha sing pow er er as $ 100 .00 in Jul y 1983,
as $2 15.35 in July 2009. In 200
tim e sinc e 1955. H owe ver, for 9, the C PI fell for the first
mos t of the pre ced ing 15 yea rs
rate of 2.5 % per yea r. A sum ing it had gro wn at an ave rage
tha t the C PI will rise at 2.5 % per
yea r will the July CP I have at yea r in the future, in wha t
leas t dou bled from its Jul y 2009
CP I will be 1.025 times the CP leve l? Not e: Eac h yea r, the
l for the previous yea r.
35. Wh en you bor row mo ney
to buy a ho use or a ca r, the loan
equ al mo nth ly pay men ts inc orp is paid off wit h a seq uen ce of
o rati ng a stat ed ann ua l inte res t
The am oun t borrowed is call ed rate co mp o und ed mo nth ly.
the princifJal. If the ann u al inte
the mo nth ly inte rest rate is .06 rest rate is 6% (o r .06) , the n
/12 = .005. At any tim e, the
am oun t still owed. Th e bal anc e balance of the loan is the
at the end of eac h mo nth is calc
end of the prev ious mo nth , plus u late d as the bala n ce at the
the inte rest due o n tha t bala nce
pay men t. For inst anc e, wit h an , and min us the mo nth ly
ann u al inte rest rate of 6%,
[new bal anc e J = [prev ious bal
anc e J + .005 · [prev io us
= 1.005 · [pre vio us bala nce J - [ mo nth bal anc e J - [ mo nth ly pay me nt J
ly pay men t].
Sup pos e you borrow $ 15 ,000 to
buy a new ca r at 6% inte rest com
your mo nth l y pay me nt is $29 0.0 po und ed mo nth ly and
0. Aft er how ma ny mo nths wil
Th at is, afte r how man y mo nth l the ca r be half paid off?
s wi ll the bala nce be less tha n ha
36. An annuity is a seq uen ce of lf the principal?
equa l periodic payments. On e
plan, con sists of mo nth ly paymen type of annuity, called a savings
ts into a sav ings accoun t in ord
futu re purchase. Suppose you dec er to ge nerate mo ney for a
ide to depos it $ 100 at the end of
accou nt paying 3% inte rest com eac h mo nth into a sav ings
pou nded mo nth ly. The mo nth ly
.0025, and the bala nce in the acc inte rest rate wi ll be .03/ 12 or
ou nt at the end of eac h mo nth
will be com put ed as
[ba lan ce at end of mo nth J = (
1.0 025 ) · [ba lan ce at end of pre
vio us mo nth ] + 100.
Aft er how man y mo nth s will
the re be mo re tha n $30 00 in
mo ney will be in the acc oun t at the acc o unt , and h ow mu ch
tha t tim e ?
37. An annuity is a seq uen ce of
equal periodic payments. For one
mo ney is deposited into a ban k type of ann uity, a large amo unt of
accoun t and the n a fixed amo unt
Sup pose you deposit $ 10,000 into is wit hdr awn eac h mo nth .
suc h an accoun t pay ing 3.6 % inte
and the n withdraw $60 0 at the rest com pou nde d mo nth ly,
end of eac h mon th. The mo nth
or .003, and the balance in the acc ly inte rest rate will be .036/12
oun t at the end of eac h mo nth will
be com put ed as
[ba lanc e at end of mo nth J = (
1.0 03) · [ ba lan ce at end of prev
ious mo nth J - 600 .
Aft er how man y mo nth s will
the acc oun t con tain less tha n
am oun t in the acc oun t at tha t $60 0, and wh at will be the
time?
38. Red o Exerci e 37 wit h the
am oun t of mo ney depos ited bein
g inp ut by the use r.
230 • Ch apt er 6 Rep etit ion

6.1
Solutions to Practice Problems
e.
sho uld be executed at least onc
b, the con d ition is che cked at th e bottom if the loop
1. As a ru le of thum the first li ne to Do and replace
with the stat eme n t con tin ue = " Yes " , or cha nge
2. Either precede the loop "Ye s" .
p Un til con tin ue <>
theL oop stat eme ntw ith Loo

6.2 For . . . Next loops


cut ed, a spec ial type of loo p,
how ma ny tim e a loo p sho uld be exe
Wh en we kno w exa ctly d and wr ite and they
p, can be use d. For .. . Ne x t loo ps are easy to rea
called a For ... Ne x t loo cod e uses a For . . .
ma ke the m ide al fo r cer tain co mm on tas ks. Th e fo llowing
have features tha t
Ne xt loop to disp lay a table:
Di spl ay Ta ble .Cl ick
btn Dis pla yT abl e_ Cli c k( ... ) Ha ndl es btn
Pri va te Sub and the ir squ are s
the fir st 5 num ber s
'Di spl ay a abl e of New
lst Ta ble is Co uri er
Ass um e the fon t for
To 5
For i As Int eg er = 1
Ite ms . Ad d(i & " " & i A 2)
lst Ta b le.
Ne xt
End Sub
in the list box .]
n. Th e foll owing is disp laye d
[Run, and clic k on the bu tto

1 1
2 4
3 9
4 16
5 25

th a Do loop is as foll ows.


A sim ilar progra m wri tten wi
e.C lic k
ndl es btn Di spl ayT abl
va te Sub btn Dis pla yT abl e_ Cli ck( ... ) Ha are s
Pri and the 1.r squ
the fir st c; nur nbe s
' 'sp lay a tab le of
Dim i As Int eg er
i = 1
Do Wh ile i <= 5 2)
& " " & i
lst Ta ble . Ite ms .Ad d(i
A

'Ad d 1 to 1.
i += 1
Loo p
End Sub

xt Loop
General Form of a For . .. Ne
gra m of the form
In gen era l, a po rtio n of a pro
Vidc oNo te

~ To n ,.__ _ _ _ _ term
For ... Next loop>

I !+
For i As nlmi / ),u<~1 '/'c = m
inating value
counter variable ~
initial value
body
stat eme nt( s)
Nex t

cause the sta tement


.. . Ne xt loo p. T he pair of sta tement For and N ex t
con stit utes a For sta tement declares a num eric
eat ed a spe cifi ed num be r of tim es . The For
betwe en the m to be rep omati cally cha nges afte r
led the cou nte r var iab le, tha t is initiali zed and the n aut
va riab le, cal
For .. . Next Loops
6.2
• 23 1

each pass through the loop. Also, the For statement


gives the range of values this variable will
assum e. The N ext statem ent increm ents the count er
variable. If m ::; n , then i is ass igned the
va lu es m, m + 1, . . . , n in o rde r, and the body is execu
ted o nce fo r each of the e va lues. If
m > n , then th e body is skipp ed and execution con tinues
with the statem ent after the For . . .
Next loop.
When program execu tion reach es a Fo r ... N ext loop,
such as the o ne sh own prev iously,
the Fo r statem ent ass igns to the count er variable
i the initial value m and ch ecks to see
wheth er i is grea ter than the termi natin g value n. If
so, then execu t io n jumps to the line fo l-
lowin g th e Next statemen t. If i < = n , the sta temen ts
inside the loop are exec uted. Then, the
Nex t statem ent increa es the va lue of i by 1 an I check
s t his new va lue to see if it excee ds n. If
no t, the ent ire process is repea ted until the va lu e of
i excee ds n. When t h is h appen s, the pro-
gram moves to th e line fo llowi ng t he loop. Figure 6.5
conta ins the pse udoco de and fl owch art
of a For . . . N ex t loop.

Set
counter variable
to initial value
For i As numD ataTy pe m to n
state ment (s)
Next

Is
counter variable Yes
> terminating
value?

No

Execute
statements
within loop

Increment
counter
variable

Execute
statements
following
the loop

FIGURE 6.5 Pseud ocode and flowc hart of a For . . . Next loop.

The cou nter variable can be any nume ric variable. The
most comm on single- letter names are
i, j , and I<; however, if appro pri ate, the name should sugges
t the purpo e of the count er variable.
The count er vari ab le, and any variable decla red inside
a For .. . N ext loop, has block -level
scope; that is, the va ri able canno t be referr ed to by code
outsid e of the loop.
232 • Cha pter 6 Rep etiti on

of the For . . . Nex t


ared with a Dim stat eme nt outs ide
A cou nter variable also ca n be decl program show n at
ram produces the same outp ut as the
loop. For inst ance, the follow ing prog
the beg inni ng of this section .
y.C lick
ck( ... ) Han dles btn Dis pla
Pri vat e Sub btn Dis pla y_ Cli ir squ are s
fir st 5 num bers and the
'Di spla y a tab le of the
abl e is Cou rier New
'Ass ume the fon t for lstT
Dim i As Inte ger
For i = 1 To 5
" & i A 2)
lstT abl e.It em s.A dd( i & "
Nex t
End Sub
e it vio lates the
have block- level scope , and therefor
In this case, the variab le i does not s book, we neve r
e that the scop e of a va riab le hould be as sma ll as poss ible. In thi
prin cipl
For ... Nex t loop.
declare a co unte r vari ab le outs ide a

ing
300 ,000 in the year 2010 and is grow
Example 1 Suppose the population of a city is the popu latio n eac h
rate of 3% per yea r. The follo win g prog ram disp lay a tab le show ing
at the
year unt il 2014.
PROPERTY SETTING
OBJECT
~~ 8 ~~ frmP op ulati on Tex t Popu latio n Gro wth
ll -' Pop ulat ion Growth
btnD isplay Tex t Disp lay Populati on
Display Population j lstTab le Fon t Couri er New

L_J y.C lick


ck( ... ) Han dles btn Dis pla
Pri vat e Sub btn Dis pla y_ Cli
201 0 to 201 4
'Di spla y pop ula tion from
Dim pop As Dou ble = 300 000
To 201 4
For yr As Inte ger = 201 0
yr & " " & For mat Num ber( pop , 0))
lstT abl e.It em s.A dd(
pop += 0.03 * pop
Nex t
End Sub

[Run, and click on the button.]

ll ~ Pop ula tion Grm·vt h

Display Population

2 010 3 00,0 00
2 011 3 0 9 ,000
2 01 2 3 18, 2 70
2 01 3 32 , 818
2 0 14 33 7,6 53
6.2 For ... Nex t Loops
• 233

The initi al and term inat ing va lues


can be li tera ls, vari ables, or exp ress
the For stat eme nt in the prec ed ing prog ion . Fo r inst ance ,
ram ca n be replaced by

Dim firs tYr As Inte ger = 2010


Dim las tYr As Inte ger = 2014
For yr As Inte ger = firs tYr
To last Yr

In Ex a mpl e 1, the cou nte r vari ab


le was incr ease d by 1 afte r each
loop . A vari atio n of the Fo r sta tem pass thro ug h th e
ent a llo w any num ber to b used as
stat e men t the inc re men t. The

For i As num Data Type =m To n Step s

instru cts the Nex t sta tem ent to add s


to the cou nter vari ab le inste ad of
s do not have to be who le num b rs. The 1. The num ber 111, n, and
num bers is called th e step valu e of the
the cou nter vari ab le wi ll assu me va lu loop. Not e 1: If
es that are no t who le num ber , then
type Dou b le. Not e 2: The cou nter vari the vari able mus t be of
ab le is a lso called the index.

Example 2 The fo llow ing prog ram display the va


lu es of the index of a For ... Nex t loop
befo re term in at ing and the step va lue
in put by the u cr:

OBJECT
~I B
D~ For index = 0 Ton 5tep s PROPERTY
I@J frm lndex Text
SETTING

For inde x = 0
n: s: To n tcp s
IbiN Text n:
Display Values of Index
txt End
~

Is! Values
- IbiS Text s:
txtS tep
btnD isp lay Text Disp lay Va lu e
of lndex
lstVa lues

Priv ate Sub btn Dis play_ Clic


k( ... ) Han dles btn Dis play .Cli
'Dis play valu es of inde x rang ck
ing from 0 to n Step s
Dim n, s As Dou ble
n = CDb l (tx tEnd .Tex t)
s = CDb l (txt Ste p.T ext)
lstV alu es.I tem s.C lear ()
For inde x As Dou ble = 0 To
n Step s
lstV alue s.It ems .Ad d(in dex )
Nex t
End Sub
Cha pter 6 Rep etit ion
234 •
.]
t boxes, and clic k on the but ton
[Ru n, type 3.2 and .5 into the tex

ll For index = 0 Ton Step sl = I @) I~ . J


n: 3.2 s: .5

Display Values of Index J


l
0
0.5
1
1.5
2
2.5
3

ively increased unt il it


les con side red so far, the cou nte r variab le was success
In the exa mp the init ial value is
ina ting val ue. H owe ve r, if a neg ative step va lue is used and
reac h ed the term reased unt il reac hin g the ter-
e, the n the cou nte r va lue is dec
gre ater tha n the term ina ting valu
the loop cou nts backward.
min atin g va lue. In oth er words,

kwa rds:
a word as inp ut and d isplays it bac
Example 3 The foll owing progra m accepts

PROPERTY SETTING
OBJECT
Wri te Bac kwa rds
~~ ~ Write Backwards ~~ ~ 1@ 3 frmBackwards Tex t
Ent er wo rd :
lblW ord Tex t
Enter word : txt Wo rd
Tex t Rev erse Lett ers
btnR eve rse
Reverse Letters Rea dOn ly Tru e
txtB ackw ards

Re ver se. Cli ck


Cli ck( ... ) Han dle s btn
Pr i vat e Sub btn Rev ers e_
e r se( txtW ord .Te xt)
tx t Ba ckw ard s.T ext = Rev
End Sub

ing
inf o As Str ing ) As Str
Fun ctio n Rev erse (By Val
As Str ing =
1111

Dim m As Int ege r , tem p


m = i nfo .Le ngt h
1 To 0 Ste p -1
For j As Int ege r = m -
trin g ( j , 1)
tem p& = inf o.S ubs
Nex t
Ret urn tem p
End Fun ctio n
6.2 For . .. Nex t Loops
• 235
[Ru n , type "SUEZ" in to the tex
t box , and clic k on the but ton
.]

a:; W ite Bac a rds l =I@) ~~ :J


Enter word : SUEZ

Reverse Letters

ZEUS

No te: Th e initial and termina


ting values of a For . . . N ex t loo
the third and fo urth lines of the p can be exp ress ion s. For inst anc
fun ctio n in Exa mp le 3 e,
can be con soli dat ed to
For j As Int ege r = inf o.L en gth - 1 To 0 Ste p -1

Nested For .. . Next Loops


Th e body of a For ... Ne xt loo
p can con ta in any sequ ence of
ula r, it can con ta in ano the r For Visual Bas ic sta tement s. In pa
.. . Ne xt loo p. H owever, the rtic-
con ta ined in ide the fi rst loo p eco nd loo p mu st be co mp lete
and mu st have a differe nt cou ly
is call ed nested For ... Ne xt nte r variab le. Suc h a configurati
loo ps. on

Example 4 Th e fo llow ing progra m d ispl ays


to 3. Here j de not es the left fac a mult ipli cation tab le for the inte
to rs of the pro duc ts, and I< den ge rs from 1
takes on a va lue fro m 1 to 3. T ote the righ t fac tor . Eac h fac
he va lues are ass ign ed to j in the to r
in the inn er loop (lin es 6-9 ). out er loo p (lin es 4- 11) and to
Init iall y, j is ass ign ed the value I<
ve rsed thr ee tim es to pro du ce 1, and the n the inn er loo p is tra-
the first row of pro duc ts. At the
va lue of j will till be 1, and the end of these th ree passes, the
first exe cution of the inn er loo
th is, the sta tem n t N ex t inc rem p will be comp lete. Fo llow ing
ents the value of j to 2. T he sta
exe cuted. It resets the va lue of tem ent beg inn i ng "Fo r k" i the n
k to 1. Th e seco nd ro w of pro
thr ee exe cution s of the inner du cts is d isplaye d d ur ing the nex
loop, and so on . t

Mu ltipl ic ati c:m Tabl e OBJECT


11
~~ 8 ![} [] PROPERTY SETTING
frm Tab le Tex t Mu lti pli cati on Tab le
Disp lay Table btn Display Tex t Disp lay Tab le
]
1stTab le Fo nt Co urie r New
l 1 s~Tahl e

J
Pri vat e Sub btn Dis pla
y _ Cli c k( ... ) Ha ndl es
Dim r ow, en try As Str btn Dis pla y.C lic k
ing
lst Ta ble . Item s . Cle ar ()
For j As Int ege r = 1
To 3
row
For k As Int ege r 1 To 3
236 • Chapter 6 Repetition

k & " " & (j * k)


ent ry = j & " x " &
row & = en try & "

Ne xt
)
l stT abl e . I t em s.A dd( row
Ne xt
End Sub
.]
[Run, and click on the but ton

D_. 1u ltip lica tion Tab le


l = I @) 1.-tJ ·J

[ Display Tab le I
1 X 2 = 2 1 X 3 = 3 1
1 X 1 =1
2 X 1
3 X 1
=2
=3
2 X 2
3 X 2
=
=
4
6
2 X 3
3 X 3
=
= :I
Left factor
t t Ri ght factor

Local Type Inference ze


s you to dec la re and ini ti ali
typ e inf ere nce (al so refe rred to as imJ)licit typing) a llow e infe ren ce is
Lo cal e. Loc a l typ
le wit hou t exp lici tly sta t ing its type wit h an As cla u 3. 1 of Sec -
a loc al variab VB Defau lts d ialog box shown in
Fig ure
Infer is se t to O n in the
e nab led if Op tio n
ault.)
t ion 3.2. (It is ena bled by def ows:
local type inferen ce are as foll
Some exa mples of the use of

e Eq uiv ale nt
Lo cal Typ e In f e r enc
S t and ard De cla rat ion
To 3 For i = 1 To 3
For i As Int eg er = 1 For i = 1 To 3 Ste p
0.5
1 To 3 Ste p 0.5
For i As Do ubl e =
Dim cou nt = 5
r 5
Dim cou nt As Int ege =
Dim rat e = 0.0 5
0 . 05
Dim rat e as Do ubl e = Dim nam e = "Fr ed"
Str ing = " Fre d"
Dim nam e As Dim d = #6 / 4 / 201 0#
#6 / 4 / 201 0#
Dim d as Da te =

d by the values foll ow ing


ren ce, the typ e of a local var iab le is det erm ine
Wi th loc al typ e infe l poi nt) and in the
lues are all wh o le num bers (wr itte n wit hou t a dec ima
the equ al sign . If the va r. If an y of the val-
rs, the n the var iab le is declared to be of type Int ege
range of va lues for Int ege Int ege rs, the n
ing a dec ima l po int or are out sid e the ran ge of values for
ues are num ber con tain , the n it i
be of typ e Do ubl e. If the va lue is surrou nded in quo te
the var iable is declared to va riable is declared to be of
to be of typ e Str ing . If the value is a date literal, the n the
declared iables.
does not app ly to class- level var
type Date. No te: Th is fea tur e um es tha t Op tio n Infer is On ) dem
ons trat es how
lkth rou gh (wh ich ass
The foll owing wa
a For ... Ne xt loo p.
loc type infe ren ce works in
al
) and a list box
gra m con sist ing of a for m hav ing a but ton (bt nC onfirm
1. Cre ate a new pro
(lstBox).
2. En ter the follow ing code.
Co n f i rm . Cli ck
Cl ick ( ... ) Ha ndl es btn
Pri va te Sub btn Co nfi rm_
2
For i = 1 To 5 Ste p
6.2 For . .. Nex t Loops • 237

lstBox .Items. Add(i)


Next
End Sub
3. In the Code Editor, hover the mouse pointer over the variable i. (The tooltip
jDim i As Integer !
appears to confirm that the variable i has indeed been declared as type Integer.
)
4. In the head r of the For . .. N ex t loop, change the 5 to 5.0 and aga in hover
the po inter ove r
the letter i. (This time the tooltip reads IDim i As Double J.)

Local type inferenc e was added to Visual Bas ic beca use it is needed fo r
LINQ (Language
INtegra ted Query) , an innovat ive language feature that unifies the manipu
lation of diverse col-
lections of data. LINQ is introdu ced in C hapter 7 of this book and is used
extensiv ely from then
on . By necessit y, we rely on local type inferenc e when using LINQ. Althou
gh we do not use
local type inferenc e in the declara tio n of ordinar y variables, you may feel
free to do so if you
prefer and your instruct or pe rmits.
Local type inferenc e is also known as duck typing. This name comes from
the well-kn own
quote, "If it walks like a du ck, and quacks li ke a duck, then it is a duck."

Comments
1. Fo r and N ext stateme nts must be paired. If one is miss ing, the syntax checker
will compla in
with a wavy underli ne and a message such as "A 'For' mu st be pa ired with
a 'Nex t' ."
2. Consid er a loop beginni ng with For i = m To n S tep s. The loop wi ll
be execute d exac tly
once if m equ a ls n no matter what va lu e s has. The loop will not be execute
d at a ll if m i
greate r than n and s is pos iti ve, or if m is less than n and s is negative.
3. The va lue of the counter variab le should not be altered within the body
of the loop; doing so
might ca use the loop to repeat indefinitely or have an unpredi ctable number
of repetitio ns.
4. N oninteger S tep va lues in Fo r ... N ex t loops ca n result in unexpe
cted outcom es. For
instance, if you run Exampl e 2 with n = 2 and s = .1, the las t num be r displaye
d will not be
2 as intend ed. In ge neral, the use of counter variables of type Do uble is poor
program ming
practice and should be avo id ed. From now on, all counter variables appea
ring in this book
will have type Integer.
5. Visual Ba ic provides a way to abort an iteration in a For ... Next loop.
When the tatemen t
Continu e For is encoun tered in the body of the loop, executio n immedi
ately jumps to the N ext
stateme nt. A n a11alogo us stateme nt continu e Do is ava ilable for Do loops. Typicall
y, Continu e
For and Continu e Do stateme nts appear inside conditio nal structur es such as
If blocks.
6. Vi ual Bas ic provides a way to back o ut of a For . . . N ex t loop. When
the stateme nt Exit
For is encoun tered in the body of the loop, executi on jumps immedi
ate ly to the tatemen t
followin g the N ex t stateme nt.
7. Counte r va riab les and variables declared inside For . .. N ex t loops have
block-level scope;
that is, they cannot be referred to by code outside the loops.
8. A ny type of loop can be nested inside another loop. For example, Fo r ...
N ex t loops can be
nested insid e Do loops and vice ve rsa. Also, Do loops can be nested inside
other Do loops.

1. Why wo n't the fo llow ing lin es of code work as intend ed ?


For i As Intege r = 15 To 1
lstBox .Items. Addite m(i)
Next

2. When is a For . .. N ex t loop more app ropriate than a Do loop ?


238 • Chapte r 6 Repetit ion

EXERCISES 6.2

list box when the button is


In Exerci ses 1 throug h 10, determ ine the output displayed in the
clicked .

1. Priv ate Sub btnDis play_ Click( ... ) Handle s btnDis p l ay . Click
For i As Intege r = 1 To 4
lstBox . Items . Add (" Pass #" & i)
Next
End Sub

Click
2. Privat e Sub btnDis play_ Click( ... ) Handle s btnDi splay.
For i As Intege r = 3 To 6
lstBox .I tems.A dd(2 * i )
Next
End Sub

Click
3. Privat e Sub btnDis play_ Click( ... ) Handle s btnDi splay.
For j As Intege r = 2 To 8 Step 2
lstBox . Items. Add(j)
Next
lstBox .I tems.A dd("Wh o do we apprec iate?" )
End Sub

splay. Click
4. Privat e Sub btnDi splay _ Click( ... ) Handle s btnDi
For countd own As Intege r = 10 To 1 Step -1
lstBox . Items.A dd(cou ntdown )
Next
lstBox .I tems.A dd("bl astoff ")
End Sub

Click
5. Privat e Sub btnDis play_ Click( ... ) Handle s btnDi splay.
Dim num As Intege r = 5
For i As Intege r = num To (2 * num - 3)
lstBox .I tems . Add (i)
Next
End Sub

splay. Click
6. Privat e Sub btnDis play_ Click( .. . ) Handle s btnDi
For i As Intege r = -9 To -1 Step 3
lstBox .Item s.Add( i)
Next
End Sub

Cli c k
7. Privat e Sub btnDis play_ Click( ... ) Handle s btnDi splay.
'Chr (l49) is a large dot
Dim string OfDots As String
For i As Intege r = 1 To 1 0
stringO fDots &= Chr(14 9)
Next
txtBox .Text stringO fDots
End Sub
6.2 For ... Nex t Loops
• 239

8. Priv ate Sub btn Dis play_ Clic


k( ... ) Han dles btn Dis play
.Cli ck
Dim n As Inte ger = 3
Dim tota l As Inte ger = 0
For i As Inte ger = 1 To n
tota l += i
Nex t
txtB ox.T ext CSt r(to tal)
End Sub

9. Priv ate Sub btn Dis play_ Clic


k( . .. ) Han dles btn Dis play
.Cli ck
'No te: Chr (65) is A and Chr
(90) is Z
Dim sen tenc e, lett er As Stri
ng
Dim num Cap s As Inte ger =
0
sen tenc e = "Th e Uni ted Sta
tes of Am eric a"
For i As Inte ger = 0 To sen
tenc e.L eng th - 1
lett er = sen ten ce.S ubs trin
g(i, 1)
If (As c(le tter ) >= 65) And
(As c(le tter ) <= 90) The n
num Cap s += 1
End If
Nex t
txtB ox.T ext CSt r (num Cap s)
End Sub

10. Priv ate Sub btn Dis play_ Clic


k( ... ) Han dles btn Dis play
.Cli ck
Dim wor d As Stri ng = "cou
rage "
Dim lett er As Stri ng = ""
Dim num Vow els As Inte ger
=0
For i As Inte ger = 0 To wor
d.Le ngth - 1
lett er = wor d.S ubs trin g(i,
1)
If IsV owe l(le tter ) The n
num Vow els += 1
End If
Nex t
txtB ox.T ext CSt r(nu mVo wels )
End Sub

Fun ctio n IsVo wel( ByV al lett


er As Stri ng) As Boo lean
lett er = lett er .ToUppe r
If (let ter "A") Or (let ter "E") Or (let ter "I") Or
(let ter = "0") Or (let ter
"U") The n
Ret urn Tru e
Els e
Ret urn Fal se
End If
End Fun ctio n

In Exe rcis es 11 thro ugh 14, iden tify


the erro rs.
11. Priv ate Sub btn Dis play_ Clic
k( ... ) Han dles btn Dis play
.Cli ck
For j As Inte ger = 1 To 25
Step -1
lstB ox.I tem s.A dd( j)
Nex t
End Sub
Cha pter 6 Rep etit ion
240 •
lay .Cl ick
ck( .. . ) Han dle s b t nD isp
12. Pri vat e Sub btn Dis pla y_ Cli
For i As Int ege r = 1 To
3
s.A dd( i & " " & 2 A i)
lstB ox. Item
End Sub
y.C lick
ck( ... ) Han dles btn Dis pla
13. Pri vat e Sub btn Dis pla y_ Cli exc ept for 13
0 thro ugh 20
'Di spl ay all num bers from
For i As Int ege r = 20 To
0

If i = 13 The n
i = 12
End If
lstB ox. Item s.A dd( i)
Nex t
End Sub
pla y . Cli ck
Cli ck( ... ) Han dle s btn Dis
14. Pri vat e Sub btn Dis pla y_
4 Ste p 0.5
For j As Int ege r = 1 To
l s tBo x.It em s.A dd( j)
Nex t
End Su b
loop.
the pro gra m usin g a For . .. Nex t
In Exe rcis s 15 and 16, rew rite
y.C lick
ck( ... ) Han dle s btn Dis pla
15. Pri va t e Sub btn Dis pla y_ Cli
Dim num As Int ege r = 1
Do Whil e num <= 9
lstB ox. Item s.A dd( num )
num += 2 'Ad d 2 to val ue of num
Loo p
End Sub
pla y.C lick
Cli ck( ... ) Han dle s btn Dis
16. Pri va te Sub btn Dis pla y_
")
ls t Box . Item s .Ad d ("h ello
Ad d(" hel lo" )
ls t Box .Ite ms.
hel lo" )
ls t Box .Ite ms. Ad d("
llo" )
lstB ox. Item s.A dd( "he
End Sub
t loop to car ry out the
a pro gra m con tain ing a For ... Nex
In Exe rcis es 17 thro ugh 3 7, wri te
stat ed ta k.
17. Display the eve n num bers
fro m 1 thro ugh 100 in a list box.
hun dred pos iti ve integers.
18. Find the sum of the first one
ut di alog boxes.
Fin d the ave rage of five num be rs obt ained from the use r with inp
19.
di alog boxes.
Fin d the largest of fi ve num bers obt ained from the user wit h inp ut
20.
1/3 + 1/4 + · · · + 1/100.
21. Find the va lue of 1 + 1/2 + lay a stri ng of n la rge
e intege r (cal l it n) and the n disp
22. Ask the use r to inp ut a pos itiv te histog ram s, as
Not e: C hr( l49 ) is a larg e dot. Str ings of dot s can be used to crea
doc .
in Fig. 6. 11 on page 242. reci ate by 15 %
DeJ mciatio n . A rule of thu mb stat es tha t cars in per a nal use dep
23. Automobile e showing the va lue of
chased for $20,000. Produce a tabl
eac h yea r. Suppose a new car is pur
t fiv e years.
the car at the end of eac h of the nex
6.2 For ... Nex t Loops
• 241

24. A ccep t a word as inpu t and deter mine if


its lette rs are in alpha betic a l orde r. (Test the
gram with the wo rds "a lmos t", "imp ly", and "biop pro-
sy".)
25. Estim ate h ow mu ch a youn g work er
will make befo re retiring at age 65 . Requ e
wo rker's name , age, and start ing salary as input t the
. A ssum e the wo rker rece ives a 5% ra ise
each yea r. For exa mple , if the use r ente rs H elen
, 25, and 2000 0, then the text box sho uld
di play th e fo llowi ng:
Hele n will earn abou t $2,4 15,9 95.

26. Whe n $ 1000 is inves ted at 5% simple


interest , the amou nt grow s by $50 each yea r.
mon ey is in veste d at 5% interest comp ound ed Whe n
annu ally, th e amou nt at th e end of each yea r
is 1.05 t imes the amou nt at the begin ning of
that year. D isplay the amo unts for 9 years for
1000 inves tmen t at 5% simple and co mpou nd a
interes t. See Fig. 6.6.

a_. I ntere st
ll _. I d ea l Weig h s l = I·@) ,,....~ J
Display Growt h of Money
( Display Ideal VI/eights
]
~.MOUNT ~.MOUNT -1 r--- -
Y:::A:;<
S IY-~ ~
INE :;<:::S T
COY-~ OT.JN:>
fE IG'HT
'iE IG'HT
WOY..:::N
-rr: rGHT
M.:. N
I
INE :;<:::ST
1 02 109. 0 120 . 0
-? 1,05 0.00 ;?1,0 5 0.00
2 63 11 £ . 5 124. 0
:;;>1, 100.0 0 -? 1,10 2 . 5 0
64 116 0 12a. o
-?1,1 5 0 . 00 :;;;1,1 5 7.6 3
0

63 119. 5 132. 0
:;;;1,2 00 . 00 -?1, 21 5 5 1
66
0

123 . 0
11 -? 1,2 5 0.00
:; > 1,30 0 . 00
-?1,2 76.2 3
67 12.0 . .5
1 36.0
140. 0

~
-? 1,34 0.10
68 130. 0

~:: : J
-? 1,3 5 0 . 00 -? 1,40 7 . 10
69 133. 5
-?1, 400 . 00 ;? 1,47 7.4 6
70 137. 0 1 5 2.0
;?1,4 50.00 -? 1, 55 1.33
71 140. 5 156 .0

FIGURE 6.6 Outp ut of Exerc ise 26. FIGURE 6. 7 Possib le ou tput for Exerc ise 2 7.

27. A ccor ding to resea rchers at S tanfo rd Med


ica l Scho o l, the idea l we ight fo r a wo man
fo und by mu ltip lying her he ight in inches by is
3. 5 and subtr actin g 108. The id ea l we ight fo
a man is fo und by mult iply ing his h eight in r
in ches by 4 and subtr actin g 128. Requ est a
lowe r and uppe r bo und fo r he ights and then
prod uce a table givin g the idea l we ights for
wo men and men in that heigh t range . Fo r exam
p le , when a lowe r boun d of 62 and an uppe r
boun d of 71 are specified, Fig. 6. 7 shows t he
outp ut displayed in the list box.
28. Requ es t a se nten ce, and then deter mine
the numb er of sibila nts (that is, letters S o r Z)
the sente nce . Carr y o ut th e co untin g with a in
Func tion procedure.
29. Refe r to the annu ity discussed in Exe rcise
36 of Secti o n 6.1. Assume th at the first depo
made at th e end of Janu ary 2010 , and display s it is
the ba lance in the acco unt at the end of each
year fro m 20 10 to 201 9. See Fig. 6. 8 o n t he nex
t page.
30. Consider the ca r loan d iscussed in Exerc i e
35 of Secti on 6.1. The loan will be paid off after
yea rs. A ssum e that the car wa purch ased at the five
begin ning of Janu ary 2010 , and display the bal-
ance at the end of each year for five years. See
Fig. 6.9. Note: The last paym ent will be slight ly
less than the othe r payments, since othe rwise the
final balan ce would be a nega tive amount.
31. Radioactive Decay. Coba lt 60, a radio activ
e fo rm of co balt used in ca nce r thera py, decay
o ver a pe riod of time. Each year, 12% of the s
amo unt prese nt at the beg innin g of the yea
will have deca yed . If a cont a iner of coba lt r
60 initia lly cont a ins 10 gram s, dete rmin e the
amo unt rema ining after five years .
242 • Chap ter 6 Repe titi on

_I = 1 @] 1~ ,.j
ll Ar n ity [= /§JL -~ ll .,. Car Loa n [

( Displa}' Balances ] ( Displcrl Balances 1


----- 2010 $ 12, 347 .. 8 .5
$1, ~Hi . 64
r 2 0l 0 2011 .$- 3, 5 32. . 13
.2011 $~,470.~8
2012 : $ C, .5 42'_7 4
.2:012 $3,7 02:.D C .;; 3,368 ~ 97
2:013
2013 $ 5 ,093 .12 ~0 . 00
2:014
2:014 .;;6,464 ~ 67

2015 n, 877 .. 94
2016 $9,3 34 . 19
2:01 7 $10, 834_ 74
2 0 18 $12 , 380 . 93
2:019 $13, 974 . 14

FIGURE 6.9 Outp ut of Exer cise 30.


FIGURE 6.8 O utpu t of Exer cise 29.
oard , sinc e the
com pute rs is know n as the Qwe rty keyb
32. The keyboard in use on nearly all if all its
YU IOP. A wo rd is ca lled a Qwe rty word
lette rs in the top lette r line read QW ERT typewriter ,
of the keyb oard . Som e exam p les are
lette rs appe ar on the top lette r line not it is a Qwe rty
t and dete rmin e whe ther or
repertoire, and treetop . A ccep t a wo rd as inpu t.
ed lsQw erty that acce pts a word as inpu
wo rd. Use a Boo lean -valu ed func tion nam
r mos t agric ul -
l of prod ucti on and pr ice (per bush el) fo
33. Supply and Demand. Each year's leve se the
on and price for the follo wing yea r. S uppo
tura l proJ ucts affec ts the leve l of producti
bush e ls in 2010 and
soyb a crop in a coun try was 80 milli on

[price each yea r] 20 - .1 * [qu anti ty that year]


10 ,
[qua ntity each year] 5 * ([pri ce from the precedin g year]) -
sh ow the
milli ons of bush els. G ener ate a table to
whe re quan tity is measure d in units of
. See Fig. 6. 10.
q uant ity and price from no w unt il 2020

I = I @] ~~ J a~ ista-g ra ~
1 = l @] I. -~- -'
D.,. S p ly & De and
Beginning year: 2' (}7
Displcrt Soybean Projections
Ending year: 2· 1])

-f.::: A~ QUJ!...N III Y P·::l.IC3


:2:J10 ao . oo .;> 12 . 00 Gather and Displcrl Data
2J11 50.0 0 $ 15 . 00
6 5 . 00 $ 13 . 50
:< 1:2: Sa1e 3 i n Mil l i ons
2013 .5 7 .. .5 0 $ 14_2 : Et 2007 • • ••• • • • • • • •• ll _f
2014 61.2 5 $1 3 . 88 2008 • ••• • •••• 8 _9
~01 5 5 9 . 38 $1 4 . 06 ~00~ • ••• • • ••• • 10 . 3
6'0 - 31 $1 3 . 97
2:016 2010 · ···· ·~ · · · · 11 _1
:<017 5 9.84 $ 1 4 .02
~018 60 _08 $ 13 _99
£ 019 59 . 9 6 $ 14 _00
$ 14 . 00 Average sales : ~1 D.lJ million
2 0:2:0 60.0 2:

FIGURE 6.11 Poss ible ou tput of Exer cise 34.


FIGURE 6.10 Outp ut of Exer cise 33.
the aver age
seve ral years in a hi togr am and calc u late
34. Display a com pany's sales figures for u nt of sales for each
clicks on the button , the amo
yearly sales. See Fig. 6.11. Whe n the user i a large dot.
inpu t dialog boxe s. Note : Chr ( 149)
year should be obta ined from the user with
6.3 List Boxes and Loops
• 243

35. You are offered two salary option s for ten days of wo rk. Option
1: $ 100 per day. O ption 2:
$ 1 the first day, $2 the second day, $4 the third day, and so on,
with the amoun t doubli ng
each day. Determ ine which optio n pays better.
Exerci ses 36 and 37 sh ould use the follow ing Functi on proced
ure.
Functi on Day0fW eek(By Va1 d As Date) As String
Dim str As String = Forma tDateT ime(d, DateFo rmat.L
ongDa te)
Dim n As Integ er= str.Ind exOf( ",")
Return str.Su bstrin g(O, n)
End Functi on
36. Reques t a yea r as input and th en display the date of the
first Tu esday of that yea r.
37. Reques t a yea r as input and then d isp lay th e dates of the first
Tu e days of each mo nth of
that year.

Solutions to Practice Problem 6.2

1. The loop wi ll never be en te red beca use 15 is greate r th an 1. The


inte nded first line mi gh t have bee n
For i As Intege r 15 To 1 Step -1
or
For i As Intege r 1 To 15
2. If the exact num ber of tim es th e loop will be exec uted is kn ow
n befo re entering the loop, th en a For . . . Next
loop shoul d be used . Otherw ise , a Do loop is more appropr iate .

6.3 list Boxes and Loops


In prev io us ectio ns we used list boxes to d isplay o utput and to
fac ili tate e lec tion . In this sec-
t io n we explore some additi onal features of list boxes and use loop
to ana lyze data in list boxes .

Some Properties, Methods, and Events of List Boxes


During run time , the va lu e of
V ideo N o te
1stBo x.Item s.Coun t
List boxes
is the numbe r of items curren tly in the li t box. Each item in lstBox and loops
is identifi ed by an index
numbe r rangin g from 0 through lstBox.ltems.C ount - 1. For instanc
e, if the list box co nta ins
10 items, then th e first item h as index 0, the second item ha index
1, ... , and the las t item has
index 9. In genera l, the nth item in a list box has index n - 1.
During run tim e, the u er can highli ght an item in a list box by cl icking
on the item with the
mo use or by mov ing to it with the up- and down-a rrow keys when
the list box has the focus. The
Selecte dind exCh anged eve nt occurs each time an item of a li t box
is clicked on or each time an
arrow key is used to change the highlig hted item. l t is the default
event for li t box contro ls.
The va lue of
1stBo x.Se1e ctedin dex

is the index numbe r of the item curren tly highlig hted in lstBox.
If no ite m is h igh li ghted, the
va lu e of Se lected Ind ex is - 1. The statem ent
1stBo x.Se1e ctedin dex = -1

will unhigh light an y highlig hted item in th e list. Note: This


sta teme nt a lso ra ises the
Se lected l nd exCh anged event.
244 • Chap ter 6 Repet ition

The val ue of
lstB ox.I t e ms(n )
of the list are of a data type called Obje ct. A
is the item of l tBox hav ing index n. The elements
type ca ting must take place when ever an
va lue of any type may be added to the list. However,
variab le or is conc atena ted with anoth er
elem ent of the list is ass igned to a nume ric or string
va riab le or Iitera l. For instan ce, the statement
txtBo x.Te x t = CStr (lstB ox.It ems( O))

display the first item of lstBox in a tex t box.


The value of
lstBo x.Te x t
to a tring.
is the curre tl y highl ighted item of lstBox conve rted
list box property. Whe n it i set to True
The Sorted property is perhaps the most interesting
atica lly be displayed in alpha betic al (i.e.,
(at eithe r design time or run time) , items will autom
rty is False.
ANS I) order. The defau lt va lue of the Sorted prope
most impo rtant eve nt for list boxes are
After the Selec tedindexC hanged event , the two
a m conta ins procedures for both of these
the C lick and Doub leCli ck even ts. However, if a progr
only the C lick even t wi ll be raised .
events and the user double-clicks on the list box,
numb er . Whe n the items are all strings,
The items in a list box are usually all strings or all
at ion. Whe n the items are all numb er , we
we use loops to searc h for items and to extra ct inform
use loops to perform calculat ions.

List Boxes Populated with Strings

lstStates and lstLastTen.


Example 1 The follow ing program uses two li t boxes, named
lstSta tes conta in the names of the 50 U.S.
We assum e that the Strin g Collection Edi tor of
am displays the last 10 states to jo in the
states in t e order they joined the union. The progr
is the numb er of items in lstSta tes, then the
union begin ning with the most rece nt. Note : If n
last item i lstSta tes has index n - 1.
Hand les btnD ispla y.Cl ick
Priv ate Sub btnD ispla y_ Click ( ... )
unt
Dim n As Integ er = lstSt ates. Item s.Co
= (n - 1 ) To (n - 10) Step -1
For i As Integ er
ms.A dd(1 stSta tes.I tems (i))
1stLa stTe n.Ite
Next
End Sub

[Run , and click on the butto n.]

a. U.S. States

States :
Dela•.-.•are ...
Penm:;1vania
New Jersey - Hawaii
Georg ia Alaska
Connecticut Arizona
Massachusetts New Mexico
M ar1~ and Oklahoma
South Carolina Utah
New Hampshire \'U'yorning
Virginia Idaho
New York Washington
North Carolina Montana
6.3 List Boxes and Loops
• 245

Whe n a list is searc hed, we often use a Boolean


variab le called a flag to tell us whet her or
not the so ught- after item has been found. The
value of the fla g is set to False initia lly and then
i changed to True if and when the sough t-afte
r item is found .

Example 2 The follow ing program use a list box na med


lstSt ates whose Strin g Col-
lection Edito r cont a ins the names of the 50
U.S. state s in the order they jo ined the unio
The prog ram also uses a masked text box with n.
Mask "LL". Afte r the use r enter s two lette rs
into the masked text box, the prog ram uses a
Do loop to searc h the list box for a state begin
ning with those letters. The Do loop term inate -
s when the state is foun d or wh en the last item
in the list box has been exam ined. If a state
is foun d , the prog ram repo rts its fu ll na me and
the ord er in whic h it joined the unio n. If the
re is no state beg innin g with the pair of lette
the prog ram so reports. rs,

Priv ate Sub btnS earc h_ Cli c k( .. . )


Hand les btnS earc h.Cl ick
Dim lett e rs As Strin g = mtbF i r stTw
oLe tters .Tex t.To Upp er
Dim foun dF l ag As Bool ean = Fals e
'ind icat es whet her stat e has been
Dim i As Inte ger = -1 foun d
'inde x of the stat e curr entl y cons
Do Unti l (fou ndFl ag) Or ( i = lstS ider ed
tate s. Item s.Co unt - 1 )
i += 1
If CStr (l st S tat e s . Item s (i)) . ToUp
per . Star tsW ith(l ette rs) Then
fo und Flag = True
End If
Loop
If f oun d F l a g Then
tx t Outp ut. Tex t CStr (l stSt ates .Item s(i)) & " is
Else stat e#" & (i + 1) & • . •
tx t Outp ut.T e xt "No stat e begi ns with " & mtbF irstT
End If wo.T ext & • •
End Sub

[Run , en te r two lette rs into the masked text box,


and click on the butto n.]

D .J U.S. Sta es l = I@) 1..:-ti-:;r


States :

Delaware Rrst two letters


PennS}~van i a of stat e :
Ne•i•' Jersey
Georg ia
Conne cticut
Massachusetts
M a r,~ a n d
Search For State
South Carolin a
New Hampshire
Virginia
New York
North Carolin a

Kansas is state tt~ .


246 • Cha pter 6 R petit ion

list Box es Populated with Numbers

grad es. The use r inse rts a grad e into


Example~ The follow ing prog ram eva lu ates exa m Record bu tton .
rade text box and then click ing on the
the list box by typ ing it into the txtG dete rmin e the
the use r clicks on th e Calculate butt on to
Afte r all th e grades have been ente red, ted as [ um of
the exa m. The ave rage grad e is ca lcula
ave rage grad e and the high est grade for ng a loop t h ro ugh the
b le sum adds up the grades duri
grades] / [n umb er of grad es]. The varia The vari able
the num be r of items in th e list box.
grad es. T he num ber of grad es is just Note : To pre-
sted duri ng each pass thro ugh the loop .
maxGrade st rt out set to 0. It is then adju that the list
alculate_ Clic k even t proc edur e chec ks
vent the prog ram fro m cras h ing, the btnC
box con ta in some items.

PROPERTY SETTING
OBJECT

D_. Ana lyze Grad es EEJI @) IE![] frm Grad es Text A nalyze G rades
lblG rade Text G rade:
lstGrades
Grade : txtG rade
btnR ccord Text Reco rd G rade
Reco·d Grade btnC alcul ate Text Calc ulate Average
and High est G rade
Calcu late Average lblAverage Text Ave rage grade:
and Hirhest Grade Read On ly Tru e
txtA verage
lblHighest Tex t High est grade:
Average grade :
txtH ighest Read Only True
Highest grade : lstG rades

... ) Han dles btnR eco rd.C lick


Priv ate Sub btnR ecor d_ Clic k(
ext)
lstG rad es.I tem s.Ad d(tx tGra de.T
txtG rad e . Cle ar()
txtG rad e.Fo cus( )
End Sub
.Cli ck
k( . . . ) Han dles btnC alcu late
Priv ate Sub btnC alcu late _ Clic
Dim sum As Dou ble = 0
Dim max Grad e As Dou ble = 0 list box is none mpty
Then 'con diti on is true when
If lstGrade s.Ite ms.C oun t > 0
rade s.Ite ms. Cou nt - 1
For i As Inte ger = 0 To lstG
i))
s um += CDb l (lst Gra des .Ite ms(
i)) > max Grad e Then
I f CDb l (lst Gra des .Ite ms(
des .Ite ms( i))
max Grad e = CDb l (lst Gra
End If
Next
s.Ite ms. Cou nt, 2)
txt vera ge.T ext Form atNu mbe r(sum I lstG rade
txt ighe st.T ext CSt r (max Grad e)
Else
t ente r some grad es." )
Mes sage Box .Sho w( "You mus t firs
End I f
End Sub
6.3 List Boxe and Loop
• 247
[Run, ent er some grades , and
the n clic k on the Calculate but
ton.]

ll w A na lyze Gra des l = I @) 1•- tJ d


Grade : B.S
.5'4

l
[ Record Grade
I 76
~
SJ
Calculate Average
and Highest Grade
J ~
91
!16
Average grade: S7.13
Highest grade : S.6

No te: In Exa mple 3, the ave


rage gra de and the highes t
wit hou t the gra des bei ng sto gra de cou ld have bee n cal
red in a list box. Som e calcul cu lated
deviati on, do req uir e the gra at ion s, howeve r, suc h as the
des to be sto red . sta nd ard

Searching an Ordered list


Wh en the item s in a list of
stri ngs are in alp habetic al ord
instan ce , if you are sea rch ing er, the search ca n be sho rte
an o rde red list of wo rds fo r one ned . Fo r
ca n ce rta inl y sto p the sea rch tha t beg ins wit h th e lett er D,
wh en yo u rea ch wo rds beg inn yo u
Wh ene ver th e pa ir of lett ers ing wit h E. Co nsid e r Ex am
ent ere d into the maske d tex ple 2.
sta te, the ent ire list was sea rch t box we re not the fir t two
ed. S uch search es can be sho lett ers of a
first o rd ere d. rten ed con sid era bly if the rate
s are

Example 4 Th e fo llow ing progra m ha


exc ept tha t the o rted pro per the sa me con tro l nd ett
ty of the li t box is se t to Tru ings as xam ple 2,
the items on e at a tim e unt e. Th e progra m beg ins by loo
il it loc ates a sta te wh ose nam kin g at
alp hab etica lly. If tha t tate e exc eed s the so ugh t-af ter
doesn 't beg in wit h the sought lett ers
sta te in the list doe . -afte r lett ers , we ca n ass um e
tha t no
Pri va te Sub b t nS ear ch_
Cli ck( ... ) Ha ndl es btn
Dim let ter s As Str ing Se arc h.C lic k
= mt bF irs tTw oL ett ers .Te xt. To Up
Dim i As Int eg er = 0 per
'in dex of the sta te
Do Un til (CS tr ( lst Sta cu rre ntl y con sid ere d
te s. Ite ms (i) ) . ToU ppe
r > let ter s) Or
( i = l stS tat es. Ite ms .Co
un t - 1)
i += 1
Loo p
If CS tr (ls tSt ate s.I tem
s(i )) . To Up per .St art sW
txt Ou tpu t.T ext ith (le tte rs) The n
CS tr (ls tSt ate s.I tem s(i
)) & "b eg ins wi th"
mt bF irs tTw oL ett ers . Te &
Els e xt & "·"
txt Ou tpu t . Te xt "No sta te beg ins wi th"
End If & mt bF irs tTw oL ett ers
.Te xt & "·"
End Sub
Ch apt er 6 Repetition
248 •
Comments
reas ing o rd er e ven wh en the
num ber s mig ht no t be num eric ally in inc
1. A list box con ta ini ng det erm ine s o rde r, th e
is se t to Tru e. Fo r ins tan ce , sin ce the AN SI tab le
So rte d pro per ty
num ber 9.
num ber 8 will pre ced e the l ord er. A mo re
way sea rch a list of stri ngs tha t are in alph abe tica
2. Exa mp le 4 prese nts on e
to
ing Proj ect 8.
hni q ue, ca lled a bin ary search, is disc ussed in Progra mm
effic ien t tec

Practice Problems 6.3


er a e lec ted lnd exC han ged
t dis plays a me ssage box te lli ng you wh eth
1. Wr ite a pro gra m tha clic kin g on an item .
sed by th e pre ss ing of an arr ow key or wa s ca use d by
eve n t was cau fo llo win g
ldn 't the ma xim um gra de be ca lculat ed wi th th e
y cou
2. Co nsid r Exa mp le 3. Wh
cod e?
Tru e
lst Gr a de s.S ort ed = es. Ite ms .C ou nt- 1))
bl( lst Gr ade s .It em s(l stG rad
max Gra de = CD

EXERCISE~ 6.3
of
. De ter mi ne the con ten ts
1 thr oug h 6, ass um e tha t lstB ox is as sho wn below
In Ex erc ises
is exe cut ed.
the tex t box aft er the cod e
Bac h
Bee th ove n
Ch o_Ein
JlU.fkle
T ch aikovsky

1. txt Ou tpu t.T ex t lst Bo x.T ex t


))
CS tr( lst Bo x.I tem s(2
2. txt Ou tpu t.T ex t 1))
stB ox .It em s.C ou nt-
CS tr( lst Bo x.I tem s(l
3. txt Ou tpu t.T ex t ))
stB ox .Se lec ted ind ex
4. txt Ou tpu t.T ex t CS tr( lst Bo x.I tem s(l
din de x)
CS tr( lst Bo x .S ele cte
5. txt Ou tpu t.T ex t
er = 0
6. Dim tot al As Int eg ou nt - 1
0 To lst Bo x.I tem s.C
Fo r n As Int eg er = The n
(n) ) . Le ng th= 6
If CS tr( lst Bo x . Ite ms
tot al += 1
End If
Nex t
tr( tot al)
tx t Ou tpu t.T ext = CS
mi ne the con ten ts of
h 12, ass um e tha t lstB ox is as sho wn below. De ter
In Ex erc ise s 7 thr oug
is exe cut ed.
the tex t box aft er the cod e

90
60
6.3 Li t Boxes and Loops
• 249

7. txtO utpu t.Te xt CStr (lstB ox.I tems (O))


8. txtO utpu t . Text lstB ox.T ext
9. txtO utpu t.Te xt CStr (lstB ox.I tems (lstB ox.S elec tedin
dex) )
10. txtO utpu t. Text CStr (lstB ox . Sele cted inde x)
11. Dim num As Inte ger = 0
For n As Inte ger = 0 To lstB ox.I tems
.Cou nt - 1
num += Cint (1stB ox.I tems (n))
Next
txtO utpu t.Te xt = CStr (num )

12. Dim min As Doub le = 100


For n As Inte ger = 0 To 1stB ox . Item
s.Co unt - 1
If CDb 1(1s tBox .Item s(n)) <mi n Then
min = CDb 1(1st Box . Item s(n))
End If
Next
txtO utpu t.Te xt = CStr (min )

In Exer cises 13 throu gh 18, fill the Strin g


Coll ectio n Edito r of lstBo x at design time with
the winn ers of the nearl y 100 Rose Bow l
games that have been played. 1 The first three
item s in the list box will be Mich igan, Was hing
ton State , and Oreg on. Som e colleges appe ar
man y time s in th e list. Writ e a prog ram that
perfo rms the indic ated task.
13. Cou nt the num ber of times USC has won
the Rose Bowl.
14. Afte r the use r cl icks on th name of a
college in lstBo x, coun t the num ber of times the
lege has won the Rose Bowl. col-
15. Dete rmin e if a college inpu t by the use r in
a text box ha won the Rose Bowl. Assume that
the Sorted prop erty of lstBox i set to False. The
procedure should term inate the searc h if
and wh en the college is found.
16. Dete rmin e if a college inpu t by the user
in a text box has won the Ro e Bowl. Assume
the Sorted prop erty of lstBox is se t to True. The that
procedu re should term inate the searc h as
soon as possible.
17. FilllstBox 2 with th e entri es of lstBo x, but
in reve rse ord er.
18. Fill lstBo x2 with the colleges (in alpha betic
al orde r) that have won the Rose Bowl, with
each winn er appea ring ju t once .
S~ppose lstBo x has been filled with the 50 U.S.
state s in the orde r they joine d the unio n. 2
In Exer cises 19 throu gh 34, write a program
to perfo rm the indic ated task.
19. Displ ay in lstBox2 th e states in alpha bet
ical orde r.
20. Disp lay in l tBox2 the states in rever e alpha
betic al orde r.
21. Disp lay in lstBox2 the states whose name
(incl udin g spaces ) are seven lette rs long.
22. Dete rmin e the first state in lstBox whose
name is seven letters long. The program shou
term inate the searc h as soon as the state is found ld
.

1
Th e fil e Rose bowl. tx t (foun d in the fo lder
Prog rams \ C h06 \ Tex t_Files_for_Ex ercises) conta
names of the Rose Bowl winn ers in the o rder ins the
th e ga mes were played. Copy the co nte nts of
and Pa te th em in to the Strin g Collection Ed the tex t fi le
itor of lstBo x.
2
The file S tates. txt (fo und in the folde r Programs
\ C h06 \ Text_ Files_ for_ Exerc ises ) conta ins the
of the states in the o rder they joined th e uni on. name
250 • Chap ter 6 Repe titio n

ram sho uld


se name begins with "New ". The prog
23. Dete rm ine the first state in l tBox who
is found.
term inat e the search as soon as the state
es begin with "New ".
24. Display in lstBox2 the state s whose nam
state s havi ng
state name, and display in lstBox2 the
25. Dete rm ine the length of the long est
that leng th.
state s h av ing
sta te name, and display in lstBo x2 the
26. Dete rmin e the leng th of the sho rtest
that leng th .
The prog ram
nam es have four lette rs that are vowels.
27. Display in lstBox2 the state s whose lette rs in a
berO Now e ls that coun ts the num ber of
sho uld call a Fun ctio n proc edur e Num
strin g that are vowe ls.
e that are
e the num ber of lette rs in the state's nam
28. Afte r the user clicks on a sta te, dete rmin
vowels.
the 50 states.
lette r that are vowels for the nam es of
29. Dete rmin e the max imu m num ber of num ber
edur e Num berO Now els that coun ts the
The prog ram should call a Fun ctio n proc
of lette rs in a strin g that are vowels.
nam es cons ist of two words.
30. Dete rmin e the num ber of states whose
join the unio n.
31. Display the nam e of the first state to
join the unio n.
32. D isplay the nam e of th e las t state to
join the unio n.
33. Display the name of the fifth state to
orig ina l thirt een states.
34. Display in lstBox2 th e nam es of the the lowe st
late_ Clic k eve nt proc edur e calc u lates
35. Alte r Example 3 so that the btnC alcu
grade instead of the high e t grade.
bers abou t the
36. The tand ard devi ation measure
s the spread or dispersal of a et of num
e m, then
coll ectio n of n num bers with ave rage valu
mea n. Formally, if x 1, x 2 , x 3 , . . . , X 11 is a
2
2 + (x 2 - m) 2 + (x3 - m) 2 + · · · + (x 11 - m)
. ~ (x 1 - m)
stan dard devt atto n = n
s th e stan -
late_ Clic k eve nt proc edur e also calc ulate
Exte nd Examp le 3 so that the btnC alcu
dard devi atio n of the grades.
the lowe st num -
37. The rang e of a set of num bers is
the diffe rence betw een the high est and
range of
alcu late_ Clic k proc edur e calc ulates the
bers. Modify Exam ple 3 so that the btnC
the grades inste ad of the high est grad e.
s the num ber of
38. Alte r Exam ple 3 so that the btnC
alcu late_ Clic k even t proc edur e calc ulate
imum grad e.
abov e-av erag e grad es inste ad of the max
last item and
earc h_C lick even t proc edur e start s at the
39. Rew rite Exam ple 4 so that the btnS
sea rche s backwa rds.

Solutions to Practice Problems 6.3

1. Dim cl ickF l ag As Boo le a n


) Hand l es l stBo x.C l i ck
Priv a t e Sub ls tBox_ Clic k( ...
clic kFl a g = True
End Sub

nde x Chan ged( . .. ) Ha n dles


Priv a t e Sub l stBo x_ Se lec tedi
lstB ox . Sele cted inde xCh a nged
ed by "
e dind exC ha nged eve n t was caus
Dim ms g As Stri ng = "Th e Se lect
Prog ramm ing Proj ects
• 251

If clic kFl ag The n


Mes sage Box .Sho w(m sg & "cli
cki ng on an item of the lis
Els e t box .")
Mes sage Box .Sho w(m sg & "pre
ssin g an arro w key .")
End If
clic kFl ag = Fal se
End Sub

2. The o rd ering in th e list box is deter


mined by the ANS I tab le (whe re the
nume ri cal va lue. Ther efore the last item items are treat ed as strin gs), not the
in the li t box mi gh t not have th e great
es t num eri cal va lue.

CHAPTER 6 SUMMARY
1. A Do loop repe ated ly exec utes a
b lock o f stat e me nts e ith e r as lo n g
ditio n is true . The con dit io n ca n as o r unti l a ce rta in co n -
be c h ecke d e ithe r at the top of the
loop o r a t t h e bo tto m .
2. A For . .. Next loop repe ats a b lock
of state men ts a fixed num be r of time
a sum es an initi al va lue a nd inc rease s. The counter variable
s it by o n e afte r each pass thro ugh the
the term inat ing va lue. A ltern ativ e loop unti l it reac h es
inc re men t va lues can be spec ified
with the Step keywo rd .
3. Vi sual Bas ic uses local t)•pe infer
ence to infe r the d ata type of loca l var
o ut an A s cla use by look ing a t the iab le decl ared with -
data type of the initi a lizat io n exp ress
ion.
4. The item s in a list box a re as
ig n ed index numbers rang ing from
min us 1] . Loo ps can use t h e ind ex 0 to [num be r of it m s
num be rs to extr act info rma tio n from
list box es.
5. A flag is a Boo lean va ria ble used
to indi ca te whe the r a cert a in eve nt
ta in situ a ti o n ex ists. h as occu rred o r a ce r-

CHAPTER 6 PROGRAMMING PROJEC


TS
1. Caf feine Absorption . Afte r caffe
ine is abso rbed in to th e body , 13
body each h o ur. Ass ume a pe rson % is e limi na ted from the
drin ks a n 8-oz c up of brew ed coffee
caff e ine, a nd the caff e ine is a b o rbed con ta ining 130 mg o f
imm edia te ly into the body . Wri te
pute t h e fo llow ing valu e . See Fig. a prog ra m to co m-
6. 12.
(a) The num be r of h o urs requ ired
unti l 65 mg (o n e-h a lf the o rigin a
the body . l a mo unt) re m a in in

I Calcu late Values Evalu ate Rule

One cup : When '•\'ill Intere st rate : 1\


65 mg . remain? 5 hours Rule of 72 doub ling time : 72
Actu al doub ling time : 7

One cup : Quantity Interest rate : 2 3~


after hours : mg . Rule of 72 doubling time : 36
Actual doubling t1me : J£

Hourf>l cups : Quantity Interest rate : 3 ~~


after hours : gss. · mg Rule of 7 doubling time : 2.
.Actu al doub ling time : 2

FIGURE 6.12 Out put of Prog ramm ing Proj ect 1.


FIGURE 6.13 Out put of Prog ramm ing Proj ect 2.
252 • Cha pter 6 Rep etition

ks the coffee.
bod y 24 hours afte r the person drin
(b) The amo unt of caffeine in the a cup of coffee at
of coffee at 7 a.m . and the n drin ks
(c) Sup pose the person drin ks a cup will be in the bod y
the nex t day. How muc h caffeine
the end of eac h hour unt il 7 a. m.
at the end of the 24 hours?
ble due to inflatio n.
Rule of 72 is used to app rox ima te the tim e required for prices to dou
2. The double in 72/r yea rs.
Rul e of 72 estimates tha t prices will
If the inflatio n rate is r%, then the 12 yea rs. Wri te a pro-
6% , prices double in abo ut 72/6 or
For instance, at an infl atio n rate of to 20% , the prog ram
test the acc urac y of this rule. For eac h interest rate from 1%
gram to for prices to
the roun ded valu e of 72/r and the actu al num ber of yea rs required
sho uld disp lay eac h yea r.) See Fig. 6.13.
sum e pric es increase at the end of
double at an r% infl atio n rate. (As
up into the
ram to prov ide info rma tion on the height of a ball thro wn stra ight
3. Wr ite a prog the init ial velo city, v
inp ut the initial height, h fee t, and
air. Th prog ram sho uld requ est as n by the formula
ball (in feet) afte r t eco nds is give
feet per seco nd. The height of the llows:
to be prov ided by but ton s are as fo
h + v t - 16t feet. The four opti ons
2
reac h its max imum
Det erm ine the max imu m heig ht of the ball. Not e: The ball will
(a)
heigh t afte r v/32 seco nds. te the height
ine app rox ima tely whe n the ball will hit the gro und. Hin t: Calcula
(b) Det erm pos itiv e num ber.
ne whe n the height is no longer a
afte r eve ry .1 seco nd and dete rmi
nd for five seco nds or
(c) Disp lay a tabl e sho win g the
height of the ball eve ry qua rter seco
.
unt il it hits the ground. See Fig. 6.14
(d) ui t.

g ... Proj ectil e Motion

Initial Velocity:
Initial Height : 5 ~eet I seco nd)
34
~eet )
Determine ~proximate Tlme j
Determine Maximum Height
~--------------
--~
ll Until Ball Hits The Grou nd

~----D-i-sp_I~_·_T_a_b_le____-J) [ Quit

I DE !E IGH T
0 . 00 5.0
0 .2 5 12 . 5
0 . 50 18 . 0
0 .75 21. 5
1. 00 23. 0
1. 2 5
1 .5 0 20 . 0
1. 75 15 . 5
2. 00 9. 0
2.2 5 0.5

g Pro ject 3.
FIGURE 6.14 Sam ple Out put for Pro gram min

rds, cha ract e r


is a wor d or phr ase tha t read s the sa me fo rwa rd s and backwa
4. A palindrome mpl es are "rac eca r",
atio n , case, and spaces. Some exa
for cha ract er, disrega rdin g punctu tha t allo ws the use r to
ada m, I'm Ad am. ", and "W a it a cat I saw ?". Wr ite a program
"M sho uld use a
or phr ase and the n dete rmi nes if it is a pali ndr ome . The pro gram
inp ut a word the valu e Tru e whe n
named lsPa lind rom e tha t retu rns
Boo lean- va lued Functio n proced ure
and the valu e False oth erwise.
the word or phrase is a palindr ome
Prog ram min g Projects
• 253
5. The following words hav e thre
e con sec ut ive lett ers tha t are also
the alph abe t: TH IRS TY , AF GH co nsecut ive lett e rs in
AN IST AN , ST UD EN T Wr ite a
word as inp ut and dete rmi nes whe prog ram tha t acc epts a
ther or not it ha thre e con sec utiv
sec utive lette rs in the alph abet. The e lett ers tha t are con-
prog ram sho uld use a Boo lean -va
IsT ripl eCo nse cuti ve tha t accepts lued fun ctio n named
an enti re word as input. Hin t: U se
the Asc fun ctio n.
6. Wri te a program tha t uses a flag
and does the fo llow ing:
(a) Ask the user to inp ut a sen ten
ce con ta ining parentheses. Not e:
sis shou ld not d irec tly precede the The clos ing par enth e-
period.
(b) Disp lay the sen tenc e with the
pare nth eses and the ir con ten ts rem
gram wit h the fo llow ing sen tenc oved. Tes t th e pro-
e as inpu t: BA SIC (Begin ner 's A
In truc tion C ode) was once the wor ll-purp ose Sym boli c
ld's mos t wid ely known co mpu ter
language.
7. Depreciation to a Salvage Value
of 0 . For tax purposes an item may
peri od of several years, n. Wit h the be dep reciated ove r a
straight-line met hod of dep rec iatio n,
d preciates by 1/nt h of it orig inal eac h year the item
valu e. W ith the double-declining-ba
ciat ion, eac h year the item dep rec lance met hod of dep re-
iate by 2/n ths of its va lue at the
(In the fina l yea r it is dep reciated beg inn ing of tha t year.
by its va lue at the beginn ing of the
tha t performs the following tasks: yea r.) Wr ite a prog ram
(a) Req uest a desc ription of the
item , the yea r of pur ch ase, the cos
ber of yea rs to be dep reciated (est t of the item , the num -
ima ted life), and the met hod of
met hod of dep reci atio n shou ld be dep reciat i n. The
cho en by clic king on one of two
(b) Display a yea r- by-year desc ript but ton s.
ion of the dep rec iat ion. See Fig. 6.15
.

to a Salv age V a l e o 0

Description Year of
c omputer
of item : purc ha<:e : Estim ated life of
Cost : 15
item l)oear<:):
Straight-U ne Meth od
Doub le- Declining-Bala nce Meth
od

Description : computer
Year of purchase : 1 B
Cost : " 1..5
E..<:timated life : 5
Meth od of depreciation : straight-lin
e

Value at beginnin g of 2 H: "15


.
Amount of depreciation during 2
.
Tota l depreciation at end of 2
•B: S-3.

Value at beginning of 1 : <:;Ef


.Amo unt of depreciation during
Tota l depreciation at end of 2:
1

FIGURE 6.15 Sam ple outp ut of Pro gram min g


Pro j ect 7.

8. An especia lly effic ient tech niq


ue for searchi ng an ord ered li t of
sea rch . A bin ary sea rch looks for items is ca lled a bin ary
a va lue by first dete rmi nin g in whi
resides. The oth er half of the list ch half of the list it
is the n igno red, and the reta ined
rega rded as the enti re list. The proc half is temporaril y
ess is repe ated unt il the item is fou
nd or the enti re list
254 • Ch apt er 6 Rep etit ion

ary sea rch sho wn below to


n con sid ere d. Use the alg orithm and flowcha rt for a bin
has bee le 4 of Sec tion 6.3.
eve n t procedure fro m Exa mp
rewrite t e btn Sea rch _C lick a bin ary sea rch. (Th e sough
t-a fter va lue is
ws a par tial flow cha rt for n
Figure 6. 16 sho wh eth er or not quarry has bee
ote d by qua rry. Th e Boo lea n variable flag keeps trac k of is as fo llow s:
den an ord ered list box
bin ary sea rch of the items in
found .) Th e algori thm for a d list by first and the
e, den ote the ind ex of the first item in the reta ine
(i) At eac h stag the va lue of las t to
las t item by last . Ini tially, set the value of firs t to 0, se t
ind ex of the va lue of flag to False.
item in the list , and set the
one less tha n the num ber of

No

Calculate
middle

Yes Set
flag = True

Yes Set last =


middle -1

Set first=
middle + 1

of a bin ary sea rch .


FIGURE 6.16 Flo wch art for the loop por tion
Programming Projects
• 255

(ii) Look at the middle item of the curren t list-th e item


hav ing index middle =
C lnt( (first + last )/2) .
(iii) If the middle item is quarry, then se t flag to True and end the
search.
(iv) If the middle item i greater than quarry, then quarry sho uld
be in the first ha lf of the
list. So the index of quarry must lie betwee n first and middle - 1. Set
last to middle - 1.
( v) If the middle item is less than quarry, then quarry h.ould be
in the second ha lf of the
list of poss ible items. So the index of quarry must lie betwee n middle+
1 and las t. Set
first to middle+ 1.
(vi) Repea t steps ( ii) through. ( v) until quarry is found o r until the
h alving process use up
the entire list. (When the entire list h as been used up , first > last.)
In the second case,
quarry was no t in the original list.
Ar ra ys

7.1 Creating and Accessing Arrays 258


• Decl aring an Arra y Variable • The Load Even
t Proced ure • Impl icit Arra y S izing
and Init ialization • Text Files • Arra y M thod s
• Calc ulati ng an Arra y Valu e with a
Loop • The ReD im State men t • Flag Variab les
• For Each Loop • Passing an Arra y
to a Proc edure • User -Def ined Array-Valued Func
tions • Searchin g for an Element in
an Arra y • Copy ing an A rray • Split Meth od and
Join Func tion
7.2 Using LINQ with Arrays 281
• LINQ Quer ies • The Disti nct Oper ator • The
ToA rray Meth od • Use of Func tion
Proc edure s in Quer ies • The Let Oper ator • The
Orde r By Oper ator • The
Data Sour ce Prop erty • Binary Sea rch
7.3 Arrays of Structures 294
• Struc tures • Arrays of Stru cture • The Data
GridView Cont rol • Sear ching an
Arra y of Struc tures • Usin g Gene ral Proced ur s
with Struc tures • Disp lay ing and
Com parin g Struc ture Valu es • Complex Struc tures
(opti onal)
7.4 Two-Dimensional Arrays 319
• Decl aring a Two-Dim n iona l Arra y Variable
• Implicit Arra y S izing and
Initia lizati on • The ReD im State ment • Fillin g
a Two -Dim ensio nal Arra y with a Text
File • Using LINQ with Two- Dimens iona l Array
s
7.5 A Case Study: Analyze a Loan 332
• The User Interface • Desi gning the Ana lyze-
a-Loan Program • Pseudoco de for the
Anal yze-a -Loa n Program • The Ana lyze-a-Loan
Program
Summary 340

Programming Projects 341

257
258 • Chap ter 7 Arrays

7.1 Creating and Accessing Arrays


value. An
to whic h Visual Basic ca n assign a ingle
A var iab le (o r simp le varia ble) is a nam e h Visual
variab les of the same type, to and from whic
array varia b le i an inde xed list of simple
of va lu es.
Basic can effic ientl y ass ign and access a list 30 stu-
yo u want to eva lu ate the exa m grad es fo r
Con side r the following situa tion: S uppose to disp lay the
the ave rage score, but you also wan t
dent s. N ot only do yo u want to com p ute o utlin ed
abov e ave rage. You migh t run the prog ram
nam es of th e stud ents whose grad e are g with 0
d num berin gs- that i , num berin gs beg innin
be low. Note : Vi ual Bas ic prefers zero-base g of the pos ition s in a
hapt er 3, whe re the num berin
inste ad of 1. (We saw this prefe renc e in C grad es from 0
num ber th e 30 stud ent nam es and
strin g bega n with 0.) The refore we will
throu gh 29 mste ad of from 1 throu gh 30.

) Han dles btnD ispl ay . Clic k


Priv ateS b btnD ispl ay_ Clic k( ...
As Dou ble
Dim stud entD As Stri ng , grad eD
grad el As Dou ble
Dim stud entl As Stri ng ,

As Dou ble
Dim stud ent2 9 As Stri ng , grad e29
'Ana lyze exam grad es
ter name of stud ent #"
Dim pro ptNa me As Stri ng = "En
= "En ter grad e for stud ent #"
Dim prom ptGr ade As Stri ng
& D, "Nam e" )
stud en t D = Inpu tBox (pro mptN ame
omp tGra de & D, "Gra de" ))
grad eD= CDbl (Inp utBo x(pr
ame & 1, "Nam e" )
stud en t 1 = Inpu tBox (pro mptN
CDbl (Inp utBo x(pr omp tGra de & 1, "Gra de" ))
grad el

& 29, "Nam e" )


stud ent 29 = Inpu tBox (pro mptN ame
omp tGra de & 29, "Gra de" ))
grad e2 9 = CDbl (Inp utBo x(pr
'Com pute the aver age grad e

with abov e-av erag e grad es


'Dis play the name s of stud ents

End Sub

30 D im
y lo ng. Wha t's mos t frust rat ing is that the
This prog ram is go ing to be unco mfo rtabl as if they hould
ining inpu t are very similar and look
state men ts and 30 pairs of state men ts obta d be we l-
t ion fo r the man y relat ed varia bles woul
be cond ense d into a loop. A shor th and nota
com e. It wou ld be nice if we co uld just write

For i As Inte ger = D To 29


& i , "Nam e" )
stud en ti = Inpu tBox (pro mptN ame
omp tGra de & i, "Gra de" ))
grad e i = CDbl (Inp utBo x(pr
Nex t

les and
will treat studenti and grade i a two variab
Of course, this will not work . Vi ual Ba ic lues of the
the end of the loop, they will h ave the va
keep reass ignin g new va lues to them. At
thirt ieth stud ent.
7.1 C reating and Acc essin g A rrays
• 259

Declaring an Array Variable


Visu al Bas ic prov ides a data stru ctur e
ca lled an arra y that lets us do wha t we
in the loop above. The vari able nam tried to acco mplish
es, similar to those in the loop , will be
stud ents ( O), stu den ts(l ),
stud ent s(2 ), stud ent s(3 ),
. .. , stud ents (29 )
and

grad es(O ), gra des (l), grad


es(2 ) , gra des (3), ... , grad es(2 9)
We refe r to t hese coll ecti ons of vari able
s as the arra y vari ables students and grad
insid e the pare ntheses of the indi vidu es . The num bers
a l vari ables are calle d subs crip ts o r
indi vidu al va riab le is call ed a sub scri inde xes , and each
pted vari able o r elem ent. For inst ance
four th elem en t of th e array students , students(3 ) is the
, and grades (20) is the twen ty-first e lem
grades. The elem ents of an array are loca ent of the array
ted in succ e sive mem ory loca t ion .
th e mem o ry loca tio ns fo r the array grad Figu re 7.1 sh ows
es.

grades(O) grades( 1) grades(Z) grades(29 )


grade s

FIGURE 7.1 The arra y grades.

N ames of array va riab les fo llow the


same nam ing con ven tion s as simple va riab les.
arrayName i the nam e of an arra y variable If
and n is a literal, vari able , or exp res io
ge r, then the decl aratio n stat eme nt n of type Inte -

Dim arra yNa me( n) As Dat aTy


pe

rese rves space in mem ory to ho ld


the valu es of the subscrip ted vari ables
arrayName( l) , a1TayName(2), .. . , mTa arra yNa me(O),
yNa me(n). The va lu e of n is call ed th e
th e array. The nu mbe r of elem en ts in upp er bou nd of
th e array, n + 1, is call ed the size of
sc ripte d variables will a ll h ave t he sam the array. The sub-
e data type -na mely, the type spec ified
inst ance , they cou ld all be vari ables by DataType. Fo r
of type S tring or all be vari ables of type
ular, the stat eme nts Dou ble. In part ic-

Dim stud ents (29 ) As Stri ng


Dim grad es(2 9) As Dou ble

decl are the 30-e lem ent arrays need ed


fo r the preced ing prog ram .
Valu es can be ass igne d to indi v id ual
subscrip ted variables with assignme nt
d isplayed in tex t boxes and list boxe stat eme nts and
s ju t like valu es of ordi nary va riab le
va lue of each ubsc ripte d variable is the . The defa ult initia l
sa me as with an o rdin ary variable -th
N o th ing fo r Stri ng types and 0 for n ume at is, the keyword
ric types. The stat eme nt
Dim grad es(2 9) As Dou ble

sets as ide a port ion of memory for the


array grades and assigns the defa ult valu e 0 to each
elem ent.

grades(O) grade s( 1) grade s(2) grades(29 )


grades 0 0 0 0
Cha pter 7 Arra ys
260 •
The stat eme nts

gra des (0) 87


gra des (1) 92

ents of the array.


assign value , to the fi rst two elem

grades(2 ) grad es(2 9)


grades(O) grades( 1)

0 0
grad es 87 92

The stat eme nts

For i As I nte ger = 0 To


2
des (i ) )
lstB ox. I tem s.A dd( gra
Nex t
in the list box:
the n produce the foll owing out put

87
92
0
of the Cod e Edi-
an ord inar y vari ab le, an arra y declared in the Dec lara tion s section
As with , and any values as igned
visible to all proced ures in the form
tor is cla s-level. Tha t is, it will be vari able s dec lared inside a
r the proced ure term inat es. Array
to it in a procedure wi ll persist afte ure is ex ited.
ure are loca l to tha t pro ced ure and cease to ex i t whe n the proced
pro ced

es of the
str ing array con sist ing of the nam
The foll ow ing prog ram creates a .
the prog ram
re 7.2 shows the array crea ted by
fi rst four Super Bow l winners. Figu

team Nam es(2 ) team Nam es(3 )


team Nam es(O) team Nam es( 1)

Jets hief
Pack ers Pack ers
team Nam es

e 1.
FIGURE 7.2 The a rray team Nam es of Exa mpl

PROPERTY SETTING
OBJECT
D Earl-; Super Bowls ~@] [};!] frmB owl Tex t Earl y S upe r Bowl
Num ber from 1 to 4:
Numberfrom 1 to 4: [ Vl/ho Won? I lblN u mbe r
mtb Num ber
Tex t
Mas k 0
btnW hoW on Tex t Wh o W on ?
Winning team : Tex t Win ning team:
lblW inne r
txt Win ner Rea d O n ly True

on.C lick
ck ( ... ) Han dle s btnW hoW
Pri vat e Sub btnW hoW on_ Cli
ing
Dim t eam Nam es(3 ) As Str
Dim n As Int ege r
s int o the arr ay
P ace Sup er Bow l Win ner
7.1 Creating and Accessing Arrays • 26 1

teamNames (0) "Packers"


teamNames ( 1) "Packers"
teamNames (2) "Jets"
teamNames (3) "Chiefs"
'Access array
n = Cint (mtbNumber.Text)
txtWinner.Text = teamNames(n - 1)
End Sub

[Run, type 2 into the masked text box, and click on the button.]

a~ Eallly Super Bowls

Numberfrom 1 to : 2 ( Vllho Won?

Winning team: Packers

The Load Event Procedure


In Example 1, the array team Names was ass igned va lues in the btn Who W on_ C lick eve nt pro-
Video ote
cedure. Eve ry time the button is clicked, the values are reass igned to the array. This approach
Fill ing arrays
ca n be ve ry ineffi c ient, espec iall y in programs with large arrays, where the task of the program
(in Example 1, looking up a fact) may be repeated numerous times fo r different u er input.
When , as in Example 1, the data to be placed in an array are known at the time the program
begins to run, a more effic ient locat ion for the statement that fi ll the array is in t he fo rm's Load
event procedure. A form 's Load event occurs just before the fo rm is displayed to the user. It is
the default event fo r the fo rm . The header for the Load event procedure is

Private Sub frmName_ Load( ... ) Handles MyBase .Load

The keywo rd MyBase is imilar to the Me keywo rd and refers to the fo rm. Exa mple 2 uses the
frmBowl_Load procedure to improve Examp le 1.

Example 2 The fo llowing variatio n of Exa mple 1 makes teamNames a clas -leve l array
and ass igns values to the elements of the array in the event procedure frmBowl_Load.

Dim teamNames(3) As String

Private Sub frmBowl _ Load( ... ) Handles MyBase .Load


'Place Super Bowl Winners into the array
teamNames (0) "Packers"
teamNames (1) "Packers"
teamNames ( 2) "Jets"
teamNames (3) "Chiefs"
End Sub

Private Sub btnWhoWon_ Click( ... ) Handles btnWhoWon.Click


Dim n As Integer
n = Cint (mtbNumber.Text)
txtWinner . Text = teamNames(n - 1)
End Sub
262 • Chapter 7 Arrays

Implicit Array Sizing and Initialization


Like ord inary variab les, array variab les can be assigned initial values when they are declared. A
statement of the form

Dim arrayName() As DataType = {valueO, valuel, value2, ... , valueN}

declare an a rray hav ing upper bound N and a signs valueO to arrayName(O), value 1 to
arrayName(l ), value2 to arrayName(2), .. . , and valueN to arrayName(N). For instance, in
Example 2, the Dim statement and frmBowl_Lo ad event procedure can be replaced by the
single line

Dim teamNames () As String = { "Packers" , "Packers" , "Jets" , "Chiefs" }

Note: Yo u cannot use a li t of values in braces to fill an array if an upper bound has been
specified for the array. For instance, the fo llowing line of code is not va lid :

Dim teamNames(3) As String = { "Packers" , "Packers" , "Jets" , "Chiefs" }

Text Files
The two eth ods we have u ed to fill an array are fine fo r small arrays. H oweve r, in practice
arrays can be quite large . One way to fill a large array is to use a simple data file known as a
text file . Text files ca n be created, viewed, and modified with sophi ticated word processors
such as Word, o r with e leme ntary word processo rs such a the Windows acces a ries W o rdPad
and Notepad. They differ from files normally created with Word in th at they h ave no fo r-
matt ing (such as line spac ing and font style ). They are pure tex t and no thing e lse-hence the
name text file. For instance, a text file that co uld be used to fill the array in Example 1 wo uld
look as f llows:

Packers
Packers
Jets
Chiefs

The text files needed fo r exercises in this book h ave been created for yo u and are in th e
material you downloaded from the compan ion website. They are contained in a subfolder
(named Text_Files_for_ Exerc i es ) of the appropriate ch ap ter folder. Each text file ends with the
extension ".txt".
The isual Basic IDE provides simple ways to create and ed it text fi les. The deta ils can be
found in Appendix B. C hapter 8 shows how to create text files program matically.
A statement of the form

Dim strArrayName () As String = IO. File .ReadAllLine s(filespec)

where filespec refers to a text file, declares a string array whose size equals the number of lines in
the file, and fills it with the contents of the file. A numeric array can be filled with a text file by
first filling a temporary string array with the file and then using a loop, along with C lnt o r CDbl,
to transfer the numbers into the numeric array. (See Example 3.) Note: ln Section 7.2, we pre-
sent a way to fill a numeric array with the contents of a numeric tex t file without using a loop.
The Solu tion Explorer window ha the name of the program as its first line. If only a few
entries appear in the Solution Exp lorer, you can click on the Show All Files button ( ~) at the
7.1 rearing and Accessing Arrays
• 263

top of th e Solutio n Exp lorer wind ow to display all the fi les and
subfo lders. O ne subfo lder is
named bin. The folder bin h as a subfo lde r named Debug. lf the filespec
above consists only of a
filename (that is, if no pa th is given) , Visual Bas ic will look for
the fi le in the Debug subfo lder
of the progra m 's bin fo lder. Throu ghout this book, we assume that
every text file accesse d by
a progra m is located in th e progra m 's bin \Debug folder. Ev ery
progra m down loaded from the
compa nion website h as th i fea ture. When you write a progra m
that uses o ne of the tex t files
fro m a Text_Fi les_for_ Exerc ises fo lde r, you sho uld use Windo ws
Explorer to place a copy of the
text fil e into the program 's bin \Debug fo lder.

Array Methods
Both nu meri c and string arrays have the Co unt, Max , Min, First,
and La t metho ds. 1 The value
of arrayName.Co unt is the size of the array, arra)>N ame. Max is the VideoNo te
h ighe t va lue (alpha bet ically
or numeri cally), arrayName. Min is the lowest value, arrayName. Array
First is t he first e lement of the merhods
array, and arrayName.La t is the last elemen t. Note: The
upper bo und of the array is
arra)>Name.Co unt- 1. Table 7.1 shows some va lues with the array
from Exa mp le 1.

lfi':J!QM Some values from Example 1.


Expression Value
teamNa mes . Count 4
te amName s .Max Packers
t eamNam es . Min C hiefs
t eamNam es . First Packers
teamNa me s.Last C hiefs

When workin g with numer ic arrays , we often also want to compute


the average and total val-
ues fo r the e lements. The average va lue is given by arrayName.Av
erage and the total valu e by
an·ayName.Sum. The program that follows illustra tes the use of array method
s for a n umeric array.

Example 3 The file A gesAtl naugur al. txt giv s the ages at inaugurat ion of
the 44 U. .
pres id ents. The first fo ur line conta in the data 57 , 61 , 57, 57- th
age fWa hingto n , Ad ams,
Jeffer on , and Madiso n at the ir inaugu rat ions. (To see the co ntents
of the fi le in a text edito r,
locate the file in the bin \Debug fo lder of t he Solutio n Explo rer and
double -click on the fi le. You
ca n remove the text edi to r by cl ick ing the X symbo l on its tab.)

Privat e Sub btnDi splay _ Cli c k ( . .. ) Handle s btnDi


splay. Click
Dim ages (4 3) As Intege r
Dim temp ( ) As String = IO. File . ReadA llLines ( "Ages
Atinau gural. txt" )
For i As Intege r = 0 To 43
ages (i ) = Cint (temp ( i ) )
Next
lstVal ues . Items . Add ( "Obama : " & ages (ages. Count
- 1))
lstVal ue s . Items . Add ( "Wash ington : " & ages. First)
lstVal ues . Items . Add( "Obama : " & ages.L ast)
lstVal ues . Items . Add ( "Olde st age: " & ages.M ax)
lstVal ues . Items . Add( "Youn gest age: " & ages.M
in)
lstVal ues.Ite ms.Ad d( "Avera ge age: " & Forma tNumb
er(age s.Aver age))

'The prop rty Le ngth ca n be used instead of the Count method


. W e favo r Coun t, since it a lso can be
used wit h LINQ q ue ri es.
264 • Chapt er 7 Arrays

Form atNw nber( ages.S um 1 ages. Coun t))


lstVa lues .I tems . Add( "Aver age age: " &
End Sub

[Run, and click on the butto n.]

a ... Pres iden ial Ages at Inaug uratio n l= / @) /,...,tJ _.J

( Display Values J
rc--
Obama : 47
Washington: 57
Obama : 47
Oldest age : 69
Youngest age : 42
Average age : 54.84
Average age : 54.84

Calculating an Array Value with a Loop


ated with loops. The following exam ple
Some of the va lues discussed above also can be calcul
be calcu lated with a For ... Next loop.
shows how the value retu rned by the Max metho d ca n
with loop in the exerc ise se t.
Some other va lues return ed by me thods are calcul ated

n of the las t nine pres-


Example 4 Consider the array consi ting of the ages at inauguratio
the age of the fi rst of the nine presidents
idents. To find the max imu m age, we temporarily take
ed, after lookin g at each succe sive age.
as the maximum and then adjust the max imum , if requir
les btnC alcul ate . Click
Priva te Sub btnC alcul ate_ Click ( ... ) Hand
on for the last 9 presi dents
'Calc ulate the maxim um age at inaug urati
52, 69, 64, 46, 54, 47}
Dim a g es() As Integ er = {55, 56, 61,
Dim max As Integ er = ages( O)
For i As Integ er = 1 To ages. Coun t - 1
If ages( i) >max Then
max= ages( i)
End If
Next
" & max & "·"
txtO tput. Text = "The gre atest age is
End Sub
in the text box.]
[Run, and click on the butto n . The follow ing is displayed
The gre atest age is 69.

The ReDim Statement


can be changed with a statement of
After an array has been declared, its size (but not its type)
the form

ReDim arrayN ame(m )

and m i an Intege r litera l, variab le,


where arrayName i the name of th already declared array
there is no need for an "As DataType"
or expression . Note: S ince the type canno t be changed,
clause at the end of a ReDim state ment.
7.1 C reat ing and Access ing A rrays • 265

Visual Basic allows you to declare an array wit hout spec ifying an upper bound with a state-
ment of the fo rm
Dim arrayName( ) As DataTyp e

Later, the size of the array can be spec ified with a ReOim statemen t. (N o va lues can be ass igned
to the e lemen ts of the array until a size is spec ified.)
The Re Dim statement h as on e shortco ming: It ca u es t he array to lose its current contents.
That is, it rese ts a ll string va lues to No th ing and resets all nu meric va lues to 0. Th is situation
ca n be remedied by foll owing ReOim with th e keywo rd Prese rve. The ge nera l fo rm of a ReOim
Prese rve statement is
ReDim Pre s e rv e array Name(m )

Of course, if you make an array smaller than it was, data at the end of the array will be lost.

Example 5 T h e following program reads the names of the winn ers of the fi rst 44 S uper
Bowl games from a tex t fi le and places th em into an array. The use r can type a tea m's name into
a text box and then d isplay the numbers of th e S uper Bowl games won by that tea m. The use r
has the option of adding winners of subseq uent games to t he array of winners. The program uses
th e fi le SBWinners. txt, whose lines con ta in the names of th e winners in order. Tha t is, th e first
four lines of the file co nta in the names Packers, Packers, Jets, and C hiefs.
Dim teamNames() As String
Dim numGames As Integer

Private Sub frmBowl _ Load( ... ) Handles MyBase .Load


teamNames = IO . File . ReadAllLines( "SBWinners.txt" )
numGames = teamName s. Count
'Note "Me" refers o the form
Me .Tex t = "First " & numGames & " Super Bowls"
Specify the capt~on of the Add Winner button
btnAddWinner.Text = "Add Winner of Game " & (numGames + 1)
End Sub

Private Sub btnDisplay_ Cl ick( ... ) Handles btnDisplay . Click


'Display the numbers of the games won by the team in the text box
Dim noWins As Boolean = True 'Flag to detect if any wins
lstGamesWon . Items.Clear()
For i As Integer = 0 To numGames - 1
If t e amNames(i) . ToUpper = txtName . Text . ToUpper Then
lstGamesWon.Items . Add(i + 1)
n oWin s = False
End If
Next
If noWins Then
lstGamesWon . Items.Add( "No Games Won" )
End If
End Sub

Private Sub btnAddWinner_ Click( . . . ) Handles btnAddWinner.Click


'Add winner of next Super Bowl to the array
Dim prompt As String
'Add one more element to the array
266 • Chapter 7 Arrays

ReDim Preserv e teamNam es (numGam es)


numGame s += 1
'Reques t the name of the next winner
prompt = "Enter winner of game #" & numGame s & "·"
teamNam es (numGam es - 1) = InputBo x (prompt, "Super Bowl" )
'Update the title bar of he ~orm and the caption of the button
Me .Text = "First" & numGame s & "Super Bowls"
btnAddWinner.T ext = "Add Winner of Game " & (numGam es + 1)
End Sub
to add subse-
[Run, type "Steelers" into the text box, and press the Display button. Then fee l free
quent winners. Your addition s will be taken into account when you next press th e Di play butto n .]

a First 44 Super Bowls

Name of football team : Steelers

Display Games T earn Won

9
10
13
1
40
43
Add Winner of Game 45

Flag Variables
keeps track of
The Boolean variable no Wins in th e btnDisp lay_C lick proced ure of Examp le 5
are used within
wh ethe r a certa in situatio n h as occurred. Such a varia ble is called a flag. Flags
lso prov ide an
loops to provide info rmat io n that will be utilized after the loop term ina tes. Flags a
a lte rnat ive meth od of terminat ing a loop.

For Each loops


with the fol-
Cons id e r Example 3. The entire sequence of ages can be disp layed in the list box
low ing statemen ts:
For i As Integer = 0 To 43
lstVa l ues.Item s.Add(a ges(i))
Next

The first line of the Fo r .. . Next loop a lso could h ave been wr itten as

For i As Integer = 0 To ages . Count - 1


type of
In the two Fo r sta tements, th e lo wer bound and upper bo und a re given . Another
a rray in o rder with n o men-
loop, called a For Each loop, cycles through a ll the e leme nts of the
o utput as the
tion wha tsoever of the two bounds. The fo llowing block of code h as the same
Fo r ... Next loop above.
For Eac h age As Integer In ages
lstVa lues.Ite ms.Add (age)
Next
7.1 C reating and Access ing A rrays
• 267

In genera l, a block of the form


For Each v a r iab leNam e As DataT ype In array
Name
st ateme nt ( s )
Next
where DataType i the data type of th e array, declares the loopin
g variab le variableName to be of
that type, and execu tes the statement(s) once for each eleme
nt of the array. That is, at each it ra-
tion of the loop, Visual Basic sets the variab le to an eleme nt
in the array and execut es the state-
ment( s). Wh en all the eleme nts in the array have been assigne
d to the variab le, the For Each loop
termin ates and the statement follow ing the Next statement is
execut ed. Note: When you use local
type inferen ce (allowed when Optio n Infer is et to On), you
can omit the As DataType clause.
Altho ugh For Each loops are le s complicated to wr ite than
For . .. N ex t loops, th ey have a
major limita tio n. They canno t alter the va lues of eleme nts
of the array.

Passing an Array to a Procedure


An array declared in a procedure is local to that procedu re and
unknown to all other procedures.
H oweve r, a local array can be passed to anothe r procedu re. Th
argum ent in the calling statement
consists of the name of the atny. The corresponding parameter
in the header for the procedure must
consist of an array name followed by an empty set of parent
hese . Like all other parameters, array
parameters are preceded with ByVal or ByRef and are follow
ed with "As DataType" clauses. How-
ever, any change to elements of an array passed by value persist
after the proced ure termin ates.

Example 6 The follow ing variat ion of Examp le 4 ca lculates the max imum
value with a
Funct ion proced ure. Notic e th at the pa ramete r in the funct
ion heade r is wr itten ByVa1 ages ( J
As I ntege r , not By Va1 ages As Integ er , and
the functi o n call is wri tten Maxim um(ag es ) ,
not Maxim um (ages () ) .

Priva te Sub btnCa 1cu1a te_ Click ( ... ) Handl


es btnCa lculat e . Click
C lc 1 t e re t a e augu a io fo the last 3 presi dents
Dim a g es( ) As Integ er = {55, 56, 61, 52,
69 , 64, 46, 54, 47}
t x tOutp ut.Te xt = "The great est age is " &
Maxim um (ages) & " · "
End Sub

Funct ion Maxim um (ByVa l ages () As Integ er )


As Integ er
Dim max As Integ er ages(O )
For i As Integ er = 1 To ages . Count - 1
If age s (i) > max Then
max = ages (i)
End If
Next
Retur n max
End Funct ion

[Run, and click o n the button. T he follow ing is d isplaye d in


the text box .]
The maximum age i s 6 9 .

User-Defined Array-Valued Functions


A Funct ion proced ure with a heade r of the form

Funct ion F un c ti onNam e (ByVa l varl As Typel


,
ByVa1 v ar2 As Type 2 , . . . ) As DataT ype ()
268 • Chapt er 7 Arrays

set of paren theses fo llowing DataType


returns an array of type DataT ype as its value. The empty
instead of just a single va lue.
tells us that the Funct ion procedure will return an array

grades . T he n umber
~ Example 1 T he fo llowin g program calc ulates the average of eve ral
r via inp ut d ialog boxes . The Function
of grades a d the grades themse lves are input by the use
s.
proced ure G etG rades return s an array con tainin g the grade
btnG et . Click
Priva te Sub btnG et Click ( . .. ) Hand les
Cint (Inpu tBox( "Num ber of grade s: " "Grad es" ) )
Dim n umGr ades As Integ er =
s) .Aver age)
t xtAv e r age.T ext = CStr (GetG rades (num Grade
End Sub

Integ er ) As Doub le ()
Func tion Ge tGrad es( ByVa l numGr ades As
Dim g r a des (numG rades - 1 ) As Doub le
For i As I n t eger = 1 To n umG rades
& i & " : " "Get Grade " ))
gra d e s (i - 1 ) = CDbl (Inpu tBox( "Grad e #"
Next
Retur n g r ades
End Func t ion
grade s 80, 85, and 90.]
[Run, enter 3 as the numb er of grades, and then enter the

a De ermine Averag e Grade

Get Grades and


Calculate Average

Average : 85

Searching for an Element in an Array


eleme nts hav ing a va lue specified by the
In Example 5, a loop is used to find the ind ices of the
that i espec ially effici ent with large
user. Visua l Basic h as a method for locati ng eleme nts
literal or exp ress ion of the same type as
arrays. Let numVar be an intege r variable and value be a
the eleme nt of a1TayN am e. Then a statement of the form
)
nurnV ar = Array .Inde xOf ( array Name , value
the reques ted value in a1TayName . If the
assigns to numVar the index of the first occurrence of
va lue is not found, then - 1 is assign ed to numVar .

order in which they


..;' Example 8 T he file States. txt con tains the 50 U.S. states in the
s:
jo ined the union. The first four lines of the file are as follow

De l awa r e
Pen n syl v a ni a
Ne w J e r sey
Georg i a
then tells the order in which it jo ined
The fo llowin g progra m requ ests the name of a state and
the union:
Dim s t a t es() As Strin g I O. File .Read AllLi nes( "Sta tes.t xt" )
7.1 C reating and Access ing Arrays • 269

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


Dim n As Integer , state As String
state = txtState.Tex t
n = Array.IndexO f(states, state)
If n <> -1 Then
txtOutput . Text = state & " was state number " & n + 1 & II II
Else
MessageBox . Show( "Re-enter a state name.", "Error" )
txtState.Cle ar()
txtS tate. Focus ()
End If
End Sub

[Run, type a state into the top tex t box, and click on the button .]

a~ U.S. Sta es l = I @) L Sl . .I

State name : Califomia

Determine Order

Califomia was stat e number 31.

If a va lue might occur more than once in an array, an ex tension of the method above will
loca te subsequent occurrences. A tatement of the form
numVar = Array . IndexOf ( arrayName, value , startindex)

where startlndex is an intege r literal or ex pression , looks on ly at elements hav ing index
startlndex or greater, and ass igns to numVar the index of the first occurrence of the req uested
va lue. If the value is not found, then - 1 is ass igned to numVar.

Copying an Array
If arra)'One and arra)'Two have bee n declared with the sa me data type, then the statement
array Two = arrayOne

makes arra)'Two reference the same array as arra)'One. It will have the ame ize and co nta in the
sa me data. This statement must be used with care, however, since after it is executed, arra)'One
and arra)'Two wi ll share the same portion of memory. Therefore, a change in the va lue of an ele-
ment in one of the arrays will affect the other array.
O ne way to make a copy of an array that does not share the same memory locat ion is ill us-
trated by the following code:
'Assume arrayOne and arrayTwo have the same data type and size
For i As Integer = 0 To arrayOne . Count - 1
arrayTwo(i ) = arrayOne ( i)
Next

Split Method and Join Function


The Split method provides another way to ass ign va lues to an array. The following code creates
the array of Examp le 1:
Dim teamNames() As String
Dim l i ne As String = "Packers,Pac kers,Jets,Chi efs"
teamNames = line . Split ( ","c )
270 • Chapter 7 Arrays

In ge era!, if strA rray is a string a rray a nd the string va riab le strVar h as been ass ign ed a
string of t he fo rm
"valueO,value l ,value2, ... ,valueN"
the n a sta tement of th e fo rm
strArray = strVar . Split( ","c )
resize strArray to an array with upper bound N having strA nay(O) = valueO , strAnay ( 1) = value
1,
... , strArray (N) = valueN. That is, the first element of the array conta ins the text preceding the
first comma, the second element the text between the first and second commas, ... , and the last ele-
men t the t xt fo llowing the la t comma. The comma character i called the delimiter for the statement
above, and th letter c specifies that d"le comma should have data type C haracter instead of String. Any
character can be u ed as a delimiter. (The two most common delimiters are dl.e comma character and
the space character.) The Split medl.od will play a vital role in Section 7.3.

Examp.le 9 The fo llow ing progra m de te rmines a pe rson 's first a nd last n a mes. The space
ne
ch aracter is used as the de limiter fo r the S plit method. Each e le ment of the a rray conta ins o
part of th pe rson 's full na me.

OBJECT PROPERTY SETTING


ll _. Pa r!ie a Name GJI @) !@:] frmName Tex t Parse a Na me
lblFull Text Full name:
Full narr e: William Howard Taft txtFull
btnExtract ~ xt Ex tract First and Last Names
[ &tract Rrst and Last Names lblFirst Text First name:
txtFirst ReadO nly True
Rrst name: lblLast Text Last name:
txt Last ReadO nly True
L.c.st name:

Private Sub btnExtra ct Click( ... ) Handles btnExtra ct.Cl ick


Dim f u llName As String = txt Full . Text
Dim p a rsedName () As String = fullName .Split( " "c )
txtFi r st.Text = parsedNa me.First
txtLa t.Text = parsedNa me.Last
End Sub

[Run, en ter a full name , and click o n the butto n.]

Full name : William Ho•; •ard Taft

( Extrac-t Rrs1 and la&1 Names )

First name: William

Last name: Taft


Creatin g and Access ing Arrays
7.1
• 271

The reverse of the Spli t metho d is the Join functi on , which


return a string value con ist-
ing of the eleme nts of an array conca tenated togeth er and sepa
rated by a specifi ed delim iter. For
insta nce, the code

Dim greatL akes( ) As Strin g =


{ 11 Huron 11 , 11 0ntar io 11 11
Michi gan 11 11
Erie 11
, , , nsupe riorn }
Dim lakes As Strin g
lakes = Join( great Lakes , ","c )
txtOu tpu t.Tex t = lakes

produces the outpu t

Huron ,Onta rio,M ichiga n,Erie ,Supe rior

Comments
1. Using a subscript greater than the upper bound of an array
is not allowed. For instan ce, at
run time the two lines of code in Fig. 7.3 prod uce an excep tion
d ialog box .

Oi m trees () As St r ing = { "Sequo ia" , "'Red•.•ood ··


, "Spruc e" }
~ st box .Te xt = t ee s {S )

.._1 lndexO utOfRa ngeE:x ception was unhand led

In dex was outside the bo unds of the array.

Trouble shootin g tips:


Make sure that the max1mum 1ndex on a list is less than the list --~
size.
Make sure the mdex 1s not a negative number .
I

l
Make sure data column names are correct.
Get general help for this exceptio~. ----­
r~
I

Search for more Help Online ...

Actions:
V1ew Detail...
Copy exception detail to the clipboard

FIGURE 7.3 Except ion dialog box.

2. The statem ents Conti nue For and Exit For can be used in
For Each loops in much the sa me
way they are used in For . . . Next loops. A lso, a vari able declar
ed inside a For Each loop has
block- level scope; that is, the var iable ca nnot be referred to
by code outside the loop.
3. After yo u doub le-click on the name of a text fi le and place
it into the text edito r, you can
alter the file's conten ts and save the altered file. To save the
altered file, right-c lick on the
fi le name in the text ed itor's tab and click on "Save bin \ Debug
\fileName."

Practice Problems 7.1

1. Give four ways to fill an array with the names of the


three mu ketee rs-A thos, Porthos,
and Aramis.
2. Write two lines of code that add the name of the fourth
muske tee r, D'Artagnan, to the
array fi lled in Proble m 1.
272 • Chapter 7 Arrays

n is clicked.
3. Dete rmine the outpu t displayed when the butto
les btnD ispla y . Click
Priva t e Sub btnD ispla y_ Click ( . . . ) Hand
Dim numW ords As Integ er
cont ains five word s."
Dim line As Strin g= "This sente nce
"c)
Dim word s() As Strin g= line .Spl it("
numWords = word s.Cou nt
txtOu tput. Text = CStr( numW ords)
End Sub

EXERCISES 7.1

100?
1. Wha t is the size of an array whose uppe r bound is
is 100?
2. Wha t is the uppe r boun d of an array whose size
displayed when the butto n is click ed.
In Exercises 3 throu gh 26, deter mine the outp ut
btnD ispla y.Cl ick
3. Priv a te Sub btnD ispla y_ Click ( ... ) Hand les
Dim n As Integ er = 2
Dim spoo ns(n) As Strin g
spo ons(O ) "soup "
spo ons( l) = "des sert"
spo ons(2 ) = "coff ee"
- 1) & " spoo n."
txt Outp ut.Te xt = "Hav e a " & spoo ns(n
End Sub
btnD ispla y.Cl ick
4. Priv a te Sub btnD ispla y_ Click ( . .. ) Hand les
'I'm look ing over a four leaf clov er.
Dim leave s(3) As Strin g
leave s(O) "sun shine "
leave s(1) 11
rain"
l e aves( 2) "the rose s that bloom in the lane"
l e aves( 3) "som ebody I adore "
Fo r i As Integ er = 0 To 3
1) & ": " & 1eav es(i) )
lstOu tput. Item s.Ad d("L eaf " & (i +
Ne xt
End Sub
les btnD ispla y.Cl ick
5. Priv ate Sub btnD ispla y_ Click ( ... ) Hand
Di m colo rs(l2 0) As Strin g
c o lors( O) = "Atom ic Tang erine "
color s(lOO ) = "Tan"
-1 Then
If color s(O) .Inde x0f(c olors (100 ))
txtO utpu t. Text = "No "
Else
txtO utpu t.Tex t "Ye s 11

End If
End Sub
btnD ispla y.Cl ick
6. Priv ate Sub btnDispla y_ Click ( ... ) Hand les
Dim year s(l) As Integ er
year s (0) 1776
year s(l) = Now. Year 'curr ent year as Integ er
7.1 C reat ing and Access ing Arrays • 273

txtOutput.Text "Age of United States: " & (years(l) - years(O))


End Sub

7. Private Sub btnDisplay_ Click( . .. ) Handles btnDisplay.Click


Dim primes() As Integer= {2, 3, 5, 7 , 11}
lst0utput . Items.Add(primes(2) + primes(3))
End Sub

8. Private Sub btnDisplay_ Click( ... ) Handles btnDisplay.Click


Dim pres() As String= {"Grant", "Lincoln", "Adams", "Kennedy"}
txtOutput.Text = pres(3) .Substring(O, 3)
End Sub

9. Dim bands() As String = {"soloist", "duet", "trio", "quartet"}

Private Sub btnDisplay_ Click( ... ) Handles btnDisplay.Click


Dim num As Integer
ReDim Preserve bands(9)
bands(4) "quintet"
bands(S) "sextet"
bands(6) InputBox ( "What do you call a group of 7 musicians?")
num = Cint ( InputBox ("How many musicians are in your group?") )
txtOutput.Text = "You have a " & bands(num- 1) &
End Sub

(Assume the first re ponse is septet and the seco nd response is 3. )


10. Private Sub btnDisplay_ Click( ... ) Handl e s btnDisplay .C lick
'Compare the values of two chess pieces
Dim chess() As String= {"king", "queen", ""}
chess(2) = "rook"
ReDim Preserve chess(6)
chess(3) = "bishop"
txtOutput . Text = "A " & chess(2) & " is worth more than a " & chess(3)
End Sub

11. Dim grades(3) As Double

Priv ate Sub frmGrades _ Load( ... ) Handles MyBase.Load


grades (0) 80
grades(l) 90
End Sub

Private Sub btnDisplay_ Click( ... ) Handl es btnDisplay.Click


Dim average As Double
grades(2) 70
grades(3) 80
average= (grades(O) + grades(l) + grades(2) + grades(3)) I 4
tx tOutput.Text = "Your average is " & average
End Sub

12. Dim names(3) As String

Priv ate Sub frmNames _ Load( ... ) Handles MyBase.Load


274 • Chapter 7 A rrays

names(O) II Alii
names (1) 11
Gore"
names(2) "Vidal"
names(3) 11
Sassoon 11
End Sub

Private Sub btnDisplay_ Click( ... ) Handles btnDisplay . Click


For i As Integer = 0 To 2
lstOutput.Ite ms.Add (names(i) & " " & names(i + 1))
Next
End Sub

13. Private Sub btnDisplay_ Click( ... ) Handles btnDisplay.C lick


Dim line As String = "2009,Million a ire ,Slumdog "
Dim films() As String= line.Split(", "c)
txtOutput.Te xt = films (2) & " " & films(l) & "won in " & films(O)
End Sub

14. Private Sub btnDisplay_ Cl ick( ... ) Handles btnDisplay.C lick


Dim line As String= " 2 ,7 , 11,13,3"
Dim nums() As String= line .Split(","c)
tx t Output.Text = CStr(Cint(num s(4)) * Cint(nums(2) ))
End Sub

15. Private Sub btnDisplay_ Click( ... ) Handles btnDisplay.C lick


Dim words() As String = {"one", "two", "three"}
txtOutput . Text = Join(words, ","c)
End Sub

16. Private Sub btnDisplay_ Click( ... ) Handles btnDisplay.C lick


Dim nums() As Integer= {1, 2, 3}
Dim temp(2) As String
For i As Integer = 0 To 2
temp(i) = CStr(nums(i))
Next
txtOutput.Te xt Join (temp, ","c)
End Sub

17. Private Sub btnDisplay_ Click( . .. ) Handles btnDisplay.C lick


Dim nums() As Integer= {3, 5, 8, 10, 21}
Dim total As Integer = 0
For Each num As Integer In nums
If (num Mod 2 = 0) Then '(num Mod 2) 0 when num is even
total += 1
End If
Next
txtOutput . Text total & " even numbers"
End Sub

18. Private Sub btnDisplay_ Click( .. . ) Handles btnDisplay.C lick


Dim words() As String= {"When", "in", "the", "course",
"of", "human", "events"}
Dim flag As Boolean = False
For Each word As String In words
7.1 C reating and Access ing A rrays • 275

If (word.L ength 5) Then


flag = True
End If
Next
If flag Then
txtOutp ut.Text •at least one five-le tter word"
Else
t x tOutput . Text "no five-le tter word"
End If
End Sub

In Exercises 19 through 2 2, assume the five lines of th e file Dates.tx t contain the
numbers
1492, 1776, 18 12, 1929, and 1941 and the fil e is in the program 's bin \Debug folder.
19. Private Sub btnDisp lay_ Click( .. . ) Handles btnDisp lay.Clic k
Dim dates() As String= IO . File.Re adAllLi nes("Da tes.txt" )
txtOutp ut . Text = "Pearl Harbor: " & dates(4 )
End Sub
20. Private Sub btnDisp lay_ Click( . .. ) Handles btnDisp lay . Click
Dim dates() As String= IO . File.Re adAllLi nes("Da tes.txt" )
txtOutp ut.Text ="Bice ntennia l Year: " & (Cint(d ates(l)) +
200)
End Sub
21. Pr i vate Sub btnDisp lay_ Click( ... ) Handles btnDisp lay.Clic k
Dim dates() As String= IO.File .ReadA llLines( "Dates. txt")
Dim flag As Boolean = False
For Each yr As String In dates
If (Cint (yr ) >= 1800) And (Cint(yr ) <= 1899) Then
flag = True
End If
Next
If flag Then
txtOutp ut.Text •contain s a 19th-ce ntury date"
Else
txtOutp ut . Text "does not contain a 19th-ce ntury date"
End If
End Sub
22. Private Sub btnDisp lay_ Click( ... ) Handles btnDisp lay.Clic k
Dim dates() As String= IO.File . ReadAll Lines("D ates . txt")
Dim total As Integer = 0
For Each y r As String In dates
If (Cint(yr ) >= 1 9 00) Then
total += 1
End If
Next
txtOutp ut.Tex t = total & " 20th-ce ntury dates"
End Sub
23. Private Sub btnDisp lay_ Click( ... ) Handles btnDisp lay.Clic k
Dim words() As String= {"We", "the", "People ", "of" , "the",
11
United" , 11
States" , "in 11 , "Order" , "to", "form",
"a" , "more", "perfec t", "Union" }
txtOutp ut.Text = BeginWi thVowel (words) & " words begin with
a vowel"
End Sub
276 • Chapte r 7 A rrays

) As Intege r
Functi on BeginW ithVow el(ByVal words( ) As String
Dim total As Intege r = 0
For Each word As String I n words
word = word.T oUppe r
Or
If word.S tartsW ith("A " ) Or word.S tartsW ith("E ")
word. Starts With( "I" ) Or word.S tartsW ith("O ") Or

word.S tartsW ith("U " ) Then


total += 1
End If
Next
Return total
End Functi on
Click
24. Privat e Sub btnDis play_ Cli c k( ... ) Handle s btnDi splay.
Dim grades () As Intege r = {85, 95, 90}
grades = Curve Grade s(grad es)
For Each grade As Intege r In grades
lstOut put.Ite ms . Add(g rade)
Next
End Sub

As Intege r()
Functi on CurveG rades(B yVa l scores () As Intege r)
For i As Intege r = 0 To scores .Coun t - 1
scores (i) = score s(i ) + 7
If scores (i) > 100 Then
scores (i) = 100
End If
Next
Return scores
End Functi on
play . Click
25. Privat e Sub btnDis play_ Click( ... ) Handle s btnDis
Dim nums() As Integ er= {2, 6, 4}
nums = Revers e(nums )
For Each num As Intege r In nums
lstOut put.Ite ms.Ad d (num)
Next
End Sub

r()
Functi on Revers e(ByV al nums() As Intege r) As Intege
Dim n = nums.C ount - 1
Dim temp(n ) As Intege r
For i As Intege r = 0 To n
temp(i ) = nums(n i)
Next
Return temp
End Functi on
Click
26. Privat e Sub btnDis play_ Click( ... ) Handle s btnDi splay.
Dim speech () As String = {"Fou r", "score ", "and",
11
Seven 11 , "years ", 11
ago" }

speech = Upper Case(s pe e ch)


txtOu tput.T ext = speec h (3)
End Sub
7.1 C reating and Access ing Arrays • 277

Function UpperCase( ByVal words() As String) As String()


Dim n As Integer = words.Coun t - 1
Dim temp(n) As String
For i As Integer = 0 To n
temp(i) = words(i) .ToUpper
Next
Return temp
End Function

27. The array declared with the statement

Dim lakes() As String= {"Huron", "Ontario", "Michigan" , "Erie" ,


"Superior" }

contains the names of the fi ve G rea t Lakes. Evaluate and interpret each of the follow ing:
(a) lakes. Max (b) lakes . Min
(c) lakes. First (d) lakes.Last
(e) lakes. Count (f) lakes (1)
(g) Array.Inde xOf(lakes, "Erie")

28. The array declared with the statement

Dim lakeAreas( ) As Integer= {23000, 8000, 22000, 10000, 32000}

contains the surface areas (in squ are miles ) of the five Grea t Lakes. Evaluate and interpret
each of the following:
(a) lakeAreas . Max (b) lakeAreas.M in
(c) lakeAreas. First (d) lakeAreas. Last
(e) lakeAreas. Count (f) lakeAreas . Sum
(g) lakeAreas . Average (h) lakeAreas ( 2)
(i) Array .IndexOf(l akeAreas, 8000)

29. The array declared with the statement

Dim statePops( ) As Double= {3.5, 6.5, 1 . 3, 1.1, 0.7, 1.3}

contains the populations (in mil lions) of the six N ew England states. Evaluate and inter-
pret each of the following:
(a) statePops.M ax (b) statePops.M in
(c) statePops. First (d) statePops. Last
(e) statePops.C ount (f) statePops (3)
(g) Array.Inde xOf(stateP ops, 1 . 1)

30. The array declared with the statement

Dim statesNE () As String = {"Connecti cut" , "Massachu setts",


"New Hampshire" , "Rhode Island", "Vermont", "Maine"}

contains the names of the six N ew England states listed in the order in which they beca me
part of the U nited States. Eva luate and interpret each of the following:
(a) statesNE .Max (b) statesNE.M in
(c)statesNE. First (d) statesNE.L ast
(e) statesNE.C ount (f) statesNE(O )
(g) Array. IndexOf (statesNE, "Maine")
278 • Chapter 7 Arrays

the o rde r in
31 . Suppose the array states has been fill ed with the names of the fifty state in
llow ing
which they beca me part of the U nited S tates. Write code to di pl ay each of the fo
states in a list box.

(a) the first state to jo in th e un ion (b) the original th irteen states
(c) the mo t rece n t state to jo in (d) the o rd er numbe r fo r O hio
(e) the second state to jo in the union (f) the twentiet h state to jo in the union
(g) th e last ten states to jo in the union
in the o rd er
32. S uppose the array JJres has bee n filled with the names of the 44 U.S. pres idents
in which they served. Write code to di play each of the fo llowing in a list box.

(a) the first pres id ent (b) the first six pres id ents
(c) the most recent pres id ent (d) the number fo r "James Monroe"
(e) the second pres ident (f) the tenth pres id ent
(g) th e last five pres idents
38,
Assume the array nums contains a list of positive integers. In Exercise s 33 through
write a Function procedur e that calculate s the stated value with a For Each loop.

33. the sum of the numbers in the array


34. th e ave rage of the numbers in the array
the Func-
35. the larges t eve n number in the array (If there are no eve n numbers in the array,
ti on procedur e hould return 0.)
36. the smallest number in the array
37. the number of two-digit numbers in the array
38. the number of even numbers in the array

In Exercises 39 through 42, identify the errors.


39. Dim nums(3) As Integer = {1 , 2, 3, 4}
40. Dim nums(lO ) As Integer
nums(nu ms.Coun t) = 7

41. Dim nums() As Integer = {1, 2, 3}


'Display 101 + 102 + 103
For Each num As Integer In nums
num += 100
Next
Message Box.Sho w(CStr(n ums . Sum))

42. Dim nums () As Integer = IO. File. ReadAll Lines ("Numbe rs. txt")
string
43. Write a single line of code that d isplays the number of words in a se ntence, where th e
variab le line ho lds the sentence.
44. Write a single line of code that d isplays the number of names in the file N ames. txt.
45. The file N umbers. txt conta ins a list of intege rs. Write a program that displays the number
of integers in the fi le and their sum.
e if
46. The fil e SomeS tates.txt contains a list of some U.S . states. Write a program to determin
th e sta tes are in a lphabetica l order.
to find
47. The file N ames2 .txt conta in a list of name in alphabetica l order. Write a program
be repeated ,
and d isp lay those entries that are repea ted in the fil e. When a name is found to

disp lay it only once.


7.1 C reating and Accessing Arrays • 279

48. S uppose the file Final. txt contains stud ent grades on a final exam. Write a program that dis-
plays the average grade on the exam and the percentage of grades that are above average.
49. The file Oigits.tx t conta ins a list of digits, all betwe n 0 and 9. Write a program that d is-
plays the frequency of each di git.
50. Wri te a Boolean-va lued Function procedure A reSa me to co mpare two intege r arrays and
determine wh ether they h ave the sa me size and hold identi cal values-that is, wh ether
a(i) = b(i) fo r a ll i.
51. Write a Function procedure to calcu late the sum of the entries with odd subscripts in an
intege r array.
52. The file S tates. txt contains the names of the 50 U.S . states. Write a program that creates an
array co nsisting of the states beginning with "New". The program also should display the
names of these states in a list box .
53. Table 7. 2 sh ows the different grades of eggs and the minimum w ight requ ired fo r each clas-
sificatio n. Write a program that proces es the tex t file Eggs.txt conta ining a list of the
we ights of a sample of egg . The program should report the number of eggs in each grade
and th e we ight of the lightest and h avies t egg in the sample. Figure 7.4 sh ows the o utput
of the program. Note: Eggs weighing I ss than 1.5 oun ces cannot be sold in supe rmarkets
and therefo re will no t be counted.

lfr1:JiftW Grades of eggs.


Grade Minimum Weight (in ounces)

Jum bo 2.5
Extra Large 2.25
Large 2
Medium 1.75
Small 1.5

57 Jumbo eggs
9 5 Ex t ra Large eggs
76 Large eggs
96 Medium eggs
77 Small eggs
Lightest egg: 1 ounces
Heaviest egg: 2.69 ounces
FIGURE 7.4 Output for Exercise 53.

54. The file USPres. txt conta ins the names of the 44 U .S. pres idents in the order in which they
erved . Write a program that places the names in an array and displays all pres idents for a
requested range of numbers. Figure 7.5 on the next page shows one poss ible outcome. (J o hn
Tyler was the tenth pres ident. James Polk was the eleventh president. And so o n.)
Exercises 55 through 58 should use the file Colors.txt that contains the names of the colors
of Crayola® crayons in alphabetical order.
55. Write a program to read the co lo rs into an array and then display th e co lors beginning with
a spec ified letter. O ne pos ible outcome is shown in Fig. 7.6 on t he next page.
56. Write a program that requ ests a colo r as input in a tex t box and then determines whether or
not the colo r is in the tex t file. The program sho uld use the Boolean-va lued Functi on proc -
dure IsCrayo la th at returns the va lue True if the color in the tex t box is a C rayo la color.
57. Redo Ex rc ise 55 with the letter passed to a Functi on procedure th at return a maller array
co nta ining just the colors beginning with the spec ifi ed letter.
280 • Chapter 7 Arrays

ll U.S. Presid ents [ = J [§] l~!t-t.J · ·J ll Crayon Colors [= I [§] ~~ . . ..1


Lower number: 10 Letter: T

Upper number: 15 Display Colors

Display Requested Presidents Tan


Teal Blue

::_j
f 10. John Ty!- -;,:- Tickle Me Pink
11 . James Polk
12. Zachary Tay!or
I Timber V\loff
TorchRed
13. Millard Fillmore Tropical Rain Forest
14. Franklin Pierce
15. James Buchanan J ITumbleweed
1 Turquoise Blue

'
FIGURE 7.5 Possible outcome of Exercise 54. FIGURE 7.6 Poss ible outcome of Exercise 55.

58. Write a program that displays the colo rs in reve rse alphabeti ca l order.
59. The file Sonnet.txt contains Shakespeare's So nnet 18. Each entry in the file conta ins a line
of the sonnet. Write a program that reports the ave rage number of words in a line and the
tota l numbe r of words in the sonnet.
60. Statisticians use the concepts of range, mea n, and stand ard dev iat ion to descri be a co llec-
tion of num erica l data. The range is the difference betwee n the largest and small est num-
bers in the collection. The mean is the ave rage of the numbers, and the standard deviation
measures the spread o r di spersal of the numbers abo ut the mean . Fo rma lly, if
x 1, Xz, X3, ... , X 11 is a co llection of num be rs, then
x 1 +x 2 +x 3 + .. . +x 11
mea n = (denote the mea n by m)
n

stand ard deviation = ~(xi


n
Write a program to calculate the range, mean, and stand ard dev iatio n for the numbers in
the file Oata.txt.
61. Write a program to d isplay the average grade and th e number of above-ave rage grades on an
exam . Each time the use r clicks a Record Grade button , a grade sho uld be read fro m a text
box. The current average grade and the number of above-ave rage grades should be dis-
played in a list box wheneve r the user clicks on a OisfJlay Average button. (Assume that the
class has at most 100 stud ents.) Use a Functio n procedure to count the number of above-
average grades. See Fig. 7. 7.

ll Analyze Grades l = I [§] ~~ .,.J ll t reque ncies l= l@] l. £4. .I

Grade: [ Record Grade I Display Frequencies


J
~ - terva- - Frecr.le:Jc _'
Display Average Grade and Number
of Above-Average Grades 0 to 9 - I
to 1 9
i- 0
The average grade is 83. . 20 to 29 7
I
l4students scored above the average -J 30 to 39 9
~ to 49 12

FIGURE 7.7 Possible outcome of Exercise 61. FIGURE 7.8 Outcome of Exercise 62.
7.2 Us ing U NQ with Arrays
• 28 1

62. The file cores. tx t conta ins scores betwee n 1 and 49. W ri te a program
that uses these scores
to c reate an array frequencies as fo llo ws:
freq uen c ies (O) = ;r of sco res< 10
freque nc ies ( 1) = *of sco res with 10 :::; sco re < 20
freq uen c ies (2 ) =#of scores with 20 :::; sco re < 30
freque n c ies(} ) = 4 of scores with 30 :::; score < 40
frequen cies ( 4) = #of scores with 40 :::; score < 50
The progra m sh o uld th en display th e results in ta bu lar fo rm, as sh o wn
in Fig. 7.8 .
In Exe rcises 63 and 64, execute the statem ent sentenc e = senten
ce. Replac e (", ", "") to
remove all comma s in sentenc e, and th en remove other punctua tion
marks similarl y. After
that, use th e space charact er as a delimit er for the Split method .
63. A se nten ce i ca lled a chain-lin k se nten ce if th e last two lette rs of each
wo rd are the arne as
the first two le tte rs of the n ex t wo rd- fo r instance , "The h ead adminis
trato r o rga nized edu -
ca ti o n o n o nl ine netwo rks. " Write a program th a t accepts a se nte nce
as input a nd de te r-
mines wh e ther it is a ch a in-link ente nce. Test the program with the
sen tence " Broadca st
stat io n , o nce ce rtified , edu cates estimab le legio ns. "
64. A word palindro me is a se nte nce th at reads the sa me, wo rd by wo
rd , backwa rd a nd fo rward
( ign o ring punctua ti o n a nd capita lizatio n) . An exa mple is "Yo u ca n
cage a swa llo w, ca n 't
yo u, but you ca n 't swa llo w a cage, ca n yo u ?" Write a program th a t req
ue ts a senten ce a nd
then determi n es whe th er the se nten ce is a wo rd pa lindrom e. Th e program
sh o ul d place the
wo rds of the sente nce in a n a rray and use a Func tio n procedu re to determi
ne whethe r th e
se nte n ce is a wo rd pa lind rome. (Test th e progra m with the sente nces "Mo
nkey see, mo nkey
do ." a nd "I a m ; therefo re, a m I?" )

Solutions to Practice Problems 7.1

1. Firsr: Dim names (2) As String


names (0) "Athos"
names( l) "Portho s"
names( 2) 11
Aramis 11

Second: Dim names( ) As String = {"Atho s" , "Porth os",


"Arami s"}
Third: Dim line As String = "Athos ,Portho s,Aram is"
Dim names( ) As String = line.S plit(", "c)
Fottrth: Assume the text fil e ames. txt has the three names in t hree lines and is located
in th e bin \OebLtg fo lder
of the program. T he n execute the fo llow ing line of co<..le :
Dim names () As String = IO . File . ReadAl lLines ("Name
s. txt")
2. ReDim Preser ve names( 3) 'resize the array
names( 3) = " D'Artag nan" 'assign value to last elemen t
3. 5

7.2 Using LINQ with Arrays


LINQ (La nguage- IN tegrated Q ue ry), a recent exc iting a nd powe rful inn
ova t ion in Vi sua l Ba ic,
pro vides a sta nd a rdized way to re trieve info rma tio n fro m da ta sources .
In this book we use LINQ
with a rrays , tex t file , XML docum ents, a nd data ba es. Befo re LINQ you
ofte n h ad to write co m-
plex loops th a t spec ified how to re tr ieve info rmatio n from a data source.
W ith LINQ you simply
282 • Chapt er 7 Arrays

lifting. Impor tant: Optio n Infer


state what you want to achiev e and le t Visual Bas ic do the heavy
at the end of this sectio n.)
must be set to "On" in order to use LINQ. (See Co mm ent 1

liNQ Queries
Video Note
ent) code that describes what you
LINQ A LIN Q query for an array is declar ative (that is, se lf-evid
want to retrieve fro m the array. A state ment of the form
[cond ition on var] Selec t var
Dim queryN ame = From var In arrayN ame Where
of e lemen ts in the array much like
is called a LINQ query. The variable var takes on th e va lu es
declares a va riab le queryN ame and
the loop ing variab le in a For Each loop. The sta temen t
that satisfy the condit ion on var.
ass igns it a equen ce consisting of the eleme nts of the array
on var] ",and " selec t var" are
The phrases " From var In arrayN ame" , "wher e [cond i tion
are ca lled query operat ors, var is
called query clauses. The keywords From, Where , and Select
data . The entire express ion to the
called a range variab le, and arrayName is called the source
right of the eq ual sign is ca lled a query expres sion.
The LINQ query above is usually writte n in th e style
Dim queryN ame = From var In arrayN ame
Where [cond it ion on var]
Selec t var
that you are declar ing a query and
As soon as you type the first line, the Code Editor will know
u at ion. H oweve r, after you type
will treat each pres of the Enter key as signaling a line contin
to tell the Code Editor that the
the last clause of t he query, you can press Ctrl + Shift + Enter
Enter key twice to compl ete entry
query declar at ion is compl ete. (Alter nately , you can press the
of the query.)

in which they
Example 1 The file States .txt contai ns the 50 U.S. states in the order
states with five-le tter names and
joined the union. The following progra m first displays the
express ion return s a sequen ce of
then displays the states beginn ing with "New" . Each query
states that is displayed with a For Each loop.
btnDi splay .Click
Priva te Sub btnDi splay_ Click ( ... ) Handl es
nes( "Stat es.tx t" )
Dim state s() As Strin g = IO. File .Read AllLi
Dim stateQ ueryl = From state In state s
Where state. Leng th = 5
Selec t state
For Each state As Strin g In stateQ ueryl
lstSta tes.It ems.A dd(st ate)
Next
lstSta tes.It ems.A dd( "" )
Dim stateQ uery2 = From state In state s
Where state . Starts Wi th ( "New" )
Selec t state
For Each state As Strin g I n stateQ uery2
lstSta tes.It ems.A dd(st ate)
Next
End Sub
7.2 Us ing LI NQ with A rrays • 283

[Run, and cl ick on the button.]

a-;} U.S. Sta1es l = I @] 1-.a d

[ Display States )
Maine
Texas
Idaho

New Jersey
New Hampshire
New York
New Mexico
'---- --

The array methods Count, Max, Min, First, and Last apply to all sequences returned by LINQ
queries, and the array methods Ave rage and Sum apply to nu meric sequences. A lso, the successive
elements in the sequence can be referred to by indices ranging from 0 to queryName.Co unt - 1.
For instance, in Examp le 1, the values of stateQuery1 (O) , stateQuery1 (1) , and
stateQuery1 (2 ) are Maine, Texas, and Idaho.

Example 2 The foll owing program d isplays values associated with numeri c sequences
returned by LINQ queries. Note: The intege r n is eve n if n Mod 2 is 0.

Private Sub btnDisplay_ Click( ... ) Handles btnDisplay.C lick


Dim nums() As Integer = {5, 12, 8, 7, 11}
Dim numQuery1 = From num In nums
Where num > 7
Select num
For Each num As Integer In numQuery1
lstBox . Items . Add(num)
Next
lstBox.Items. Add( 11 Largest number: 11 & numQuery1.Ma x)
lstBox.Items . Add( 11 Second number: 11 & numQuery1(1) )
lstBox.Items . Add( 11 Sum of numbers: 11 & numQuery1.Sum )
lstBox . Items . Add( 1111 )
Dim numQuery2 = From num In nums
Where num Mod 2 = 0
Select num
lstBox.Items . Add( 11 Number of even numbers: 11 & numQuery2.Co unt)
1stBox.Items .Add( 11 Average of even numbers: 11 & numQuery2.Av erage)
1stBox . Items.Add( 11 Last even number: 11 & numQuery2.La st)
End Sub
284 • Chapter 7 Arrays

[Run, and click on the button.]

D umbers l = I @J 1-- ~
[ Display Numbers
1
12
s
11
Largest number: 12
Second number: S
Sum of numbers : 31

Number of even numbers : 2


Average of even numbers : 1
Last even number: 3
'---- ---

T h e va ri able in the Se lect clause can be replaced by an express ion involving the variab le.
For instance, if the clause Select nwn in numQuery 1 of Example 2 were replaced by
Select nwn * nwn

th en the first three lines in the list box would be 144, 64, and 121. A lso, bo th Where clause
and Select clauses are optional. W hen th e Where clause is miss ing, all va lues in the source data
are includ ed. A miss ing Select clause produces the same effect as th e clause Select var. In this
textbook we always include a Select clause.

The Distinct Operator


The sequence crea ted with a LIN Q q uery might co nta in duplicate elements. Duplicates ca n be
eli minated by adding the Distinct operator to the query. For instance, using the array
teamNames from Example 5 of the prev io us section , the lines of code
Dim teamQuer y = From team In teamName s
Select team
Distinct
For Each team As String In teamQuer y
lstGamesW on.Items. Add(team )
Next

disp lay the name of the teams that have won a S uper Bowl, with each team listed once .

The ToArray Method


The sequence returned by a LINQ q uery has many of the features of an array. Its ma in limita-
tion is that its va lues cannot be altered with ass ignment statement s. H oweve r, the sequence can
be con ve rted to an array with the ToArray method. For instance, using the array team N ames
from Example 5 of the prev ious secti on , the lines of code
Dim teamQuer y = From team In teamName s
Select team
Distinct
Dim uniqueWi nners() As String = teamQuer y.ToArray

create the array named uniqueWinners containin g the names of the teams th at have won the
S upe r Bowl, with each team appearing just once as an element of the array.
7.2 Using UNQ with Arrays • 285

Use of Function Procedures in Queries


The Where and elect clau e of a LINQ query can use Function procedu re , a illustrated in
the next exa mp le.

Example 3 The file US Pres. txt conta ins the names of the 44 U. . presidents. The first
two lines of the fi le are George Washington and John Adams. The follow ing program asks the
user to enter a first name and then displays the names of all the pres idents hav ing that first name:

Dim presidents() As String = IO. File .ReadAllLines( "USPres.txt" )

Private Sub btnDisplay_ Click( ... ) Handles btnDisplay.Click


Dim presQuery = From pres In presidents
Where FirstName(pres) = txtFirstName . Text
Select IncludeTitle(pres)
lstPres .Items.Cl ear ()
For Each pres In presQuery
lstPres .Ite ms .Add (pres)
Next
End Sub

Function FirstName( ByVal name As String ) As String


'Extract the first name from a full name .
Dim parsedName() As String = name.Split( " "c )
Return parsedName.First
End Function

Function IncludeTitle (ByVal pres As String ) As String


Return "President " & pres
End Function

[Run, enter a first name, and click on the button.]

c... oSo I side ts l =J @J 1-~ J

Rrst name: James

I Display Presidents }
·-
~;resident James Madison
President James Monroe
President James Polk
President James Buchanan
President James Garfield
President James Carter

The let Operator


The Let operator, which give a name to an express ion, makes querie eas ier to read. For
in tance , the query in Examp le 3 ca n be wri tten as
Dim presQuery = From pres In presidents
Where FirstName(pres) = txtFirstName.Text
Let formalName = IncludeTitle(pres)
Select formalName
Let operato rs a l o can significantly improve the readability of queri es.
286 • Chapter 7 Arrays

The Order By Operator


A n array or query result is said to be ordered if its va lues are in either a cend ing or desce nd ing
ord er. W ith ascend ing order, the va lue of each element is less than or equal to the va lue of the
next element. That is,
[each element] s [next elemen t].

For string va lues, the A NS I table is used to evaluate the "less than or eq ual to" cond ition .
Putt ing eleme nts in alphabe tical or numeric order (either ascend ing or de cending) is
referred to as sorting. There are many algorith ms for so rting arrays. The mos t efficient ones use
complex nested loops and are tricky to program. Howeve r, LINQ prov ides the O rder By query
operato r that spa res us fro m hav ing to code co mplicated sort ing algori thms. T he simplest form
of an O rder By clause is

Order By [expre s sion] Direct i o n

where Direction is one of the keywords Asce nding or Descend ing, and the exp ress ion invo lves
range and/or Let va riables.

Example 4 The following program sorts an array of numbers in ascend ing order. Note: If
the word Ascending is replaced by Descend ing, the array will be so rted in descend ing order.

Private Sub btnSort_ Click( .. . ) Handles btn Sort.Click


Dim nums () As Integer = {3 , 6, 4 , 1}
Dim n umQuery = From num In n ums
Order By n um Ascending
Select num
For Each n As Integer In n umQuery
l stOutput . Items.Add (n)
Next
End Sub

[Run , and click on the button.]

a::: So ing With UNQ l = I @] I. -"'2. .I

Sort Numbers

[]
The O rder By operator is quite flex ible and can order arrays in ways other than just alpha-
betical or numeric ord er. Second ary criteria for orde ring can be specified by listing two or more
criteria sepa rated by commas. In general, an O rder By clause of the form
Orde r By expressi onl Direct i on l , expression 2 Direc tion 2, . ..

primarily sorts by expres ionl and Direction! , secondarily by express ion 2 and Direction 2, and
so on. For ins tance, an O rde r By clause such as
Order By l as t Name Ascending , f irstName Ascending
7.2 Using LINQ with Arrays • 287

can be used to alph abetize a seq uence of full na mes. When two peop le have the same last name,
their first n ames will be used to determine wh ose full name comes first .

Example 5 The fo llo wing program uses the file S tates. txt considered in Example 1 and
sorts th e states by th e length of the ir na mes in ascending ord er. S tates with names of the same
length are sorted by the ir names in reve rse alphabe tical order.

Private Sub btnDisplay_ Click( . . . ) Handles btnDisplay.Click


Dim states() As String = IO. File .ReadAl lLines( "States.txt" )
Dim stateQuery = From state In states
Order By state.Length Ascending , state Descending
Select state
For Each state As String In stateQuery
lstStates.Items.Add(state)
Next
End Sub

[Ru n, and click on th e button.]

Dj So ing with UNQ l = l @l ~ __d

( Oisplcrt States )
Utah i-

Ohio
Iowa
Texas ~
Maine
Idaho
Oregon
Nevada
Kansas
Hawaii
Alaska
Wroming ~

Note: In an O rder By clause, the default direction is A scending. For instance, the fo urth line of
Example 5 co uld h ave been written

Order By state.Length, state Descending

The DataSource Property


In Examp le 5, a Fo r Each loop was used to place the va lues returned by the qu ery in to a list box.
T h e task also can be accomp lished with a DataSo urce prope rty. To use the DataSo urce prop-
erty, rep lace the For Each loop with th e fo llow ing pa ir of sta temen ts. Note: The second state-
ment is op ti ona l. It prevents having th e first item in th e list box selected at startup.
lstStates.DataSource = stateQuery.ToList
lstStates.Selecteditem = Nothing
288 • Chapter 7 Arrays

directly in to a
T he DataSo urce prop rty also can be used to di play the con tents of an array
list box wi th a stateme nt of the form
lstBox. DataSo urce = arrayNa me
a list box, then
Note: If a Se lectedln dexCha nged eve nt proced ure has been defined for
eve nt.
executi on of the DataSo urce property will rr~ise the Se lec tedlnd exChan ged

Binary Search
search. The Binary-
A large array in asce nding ord er i most ffic iently searched with a binary
of the array it lies.
Search method looks for a va lue in the array by first determi ning in wh ich half
half. The process is
The other half is then ignored , and the search is narrowe d to the retained
nt of the fo rm
repeated until the item is found or the entire list has been considered. A stateme
numVar = Array .Binary Search (arrayN ame, value)
me. If the va lue
assigns to numVar the index of an occurre nce of the requested value in arrayNa
is not found , then a nega ti ve num be r is ass igned to numVar.

Comments
Visual Bas ic pro-
1. The Option Infer setting can be made the default se tting for all of your
grams or ca n be made the se tting for a single program .

hown in
(a) If a value for Option Infer is set in the Option defa ult proj ect setting window
programs .
Fig. 3.1 of Section 3.2, th en th at sett ing wi ll be the default setting for all new
nt Option
(b) To override the default se tting for an ind ividual program, enter the stateme
Window . A lternate ly, right-
Infer on or Option Infe r Off at the top of the Code
rties , click on
click on the program name at th e top of Solutio n Explore r, click on Prope
the Comp ile tab, and change the va lue for "Option infer".
sa id to project data.
2. UNQ Where ope rators are sa id to filter data, and Se lect ope rato rs are
form
3. Visual Basic h a a built-in rout ine for so rting arrays. A stateme nt of the
Array .Sort( arrayName)
where the more
sorts the array in ascendi ng orde r. This method is usefu l for simple orting
advanced capa biliti es of LINQ are not needed.

Practice Problems 7.2


s in th e file
1. Write a program that uses a LINQ query to calculat e the sum of the number
Number s. txt.
The followin g pro-
2. The file USPres. txt contain s the fu ll n ames of the 44 U.S. presiden ts.
name is "Eisenh ower." S ince there is
gram finds the fu ll name of the presiden t whose last
to display the output.
only one such pre ident, a text box (rather than a list box ) is sufficien t
Private Sub btnFin d_Clic k( ... ) Handle s btnFin d.Click
)
Dim presid ents() As Str ing= IO.File .ReadA llLines ("USPr es.txt"
Dim query = From pres In presid ents
Where pres.E ndsWit h("Eise nhower ")
Select pre s
txtFull Name.T ext = query. First
End Sub
7.2 Using UNQ with Arrays • 289

(a) Since the value of query consists of just one name, wh y ca n't the six th
line be replaced
with txtFull Name. Text = query ?
(b) W hat ex pression s, other than query. First , ca n be used for the righ t side
of the sixth
li ne that would yield th e same result ?

EXERCISES 7.2

In Exercises 1 through 18, determi ne the output displayed when the button
is clicked.
1. Private Sub btnDis play_ Click( . . . ) Handle s btnDis play . Click
Di m nums() As In t eger = {5 , 7, 2, 3}
Dim numQue ry = From num In nums
Where num > 4
Select num
For Each num As Intege r In numQue ry
lstOutp ut.Item s.Add( num)
Next
End Sub

2. Privat e Sub btnD i splay _ Click( .. . ) Handle s btnDis play.C


lick
Dim words( ) As String = {"Hous ton", "we", "have" , "a",
"proble m"}
Dim wordQu ery = From word In words
Where word . ToUppe r. StartsW ith ( "H " )
Select word
For Each word As String In wordQu ery
lstOutp ut.Item s . Add(wo rd)
Nex t
End Sub

3. Privat e Sub btnDis play _ Click( ... ) Handle s btnDis play.C


lick
Dim line As String = "I ' m going to make him an offer
he can ' t refuse"
Dim words( ) As String = line . Split(" "c)
Dim wordQu ery = From word In words
Where word.L ength = 5
Select word
l stOutp ut.Data Source = wordQu ery . ToList
lstOut put.Se lectedi tem = Nothin g
End Sub

4. Priv ate Sub btnDis play _ Click( ... ) Handle s btnDis play. Click
Dim line As String = " 1 492,17 76,181 2,1929 ,1941"
Dim dates() As String = line.S plit(", "c)
Dim dateQu ery = From yr In dates
Where Cint(y r) < 1800
Select yr
lstOutp ut.Data Source = dateQu ery.To List
lstOutp ut.Sele ctedite m = Nothin g
End Sub

5. Priv ate Sub btnDis play _ Click( . . . ) Handle s btnDis play.C lick
Dim line As String = "If,yo u,fail, to,plan ,then,y ou ,
plan,to , fail"
Di m words( ) As Str i ng= line .Split( " , "c )
290 • Chapt er 7 A rrays

Dim wordQ uery From word In words


Selec t word
Disti nct
txtOu tput.T ext = CStr(w ordQu ery.Co unt)
End Sub
.Click
6. Priva te Sub btnDi splay_ Cli c k( ... ) Handl es btnDi splay
Dim nums( ) As Integ er = { 2, 3, 4, 3, 2}
Dim numQu ery = From num In nums
Selec t num
Disti nct
txtOu tput.T ext = CStr(n umQu ery.Su m)
End Sub
btnDi splay .Click
7. Priva te Sub btnDi splay_ Click ( ... ) Handl es
Dim nums( ) As Integ er= {2, 3, 4, 3, 2}
Dim numQu ery = From num In nums
Selec t num + 100
Dist inct
txtOu tput.T ext = CStr(n umQu ery.Av erage)
End Sub
.Click
8. Priva te Sub btnDi splay_ Click ( ... ) Handl es btnDi splay
r", "kaya k", "civic s"}
Dim words () As Strin g= {"ra cecar ", "moto
Dim wordQ uery = From wo r d In words
Where I s Palind rome( word)
Selec t word.T oUppe r
For Each word As Strin g In wordQ uery
lstOu tput.I tems. Add(w ord)
Next
End Sub

) As Boole an
Funct ion IsPali ndrom e(ByV al word As String
reads the same forwa rds and backw ards.
'A palind rome is a word that
Dim n As Integ er word. Lengt h
For i As Integ er 0 To (n - 1) \ 2
tring( i, 1) <> word. Subst ring(n i - l, 1) Then
If word .Subs
Retur n False
End If
Next
Retur n True
End Funct ion
.Click
9. Priva te Sub btnDi splay_ Cl ick( ... ) Handl es btnDi splay
in the numbe rs 2, 6, 7, and 8.
'The first four lines of Numb ers.tx t conta
("Num bers.t xt")
Dim numbe rs() as Strin g= IO.Fi le.Re adAll Lines
Dim query = From num In numbe rs
Selec t Cin t (num)
ls tOutp ut.Ite ms.Ad d(que ry(O) + query (l))
End Sub
btnDi splay .Click
10. Priva te Sub btnDi splay_ click ( ... ) Handl es
'The f irst four lines of Word s.txt conta in scale , top, up, and low.
s("W ords.t xt")
Dim words () As Strin g= IO.Fi le.Rea dAl lLine
7.2 Us ing LIN Q with A rrays • 29 1

Dim query From word In words


Select word
txtOutput. Text = query(2) & query(O)
End Sub
11. Private Sub btnDisplay_ Click( ... ) Handles btnDisplay .Click
Dim grades() As Integer = {66, 68, 72, 76, 90, 92, 93, 94, 95}
Dim query = From grade In grades
Let newGrade = CurveGrade (grade)
Where newGrade 100
Select newGrade
txtOutput. Text = query.Coun t & " students have a grade of 100"
End Sub

Function CurveGrade (ByVal grade As Integer) As Integer


grade += 7
If grade > 100 Then
grade = 100
End If
Return grade
End Function

12. Private Sub btnDisplay_ Click( . . . ) Handles btnDisplay .Click


Dim words() As String= {"rated", "savory", "abl e", "just"}
Dim query = From word In words
Let opposite = ("un" & word) .ToUpper
Select opposite
txtOutput. Text = query.Max
End Sub

13. Private Sub btnDisplay_ Click( ... ) Handle s btnDisplay .Click


Dim nums() As Integer= {12, 5, 7, 10, 3, 15, 4}
Dim query = From num In nums
Where num > 10
Order By num Descending
Select num
lstOutput.D ataSource = query.ToL ist
lstOutput. Selectedit em = Nothing
End Sub

14. Private Sub btnDisplay_ Click( ... ) Handles btnDisplay .Click


Dim words() As String= {"When " , "in" , "the", "course",
11
0f 11 , "hUinan 11 , "events 11 }
Dim query From word In words
Order By word.Lengt h
Select word.Lengt h
Dim greatestLe ngth As Integer = query.Last
Dim query2 = From word In words
Where word.Lengt h = greatestLe ngth
Order By word Descending
Select word
lstOutput.D ataSource = query2.ToL ist
lstOutput. Selectedit em = Not h ing
End Sub
292 • Chapter 7 A rrays

15. Private Sub btnDispl ay_ Click( . . . ) Handles btnDispl ay .Cl ick
Dim grades() As Integer = {60, 70, 90, 80}
Dim query = From grade In grades
Order By grade Descendi ng
Select grade
grades = query . ToArray
ReDim Preserve grades(g rades.Co unt- 2) 'drop lowest grade
Dim str As String = "The average after dropping the lowest grade is "
txtOutpu t.Text = str & grades.A verage
End Sub
16. Private Sub btnDispl ay_ Click( ... ) Handles btnDispl ay.Click
Dim golfers(2 ) As String 'top 3 golfers in tourname nt
golfers(O ) "Funk,65 ,69,69,75 " 'total 278
golfers( l) "Ramaro, 67,69,65, 73" 'total 274
golfers(2 ) "McNulty ,68,70,73 ,68" 'total 279
Dim query = From golfer In golfers
Let data golfer.S plit(","c )
Let name data(O)
Let score= Cint(data (1)) + Cint(dat a(2)) +
Cint(data (3)) + Cint(dat a(4))
Let result = score & " " & name
Order By score Ascendin g
Select result
For Each result As String In query
lstOutpu t.Items.A dd(result )
Next
End Sub
17. Private Sub btnDispl ay_ Click( ... ) Handles btnDispl ay.Click
Dim smallPrim es() As Integer= {2, 3, 5, 7, 11, 13, 17, 19, 23,
29, 31, 37, 41, 43, 47, 53, 59,
61, 67, 71, 73, 79, 83, 89, 97}
Dim n As Integer= Cint( I nputBox( "Enter a number less than 100:"))
If Array.Bi narySear ch(smallP rimes, n) < 0 Then
txtOutpu t.Text = n & " is not a prime number"
Else
txtOutpu t. Text n & " is a prime number"
End If
End Sub
(Assume the response is 37. )
18. Private Sub btnDispl ay_ Click( ... ) Handles btnDispl ay.Click
Dim statesNE () As String = {"Conne cticut•, "Maine•, "Massach usetts",
"New Hampshir e", "Rhode Island", "Vermont "}
Dim state As String= InputBox ("Enter a state:")
If Array.Bi narySear ch(states NE, state) < 0 Then
txtOutpu t.Text =state & " is not in New England ."
Else
txtOutpu t.Text state & " is in New England. "
End I f
End Sub
(Assume the response is New York.)
7.2 Using UNQ with Arrays • 293

Use LINQ to carry out the primary tasks of the programs in the remaining exercises of this
section. In Exercises 19 through 24, redo the exercises from Section 7.1 using LINQ queries.
19. Exercise 17 of Section 7. 1 20. Exercise 18 o f Sectio n 7. 1
21. Exercise 21 of Section 7.1 22. Exercise 22 of Section 7.1
23. Exercise 25 of Section 7. 1 24. Exe rci e 26 of Sectio n 7. 1
In Exercises 25 through 28, use the file SBWinners.tx t that lists the winners of the first 44
Super Bowls.
25. Write a program that disp lays the teams ( in alphabetical ord er) who have won a S uper
Bowl. Each team sh ould appear only once.
26. Write a program that displays the teams (in alphabetical o rder) who h ave won a S uper
Bowl and whose name beg in with the letter B. Each tea m should appear only once.
27. Write a program that disp lays in a text box the num.ber of games won by the team specified .
See Fig. 7.9.

Displcrt Super Bowll/1/inners


by Nurnber of lNins

ll _. S per Bowl l = I @I I~. _r


~- " J

Narne of football tearn : 9ers 1~1


I Detennine Number of Super Bowls learn 1/llon j 3
3
Patriots
Raiders
3 Redskins
Number of Super Bowls lo\lon :
2 Broncos

FIGURE 7.9 Possible outcome of Exercise 27. FIGURE 7.10 Outcome of Exercise 28.

28. Write a program that disp lay a list of S uper Bowl winners ordered by the number of games
won. See Fig. 7.10.
29. The file Final. txt contains student grades on a fina l exa m. Write a program using LINQ
that disp lays the ave rage grade on the exam and the percentage of grade that are above
average.
30. Write a program that requests fiv e grades as input and then calculates the average after
dropping the two lowest grades.
31. The fi le States.txt conta ins the 50 U.S. states in the order in which they jo ined the un ion.
Write a program to d isp lay the o rigina l 13 states in alphabetical o rd er.
32. An anagram of a word or phrase is another word or phra e that uses the same lette rs with
the same frequency. Punctuation marks, case , and spaces are ignored. W rite a program that
request two words (no punctuation) as input and dete rmines if they are anagrams of each
other. (Test the program with the wo rds Elvis and lives.)
33. The file USPres.txt conta ins the names of the 44 presidents in the o rd er in which they
se rved. The first two lin es conta in the names George W ashington and John Adams. Wr ite
a program that displays the president ordered by their last name.
294 • Chapter 7 Arrays

34. The fi le Words. txt conta ins a list of words. Wr ite a program that d isplays the wo rds in a list
box so rted by the number of diffe rent vowels (A, E, I, 0 and U) in the wo rd. When two
words have the sa me number of different vowe ls, they sho uld be ordered first by the ir
length (desce nding) and then alphabetica lly. The display sho uld show bo th the wo rd and
the number of different vowe ls in the word . See Fig. 7 .11.

a ... Co nting Vowels l =I@] 1~ ,.-~J a ... Unrted N atio ns l = I @] I~ .,J

( Display Words
I Ma
-
5
--
caulitlower ;.
~dagascar
alawi
5 diSCOIJrage
Malaysia
5 facetious := Maldives
5 dialogue
5 sequoia
- Mali
Ma~a
4 organized
Marshall Islands
4 courage
Mauritania
3 important
Mauritius
3 pulverize
3 educat e
....

FIGURE 7.11 Output of Exercise 34. FIGURE 7.12 Output of Exercise 35 .

35. The file N ations.txt contains the names of the 192 member nations of the Un ited N at ions.
Wr ite a program that initia lly d isplays all the nat ions in a list box. Each time a letter is
VideoN ote typed into a text box , the program should reduce the displayed nations to those beginning
President> with the letters in the text box. Figure 7.12 shows the status after the letters "Ma" are typed
( Homework) into the tex t box. At any time, the use r sho uld be able to cl ick on the name of a nation to
have it appea r in the tex t box.
36. The median of an o rdered set of measuremen ts is a number separating the lower h alf from
the upper ha lf. If the n umber of measuremen ts is odd, the median is the m idd le measure-
ment. If the number of measuremen ts is eve n , the medi an is the ave rage of the two m iddle
measuremen ts. W rite a program that requ ests a number n and a et of n measuremen ts as
input and then displays the median of the measuremen ts.

Solutions to Practice Problems 7.2

1. Private Sub btnDisplay_ Click( ... ) Handles btnDisplay . Click


Dim numbers() As String = IO. File . ReadAllLin es ("Numbers. txt")
Dim query = From num In numbers
Select CDbl(num)
MessageBo x.Show(CS tr(query.Su m), "Total")
End Sub

2. (a) A text box can be filled onl y with a string. The va lue returned by a qu ery is a seqLLence type th at conta ins one
string clemen t. O nly that element, not the seq uence itself ca n be assigned to the text prope rty of the text box.
(b) query(O) , query.Last , query.Max , query.Min

7.3 Arrays of Structures

Often we work with s v ral piece of re lated data. For in tance, four re lated piece of data abo ut
a country are name, continent, pofndation, and area. Suppose we are considering this information
fo r th e 192 countries in the United Nat ion . In the ea rly days of programm ing, the way to work
7.3 Arrays of Structu res • 295

with such info rm ation was to put it into four para llel arrays-o ne array of type S t ring fo r names,
a second array of type S tr ing for contin ents, a th ird array of type Do uble fo r populat ions, and a
fo urth array of type Double fo r areas. The modern way of dea ling with such info rmation is to
place it in to a single array of a co mpos ite data ty pe that you define called a structure o r a use r~
defined data type .

Structures
A structure contains variab les of (pos ibly) d ifferent type , wh ich are known as members. A
stru cture is defined in the Declaratio ns section of th e Code Editor by a block of the form

Structur e Structure Name


Dim memberNa me l As MemberTy pe1
Dim memberNa me2 As MemberTy pe2

End Structur e

where StructureName is the name of the u se r~d efi ned data type, memberNa mel and
memberName2 are the names of the members of the u se r~d efined type, and MemberT)'/Je l and
MemberTyfJe2 are the correspon ding member data types.
Some examples of structures are

Structur e Nation
Dim name As String
Dim contine nt As String
Dim populatio n As Double 'in millions
Dim area As Double 'in square miles
End Structur e

Structur e Employee
Dim name As String
Dim dateHir ed As Date
Dim hourlyWa ge As Double
End Structur e

Structur e College
Dim name As String
Dim s t ate As String 'state abbrevia tion
Dim yearFoun ded As Integer
End Structur e

Variables hav ing a u se r~ d efined data type are declared with Dim statements just like o rdi ~
nary va riab les. For in tance, the statement

Dim country As Nation

decla res a va riable of data type N at ion.


Dot no tation is used to refer to an ind ividu al member of a u se r~ d e fined variable. Fo r
instance, the set of statements

country. name = "China"


count r y . continen t = "Asia"
c ountry.p opulation = 1 3 32 .5
country . a r ea = 3696100
296 • C hapter 7 Arrays

above. After these ass ign ment


assigns va lues to the membe rs of the va riab le country decla red
statem ents are execut ed, the statem ent

txtOut put.Te x t = countr y.c ontine nt

will display the string "As ia" in a text box, and the sta tement

n I countr y . area)
txtOut put . Text = CStr(lO OOOOO * countr y.pop ulatio

wi ll disp lay the popu lat ion de n ity of C hina in a text box.
n of t h e Code Ed itor,
Althou gh structu res are a lways defin ed in th e Declarations sectio
m. Just li ke o rd inary vari-
va ri ab les of use r-defin ed type ca n be decla red an yw h ere in a progra
depend ing o n where t hey are
ab les, they have class- leve l, loca l, o r block- leve l scope
declare d.

to the mem-
Example 1 The fo llow ing program uses the Split method to assign va lues
play a vital ro le when va lu es
bers of a va ri abl e hav ing a user-de fin ed type. This tec hnique will
the pop ulat io n membe r of the
are ass igned fro m text files to an array of stru ctures. Note: S ince
be mult iplied by o ne million
stru cture Nation is give n in terms of m illio ns, the va lue has to
when used in a calcula t ion .

Struct ure Nation


Dim name As String
Dim contin ent As String
Dim popul ation As Double 'in millio ns
Dim area As Double 'in square miles
End Struct ure

Dim countr y As Nation 'class -level variab le

.Load
Privat e Sub frmCo untry_ Load( ... ) Handle s MyBase
'Assig n values to count ry's membe r variab les
Dim line As String = "Chi na,Asi a,l332 .5,369 6100"
Dim data() As String = line.S plit( ","c )
countr y . name = data(O )
count ry.con tinent = data(l )
countr y.pop ulatio n = CDbl (data( 2))
countr y .area = CDbl (data( 3 ) )
End Sub

splay. Click
Privat e Sub btnDis play_ Click( ... ) Handle s btnDi
'Displ ay data in text boxes
txtNam e . Text = countr y . name
txtCon tinent .Text = count ry.con tinent
ulatio n, 0)
txtPop . Text = FormatN umber(l OOOOO O * countr y.pop
" square miles"
txtAre a.Text = Forma tNumb er(cou ntry.ar ea, 0) &
y.area ) &
t x tDens ity.Te xt FormatN umber(l OOOOO O * countr y.popu lation I countr
" people per square mile"
End Sub
7.3 Arrays of Structures
• 297

[R un , and click on th e butto n .]

a_. Co ntry Data

Display Data

Name of country : China

Continent : Asia

Population : 1.332.

Area: 3. 6-96.1 square miles

Density: 360.52 people per square mile

Arrays of Structures
S ince a struct ure is a data type, an array ca n be decla
red with a struct ure as its data type. Fo r
instan ce, the statem ent
Dim natio ns(19 1 ) As Natio n

declares nations to be an array of 192 eleme nts, where


each eleme nt has data type N ation. Fo r
each index i, nations (i) wi ll be a variab le of type N ation,
and the va lues of its memb ers will be
nations (i) .nam e, nations(i) .continent, nations(i) .jJo pulatio
n, and nations(i) .area. Fillin g t h is 192-
e lemen t array req uires 4 X 192 = 768 pieces of data.
This amou nt of data is bes t upp lied by a
text file. T he optim um des ign for thi s tex t file is to have
192 lines of text, each consis ting of 4
pieces of data delim ited by comm as. The n ex t exa
mp le uses the file UN .txt that gives data
abo ut th e 192 memb ers of the Unite d N ations with
the countri es listed in a lphab et ica l order.
So me li nes of the file are
Cana da,No rth Amer ica,3 2. 9,385 5000
Franc e,Eur ope,6 3 . 5,211 209
New Zeala nd,A ustra lia / Ocea nia,4 . 18,10 3738
Nige ria,A frica ,146. 5,3 5 6669
Pakis tan,A sia,l6 4,310 403
Pe ru , South Amer ica,27 .9,49 6226

Each line of this tex t fil e is called a recor d and each


reco rd is aid to co ntain four fields-a
name field , a cont inent field , a popul ati on fi eld, and
an area fie ld. The tex t fi le is sa id to use a
C SV fo rmat. (CSV stand s fo r "Com ma Separated Value
s. ")

Example 2 The fo llowin g progra m uses the text file UN. txt to fill
an array of st ru ctures
and then uses the array to d isplay the name s of the
count ries in the con ti nen t selec ted by the
use r. T he program uses two list boxes . A ssume the S
tring C o llectio n Ed ito r for lstC o ntin ents
has been filled at des ign t ime with the names of the
seven con t inen ts. The count ries in the
select ed conti nent are el i played in lstCo untrie s.

Struc ture Natio n


Dim name As Strin g
Dim conti nent As Strin g
298 • C hapte r 7 Arrays

Dim popu latio n As Doub le 'in mill ions


Dim area As Doub le 'in squa re mile s
End Stru cture

Dim natio ns(l9 l) As Natio n

les MyBa se .Load


Priv ate Sub frmC ountr y_ Load ( ... ) Hand
the array natJ. ons .
'Plac e the cont ents of UN t. t into
Dim line As Strin g
Dim data () As Strin g
Dim coun tries () As Strin g IO. File .Rea dAll Line s( "UN. txt" )
For i As Integ er = 0 To 191
line = coun tries (i)
data = line .Spl it( " , "c )
natio ns(i) .name = data( O)
natio ns(i) .con t inen t = data (l)
natio ns(i) .pop ulati on= CDbl (data (2))
natio ns(i) . area = CDbl (data (3))
Next
End Sub

dexC hang ed( ... ) Hand les _


Priv ate Sub lstCo ntine nts_ Selec tedin
lstCo ntine nts.S elect edin dexC hang ed
ntine nts.T ext
Dim selec tedC ontin ent As Strin g = lstCo
lstCo untri es . Item s.Cle ar ()
Then
If selec tedC ontin ent = "Ant arcti ca"
ox .Show ( "The re are no coun tries in Anta rctic a." )
Mess ageB
Else
For i As Integ er = 0 To 191
ontin ent Then
If natio ns(i) .con tinen t = selec tedC
)
lstCo untri es.It ems . Add( natio ns(i) .name
End If
Next
End If
End Sub

[Run , and cl ick on the name of a conti nent. ]

l=l@) l~ ·J
a .. Display Cou nt ries by Conti nent
-- -- - ;.
Oick on the name Albania
of a continent : Jl.ndorra ~
I
AJ..Jstria
Africa Belarus
Jl.ntarctica Belgium
Asia Bosnia and Herzegovina
AJ..Jstra lia/ Oceania Bulgari a
0 I- Croatia
North America Czech Repub lic ~

South America Denmark

the same way they are used with o rd i-


Quer ies can be used with array of tructu re in much
nary array .
7.3 Arrays of tructures • 299

Example 3 In the fo llowing va riation of Examp le 2, the co untri es are d isplayed in


descend ing order by their areas. LINQ is used both to filter the countries and to so rt them by
area. The qu ery returns a sequence of names of countries.
Structure Nation
Dim name As String
Dim continent As String
Dim population As Double 'in mill~ons
Dim area As Double 'in square miles
End Structure
Dim nations(l91) As Nation
Private Sub frmCountry_ Load( ... ) Handles MyBase .Load
Dim line As String
Dim data() As String
Dim countries() As String IO. File .ReadAllLine s( "UN.txt" )
For i As Integer = 0 To 191
line= countries(i)
data= line.Split ( ","c )
nations(i) .name= data(O)
nations(i) .continent = data(l)
nations(i) .population= CDbl (data(2))
n ations(i) .area= CDbl (data(3))
Next
End Sub
Private Sub lstContinent s_ Selectedindex Changed( ... ) Handles
lstContinents .Selectedinde xChanged
Dim selectedCont inent As String = lstContinent s . Text
Dim query = From country In nations
Where country.cont inent = selectedCont inent
Order By country.area Descending
Select country.name
lstCountries . Items.Clear()
If selec t edContinen t = "Antarctica" Then
MessageBox . Show( "There are no countries in Antarctica." )
Else
For Each countryName In query
lstCountries.I tems.Add(cou ntryName)
Next
End If
End Sub

[Run, and click on the name of a continent.]

O ick on the name O;ina


of a continent : India
Kazakhstan
rica I
Antarctica~ ~
Saudi Arcibia
Indonesia
Asia Iran
hlstralia/ Oceania Mongolia
Europe Pakistan
North America I Turkey
SouthAm~ Myanmar
300 • C hapter 7 A rrays

So fa r, LINQ Select cl auses h ave conta ined a single ite m. H owe ver, Select cla u es can con -
ta in mu lt iple items. ln th at case t he q uery re turns a seq ue nce of st ruc tu res.
Th e nex t exa mp le uses t he file Co lleges. tx t th at conta ins da ta (na me , sta te, and yea r
fo unded) about co lleges founded before 1800. The first four lines of the file a re

Harvard U. ,MA , 1636


Wi lliam a nd Mary,VA,l6 9 3
Yale U.,CT,l701
U. o f Pen nsyl v ania,PA,l7 40

Example 4 T h e fo llowing program displays co lleges alphabe t ica lly ordered (alon g with
the ir year founded ) th at a re in the state spec ified in a masked text box . In this progra m we do
not assume th at th e n umbe r of co lleges in the tex t file is known in advan ce. A lso, th e Se lec t
clause returns a seque nce of values whose da ta type is a st ructure h av ing two me mbers- a na me
me mbe r and a yearFounded mem ber.

Structure College
Dim name As String
Dim state As String 'state abbreviat1 on
Dim yearFounde d As Integer
End Structure

Dim co l leges() As College

Private Sub frmCollege s _ Load( . .. ) Handles MyBase .Load


'Place the d~ta fo e. ch 1 'ge 1nto the ar ay hoo s .
Dim schoo l s () = IO. File . ReadAllLin es ( "Colleges. txt" )
Dim n As I nteger = schools. Count - 1
ReDim col l eges (n)
Dim l i ne As String ho.ds data for a single college
Dim data( ) As String
For i As Integer = 0 To n
line = schools(i)
data= line.Split ( ","c )
c ol l ege s (i) .name = data(O )
col l eges(i) .state = data(l)
col l eges(i) .yearFound ed = Cint (data(2))
Next
End Sub

Private Sub btnDisplay_ Click( . .. ) Handles btnDisplay .Cli c k


Dim query From col In col l eges
Where col.state = mtbState.T ext.ToUppe r
Order By col.name Ascending
Select col . name, col.yearFo unded
lstCollege s.Items.Cl ear()
For Each institutio n In query
ls t Colleges . Items.Add ( institution .name & " " & insti t ution.yearF ounded)
Next
End Sub
7.3 A rrays of S tructures • 30 1

[Run, type a state abbrev iat ion into the masked text box, and cl ick on the button.~
I
a ... Earlies Coll eges l = I @) j-tJ J

State : PA

I Display Colleges )
IDickinson Coll ege 1773
Moravian Coll ege 742
U. of Pennsybtania 1740
U. of Pittsburgh 1787
.1 Wash. & Jefferson 178 1
-

In the progra m above, th e q ue ry returned a sequ en ce of values whose data type is a struc ture
h av ing two me mbers. (The numbe r of me mbe rs was de termin ed by the numbe r of items in the
Select clause. ) The n ew structure type h a no decla red n ame, and thus it is sa id to h ave an
anonymou s type. Local type inferen ce (prov ided by h av ing Option Infe r set to O n ) spa res us
from h av ing to know the n a mes of an on ymous data types.

The DataGridView Control


ln Section 7 .2, t he Data o urce property was used to d isplay (as a li st) th e va lues return ed by a
q ue ry h av ing a single ite m in its Selec t clause. The DataSource prope rty a lso ca n be used to d is-
p lay (as a ta ble) th e struc ture va lues re tu rned by a q ue ry h av ing two or mo re ex press ions in its
Select clause. In tead of a list box, th e va lues are d isp layed in a Da taG ridView co ntro l. (The
DataG ridView control is found in th e Too lbox 's A ll Windows FomlS and Data groups. The sta n -
da rd prefix fo r th e na me of a DataG rid View contro l is dgv. )
If the Select clause of a q ue ry con ta ins two or mo re ite ms, the n a pa ir of sta te me nts of th e
fo rm

d gvOu t put.DataSource = qu e r y Name . ToList


dgvOutput. Cur r entCe l l = Nothing

d isp lays th e va lues re turned by the q uery in th e DataG ridView con tro l dgvOutput. (Note: The
second sta te ment is optio n al. It prevents h av ing a sh aded ce ll in th e table. ) For insta nce, co n -
sider th e progra m in the prev ious example. If the list box is rep laced by the DataG ridView co n -
tro l dgvCo lleges, the state me nt lstCollege s. Items. Cl ear () is de le ted , a nd th e For Each
loop is replaced by the state me nt

dgvCol l eges . DataSource = query. ToList


dgvCo ll eges .Cu r rentCell = Nothing

th en the outco me will be as shown in Fig. 7.13 on the nex t page.


The blank co lu mn at th e left sid e of the DataGridView contro l ca n be re moved by se tt ing
the RowHeade rsVisib le pro pe rty of th e DataG ridView contro l to Fa lse at des ign time. By
defa ul t, the co lumn h eade rs contain the me mbe r n ames fro m the query's Select cla use. The co l-
umn h eade r can be c ustomi zed with the H eade rText prope rty. Figur 7.14 results wh en the
302 • Chapter 7 A rrays

a ~ Earlie:; Coll eges l = I @] I~ ,J


State : PA

I Display Colleges )
name yearFounded
Dickinson College 177.3
- -
Moravian College 117 2
-
U. of Pennsylvania 174.0
lJ . of Pittsburgh 17B7
Wash. & Jefferson 1781

FIGURE 7.13 Use of a DataGridView in Example 4.

ll _. Earlie st Coll eges l = I @] 1-...ES d


State: PA

( Display Colleges ]
College Year Founded
Dickinson College 177.3
- ---
Moravian College 17 2
--
U. of Pennsojlvania 17 0
U. of Pittsburgh 1787
Wash. Jefferson 1781

FIGURE 7.14 C ustomizing the headers in Example 4.

RowHeadersVi ible property is set to False and the fo llow ing two lines of code are added to the
btnOisplay_C lick event procedu re:
dgvColleges .Co lumns( "name" ) .HeaderText = "College"
dgvColleges .Co lumns( "yearFounded" ) .HeaderText = "Year Founded"

Note : The DataGridView contro ls appearing in this textbook have bee n carefu lly sized to
exactly fit the data. Comment 3 exp la ins how this was acco mplished. There is no need for you
to trive fo r such precision when working the exe rcises.

Searching an Array of Structures


Often one member (or pair of members) serves to uniquely identify each element in an array of
structures. Such a member (or pair of members) is called a key. In Example 4, the name member is
a key for the an·ay of College structure . Often an array of tructures is searched with a LINQ query
for the sole element having a specific key value. If so, the query returns a sequence consisting of a
single item, and a method such as the First method is used to disp lay the value in a tex t box.
7.3 A rrays of S tructures • 303

Example 5 The followin g program provides informa t ion about a college se lected from
a
list box by the user. (Note: In this program, the method First can be replaced
by other method s,
such as Last, Max, or Min.)
Struct ure Colleg e
Dim name As String
Dim state As String
Dim y earFoun ded As Intege r
End Struct ure
Dim colleg es () As Colleg e
Privat e Sub frmCol leges Load( ... ) Handle s MyBase .Load
Dim school s() = IO. File .ReadA llLines ( "Colle ges.txt " )
Dim n = school s.Coun t - 1
ReDim college s(n)
Dim line As String 'holds data for a single colleg e
Dim data() As String
For i As Intege r = 0 To n
line= school s(i)
data = line.S plit( ","c )
coll eges (i) . name = data(O)
colleg es(i) .state = data(l)
colleg es(i) .yearFo unded = Cint (da ta(2))
Next
Dim query = From institu tion In college s
Order By institu tion.na me
Select institu tion
For Each institu tion In query
lstColl eges.It ems.A dd(ins titution .name)
Next
End Sub
Privat e Sub lstColl eges_ Selecte dindex Change d( ... ) Handle
s
lstCol leges.S elec tedinde xChang ed
Dim query From institu tion In college s
Where institu tion .name = lstColl eges.T ext
Select institu tion
txtSta te . Text = query. First.s tate
txtYea r.Text = CStr (query .First.y earFou nded)
End Sub
[Run, and click on a college.]

a~ Earliest Coll eges l = I @) l!l!<"·tJ J

Oick on the name of a college .

Bowdoin College
Brown U. Stat e : DC
Columbia U.
Dartmouth College Yearfounded : 1789
Dickinson Colleqe I=
18l~-~.~.m-·~·mi!c:::Jl\.-.!
Hampton-Sydney
Hartwick College
Harvard U.
Moravian College
Princeton U.
Rutgers College
304 • Chapter 7 Arrays

Using General Procedures with Structures


and returned by Function
Var iables whose type is a structu re ca n be passed to Sub procedures
procedu res in the same way as variab les of other da ta types.

to curve
Example 6 The following program uses genera l proced ures to input grades and
the grades.

Struct ure Grades


Dim examl As Double
Dim exam2 As Double
Dim final As Double
End Struct ure

lculat e .C lick
Privat e Sub btnCa lculat e_ Click( ... ) Handle s btnCa
Dim scores As Grades
Dim semest erAver age As Double
GetGr ades(s cores)
scores = Curve Grade s(scor es)
+ 2 * score s.fina l) I 4
semes terAve rage = (score s.exam l + scores .exam2
er(sem esterA verage , 2)
txtOu tput.T ext = "Seme ster Averag e: " & Forma tNumb
End Sub

Sub GetGr ades( ByRef scores As Grades )


scores .exam l 80
scores .exam2 90
scores . final 95
End Sub

Grades
Functi on CurveG rades( ByVal scores As Grades ) As
scores .exam l += 3
scores .exam2 += 4
score s.fina l += 2
Return scores
End Functi on

[Ru n, and click on the button .]

a Se ester Ave ra ge

[ Get Data and Detennine Status

Semester Average : 92.75

Displaying and Comparing Structure Values


Statem ents of the fo rm
lstBox . Items. Add(s tructu reVar)
ed. Each membe r of a struc-
where structureVar is a structure variable, do not perform as intend
en t . A I o, compa risons invo lving
ture should appear separat ely in a lstBox.ltems.A dd statem
are valid only with ind i-
structu res using the re lationa l ope rato rs<,> ,= , <>,< =, and >=
vidual membe rs of the structure , not with the tru ctures themse lves.
7.3 Arrays of Structures • 305

Complex Structures (Optional)


So far, the membe rs of stru ctures have had elementary types; such as String o r Intege r. H ow-
ever, the type for a member can be an ot her structure or an array. When a member is given an
array type, the defining Dim statement must not spec ify the upper bound ; th is task must be left
to a ReD im statement. Example 7 demonstrates the use of both of these nonelementary types of
members.

Example 7 The follow ing program totals a person's college credits and determines whether
that person has enough cred its for graduation. Notes: The structure variable person is loca l to the
btnGet_Click event procedure. In the fifth line of the procedure, pe r son . name . firstName should
be thought of a (person . name ) . firstName .

OBJECT PROPERTY SETTING


a::} Graduation Statu s GJI [§] ICID frmStatus Text G rad uation Status
btnGet Text
Get Dat a and Determine St atus
l txtResult ReadO nly
Get Data and
Determine Status
True

Structure FullName
Dim firstName As String
Dim lastName As String
End Structure

Structure Student
Dim name As FullName
Dim c redits() As Integer
End Structure

Private Sub btnGet Click ( ... ) Handles btn Ge t .Click


Dim numYears As Integer
Dim person As Student
txtResult. Clear ()
person . name . firstName = I npu tBox( "First Name:" )
person.name . lastName = InputBox ( "Last Name:" )
numYears = Cint (InputBox( "Number of years completed:" ) )
ReDim person . c r edits(numYears - 1)
For i As Integer = 0 To numYears - 1
person . credits(i) = Cint ( InputBox( "Credits in year" & i + 1))
Next
DetermineStatus (person)
End Sub

Sub DetermineStatus( ByVal person As Student)


Dim query = From num In person.credits
Select num
Dim total As Integer = query . Sum
If ( to ta l > = 12 0 ) Then
txtResult.Tex t = person . name . firstName & " " &
person . name.lastName & "has enough credits to graduate."
306 • Chapter 7 Arrays

Else
txtRes ul t .Text person .name. firstNa me & " " &
person . name . l a stName & " needs " &
(120 - total) & "more credits to gradua te."
End I f
End Sub

[Run, click on the bu tton , and respond to requests for input with Miranda
, Smith, 3, 34, 33, 34.]

a... Graduat ion Sta us.

I Get Data and Determine Status

Miranda Smith needs 19 more credits to graduate .

Comments
involve comput ed
1. When a Select clause conta ins two or mo re items, none of the items ca n
were interest ed in the
va lues. For instance , cons ider the q uery in Example 3 and suppose we
age of each college in 2010. The following query wou ld not be va lid:
Dim co l legeQu ery = From col In college s
Where col.sta te = mtbSta te.Text .ToUpp er
Order By col.nam e Ascend ing
Select col.nam e, 2010 - col.yea rFound ed

Instead, the q uery must be written

Dim college Query = From col In college s


Where col.sta te = mtbSta te . Text . ToUppe r
Order By col.nam e Ascend ing
Let age = 2010 - col.yea rFound ed
Selec t col.nam e, age
modate its text,
2. If a column header cell in a DataGr idView control is too narrow to accom
is too narrow to
the text is disp layed in two or more li nes. H owever, if an o rd inary cell
some ce lls will be
accomm odate its text, part of the text will be cut off. If yo u suspect that
each column 's width will
too narrow, set the A utoSize Co lu mn property to A llCells. Then,
automa tically adjust to accomm odate the longest entries in the column .
at its default setting
3. When the AutoS izeCo lumn property of a DataGr idView control is left
the S ize property
of None, the control's ize is specified by its Size property. The etting for
he ight in pixels.
has the form w, h, where w i the width of the grid in pixe ls and h is its
been set to Fa lse, good values for the S ize prop-
After the RowHe adersVisible property h as
erty are w = 100 ·[numb er of columns] + 3, and h = 22 ·[numb er of rows] + 1. Note: If
column header will
there will be a scroll bar on th right sid e of the grid, add 17 tow. If any
occupy more than one line, add 13 to h for each addition al line.

Practice Problems 7.3

1. Find the errors in the fo llowing event procedure.


Sub btnDis play_C lick( ... ) Handle s btnDis play.C lick
Structu re Team
7.3 A rrays of Structures • 307

Dim school As String


Dim mascot As String
End Structure
Team. school 11
Rice"
Team.mascot "Owls"
txtOutput.Text = Team.school & " " & Team.mascot
End Sub

2. Correct the code in Practice Problem 1.

EXERCISES 7.3

In Exercises 1 through 10, determine the output displayed when the button is clicked.
1. Structure Rectangle
Dim length As Integer
Dim width As Integer
End Structure

Private Sub btnDisplay_ Click( ... ) Handles btnDisplay.Click


Dim footballField As Rectangle
footballField.len gth = 120 'yards
footballField.wi dth 160
'yards
Dim area As Integer footballField.len gth * footballField.wi dth
txtOutput.Text = "The area of a football field is " & area &
" square yards."
End Sub

2. Structure College
Dim name As String
Dim state As String
Dim yearFounded As Integer
End Structure

Private Sub btnDisplay_ Click( ... ) Handles btnDisplay.Click


Dim school As College
school.name = "USC"
school.state = "CA"
school.yearFound ed = 1880
'Now.Year is the current year
Dim age As Integer = Now.Year - school.yearFound ed
txtOutput.Text = school.name & " is " & age & "years old."
End Sub

3. Structure College
Dim name As String
Dim state As String
Dim yearFounded As Integer
End Structure

Private Sub btnDisplay_ Click( ... ) Handles btnDisplay.Click


Dim school As College
308 • Chapter 7 A rray

Dim line As String= "Duke,NC,l 838"


Dim data() As String line.Split (","c)
school.nam e = data (O)
school.sta te = data(l)
school.yea rFounded = Cint(data( 2))
txtOutput. Text = school.nam e & " was founded in " & school.sta te &
" in " & school.yea rFounded &
End Sub

4. Structure College
Dim name As String
Dim state As String
Dim yearFounde d As Integer
End Structure

Private Sub btnDisplay_ Click( . . . ) Handles btnDisplay .Click


Dim school As College
Dim data() As String = {"Stanford ", "CA", "1885"}
school.nam e = data(O)
school.sta te = data(l)
school.yea rFounded = Cint(data( 2))
txtOutput. Text = school.nam e & " was founded in " & school.sta te &
" in " & school.yea rFounded &
End Sub

5. Structure Appearance
Dim height As Double
Dim we i ght As Double
End Structure

Private Sub btnDisplay_ Click( ... ) Handles btnDisplay .Click


Dim pe r sonl, person2 As Appearance
personl.he ight 72
personl.we ight 170
person2.he ight 12 * 6
If personl.he ight = person2.he ight Then
lstOutput.I tems.Add( "heights are same")
End If
person2 = personl
lst0utput.I tems.Add( person2.w eight)
End Sub

6. Structure Employee
Dim name As String
Dim hoursWorke d As Double
Di m hourlyWage As Double
Dim eligibleFor Bonus As Boolean
End Structure

Dim worker As Employee

Private Sub frmWages _ Load( ... ) Handles Me.Load


worker.nam e = "John Q. Public"
7.3 A rrays of Structures • 309

worker.hoursWork ed = 40
worker.hourlyWag e = 25
worker.eligibleFo rBonus True
End Sub

Private Sub btnDetermine_ Click( ... ) Handles btnDetermine . Click


Dim wage As Double
wage = worker.hoursWork ed * worker.hourlyWag e
If worker.eligibleFo rBonus Then
wage = wage + 0.1 * wage
End If
MessageBox.Show(" Wage for" & worker.name & ": " & FormatCurrency(w age))
End Sub

7. Structure TestData
Dim name As String
Dim score As Double
End Structure

Dim students() As String IO.File.ReadAllL i nes("Scores.txt" )

Priva te Sub btnDisplay_ Click() Handles btnDisplay.Click


Dim student As TestData
For i As Integer = 0 To students.Count - 1
student = GetScore(i)
DisplayScore(stu dent)
Next
End Sub

Function GetScore(ByVal i As Integer) As TestData


Dim student As TestData
Dim line As String= students(i)
Dim data() As String= line .Split(","c)
student.name = data(O)
student.score = CDbl(data(l))
Return student
End Function

Sub DisplayScore(ByV al student As TestData)


lstOutput . Items.Add(studen t.name & ": " & student . score)
End Sub

(Assume that the three lines of the file Scores.txt contain the fo llowing data: Joe,88;
Moe,90; Roe,95.)
8. Structure Employee
Dim name As String
Dim dateHired As Date
Dim hasDependents As Boolean
End Structure

Private Sub btnDisplay_ Click( ... ) Handles btnDisplay.Click


Dim worker As Employee
3 10 • Chapter 7 Arrays

worker.name = "John Jones"


worker.dateH ired = #9/20/2010#
worker.hasDe pendents = True
If DateDiff(Da teinterval . Day, worker.dateH ired, Today) < 180 Then
MessageBox.S how("Not el i gible to participate in the health plan.")
Else
MessageBox.S how("The monthly cost of your health plan is " &
HealthP l anCost(worke r.hasDepende nts) & ".")
End If
End Sub

Function HealthPlanCo st(ByVal hasDependent s As Boolean) As String


If hasDependent s Then
Return FormatCurren cy(75)
Else
Return FormatCurren cy(50)
End If
End Function

(A sume th at today is 1/1 /20 11.)


9. Structure Address
Dim street As String
Dim city As String
Dim state As String
End Structure

Structure Citizen
Dim name As String
Di m dayOfBirth As Date
Dim residence As Address
End Structure

Private Sub btnDisplay_ Click( ... ) Handles btnDisplay.C lick


Dim person As Citizen
person . name = "Mr . President"
person . dayOfBirth = #8/4/1961#
person . residence.st reet = "1600 Pennsylvania Avenue"
person . residence.ci ty = "Washington"
person . residence . state = "DC"
txtOutput.Te xt = person.name & " lives in " &
person.resid ence.city & ", " & person.resid ence.state
End Sub

10. Structure TaxData


Dim socSecNum As String
Dim numWithAllow As Integer 'number of withholding allowances
Dim maritalStatu s As Str i ng
Dim hourlyWage As Double
End Structure

Structure Employee
Dim name As String
7.3 A rrays of Structu res
• 311

Dim hrsWo rked As Doubl e


Dim taxin fo As TaxDa ta
End Struc ture

Priva te Sub btnDi splay_ Click ( ... ) Handl es


btnDi splay .Click
Dim worke r As Emplo yee
worke r.nam e = "Hann ah Jones "
worke r.hrsW orked = 40
worke r.taxi nfo.h ourly Wage = 20
txtOu tput . Text = worke r . name & " earne d "
&
Forma tCurre ncy(w orker. hrsWo rked * worke r.taxi
nfo.ho urlyW age)
End Sub

In Exerc ises 11 throug h 13, determ ine the errors .


11. Struc ture Nobel
Dim peace As Strin g
Dim yr As Integ er
End Struc ture

Priva te Sub btnDi splay_ Click ( .. . ) Handl es


btnDi splay .Click
Dim prize As Nobel
peace = "Mar tti Ahtis aari"
yr = 2008
txtOu tput.T ext peace & "won the " & yr & "Nob el Peace Prize
."
End Sub

12. S true ture Vitam ins


Dim a As Doubl e
Dim c As Doubl e
End Struc ture

Priva te Sub btnDi splay_ Click ( ... ) Handl es


btnDi splay .Click
Dim minim um As Vitam ins
minim um.c 60
minim um.a 5000
lstOu tput.I tems.A dd(mi nimum )
End Sub

13. Struc ture BallG ame


Dim hits As Doubl e
Dim runs As Doubl e
End Struc ture

Priva te Sub btnDi splay_ Click ( ... ) Handl es


btnDi splay .Click
Dim gamel , game2 As BallG ame
game l.hits 15
game l.runs 8
game 2.hits 17
game2 .runs 10
If gamel > game2 Then
txtOu tput.T ext = "The first game was bette
r."
Else
312 • Chapter 7 Arrays

."
txtO utpu t.Tex t "The secon d game was at leas t as good
End If
End Sub

thro ugh (e) to fill in the miss ing lines in the


14. Wr ite lines of code as instru cted in S teps (a)
fo llow ing program.
Stru cture Appe aranc e
Dim heig ht As Doub le 'inch es
Dim weig ht As Doub le 'poun ds
End Stru cture

Stru cture Perso n


Dim name As Strin g
Dim stats As Appe aranc e
End Stru cture

les btnD ispla y.Cl ick


Priv ate Sub btnD ispla y_ Click ( ... ) Hand
Dim pers onl, perso n2 As Perso n
(miss ing lines )
End Sub

(a) Give /Jerso nl the name Mich ael.


respe ct ive ly.
(b) Set Mi chae l's he ight and we ight to 71 and 190,
(c) Give person2 the name Jacob.
respe ctive ly.
(d) Set Jacob's heigh t and we ight to 70 and 175,
t he other, disp lay a sente nce of t he form
(e) If o ne perso n is both taller and heav ier than
sma ller perso n]."
"[nam e of bigge r pe rson] is bigge r than [name of
results from clicking on the butto n. The
In Exercises 15 throu gh 18 describe the outpu t that
matio n abou t the 25 largest cities in the
programs use the fil e Cities .txt that conta ins infor
field s-nam e, state , population in 2000 (in
Unite d States. Each record of the file has four
The first four lines in the file are as follow s:
IOO,OOOs), and population in 2010 (in lOO,OOOs).
New York ,NY, 80.1, 82.7
Los Ange les,C A,36 .9,38 .84
Chic ago,I L,29 .0,28 .7
Hous ton,T X,l9 .5,22 .4
code:
Assu me that each progr am conta ins the following
Stru cture City
Dim name As Strin g
Dim state As Strin g
Dim pop20 00 As Doub le
Dim pop20 10 As Doub le
End Stru cture

Dim citie s() As City

les Me.L oad


Priv ate Sub frmC ities Load ( .. . ) Hand
the array citie s.
'Plac e the data for each city into
ines ("Ci ties. txt")
Dim ci tyRe cords () = IO . File . Read AllL
the array citie s.
'Use the array cityR ecord s to popu late
Dim n = cityR ecord s.Co unt - 1
7.3 A rrays of S tructures • 313

ReDim cities(n)
Dim line As String 'holds data for a single city
Dim data() As String
For i As Integer = 0 To n
line = cityRecords( i)
data= line.Split{", "c)
cities(i) .name= data(O)
cities(i) .state= data(l)
cities(i) .pop2000 CDbl(data(2) )
cities(i) .pop2010 = CDbl(data(3) )
Next
End Sub

15. Private Sub btnDisplay_ Click( ... ) Handles btnDisplay.C lick


Dim query From cty In cities
Where cty.state = "TX"
Order By cty.pop2010 Descending
Select cty.name, cty.pop2010
For Each cty In query
lstOutput.Item s.Add(cty.nam e & " " &
FormatNumber( lOOOOO * cty.pop2010, 0))
Next
End Sub

16. Private Sub btnDisplay_ Click( ... ) Handles btnDisplay.C lick


Dim query From cty In cities
Where cty.state = "TX"
Let growth = (cty.pop2010 - cty.pop2000) I cty.pop2000
Order By growth Descending
Select cty.name, cty.state, growth
For Each cty In query
lstOutput.Item s.Add(cty.nam e & ", " & cty.state)
Next
lstOutput.Ite ms.Add("Gre atest growth: " &
FormatPerce nt(query.Firs t.growth))
End Sub

17. Private Sub btnDisplay_ Click( ... ) Handles btnDisplay.C lick


Dim query From cty In cities
Let increase = cty.pop2010 - cty.pop2000
Where cty.name 11
Phoenix"
Select increase
txtOutput.Te xt = FormatNumber( lOOOOO * query.First, 0)
End Sub

18. Private Sub btnDisplay_ Click( ... ) Handles btnDisplay.C lick


Dim query From cty In cities
Order By cty.pop2010 Descending
Select cty.pop2010
Dim pops() As Double = query.ToArra y
ReDim Pres e rve pops(9)
txtOutput.Te xt = FormatNumber( lOOOOO * pops.Sum, 0)
End Sub
3 14 • C hapter 7 A rrays

In Exercises 19 through 2 2 use the fil e U SStates.tx t that consists of 5 0 record s and four
fields. Each field gives a piece of info rmation about a state-name, abbreviation, land area
(in sq uare miles), population in the year 2000. The records are ordered by the states' date
of entry into the union. The first fou r lines of the fil e are
Delaware , DE,l95 4 ,759000
Pennsylv ania , PA, 4 4817,1 22 9 60 00
New J e r s e y, NJ,74 17,813500 0
Ge org i a,GA,57 906,76370 00
19. Write a program that accepts a state's abbrev iation as input and displays the state's name
and its area. See Fig. 7.15.

aj U.S. States l = I @) 1--ES J


j Display States and Abbreviations ]
;.
State
State
Abbreviation
l[J
a-J U.S. Sta es l = I @) ~~ .J A.K ALASKA
---- ...
AZ ARIZONA.
State Abbreviation : MD
CT CONN ECTIC UT
Find Area of State
---
GA. GEORGIA

The area of Mar,1and is 9.77 square miles .


HI HAWAII l~

FIGURE 7.15 Possible outcome of Exe rcise 19 . FIGURE 7.16 Outcome of Exe rcise 20.

20. W rite a program that displays the names of the states whose abbrev iat ions are different
than the first two letters of their name. Both the abbreviat ions and the states should be dis-
played. See Fig. 7.1 6.
21. W rite a program that d isplays th e names of the state sorted by their pop ulation densities in
desce nding order. N ext to each name should be the state's pop ul ation density. See Fig. 7.1 7.

l = I @) 1-a . .J a'i U.S. Sta es l = I @) I~ · .J


a:; U.S. Sta es

Display States Ordered by Land Area


Display States and Population Densities
;.
~
Percentage of
People per State
State Total Area
Square Mile u
AJaska 15 . 96~~
New Jersey 1.096.80 ---
Rhode Island
---
955.02 I Texas nn;
----
Califomia . 35 ~~
Massachusetts 75&.93 I
----
Montana 4.1 "·''•·
Connecticut 675.13
J ---
New Mexico 3 . 39~~
M a r,~an d 544.51 ....

FIGURE 7.17 O utcome of Exercise 2 1. FIGURE 7.18 O utcome of Exercise 22.


7.3 A rrays of Struct ures
• 315

22. Write a program that di play the names of the states


ordered by land area. N ext to each
name should be the perce ntage of the total U .S. land area
in that state. See Fig. 7 .18.
In Exerc ises 23 throu gh 26 use the fil e Baseb all.txt
that conta ins data about the perfo r-
mance of major leagu e baseb all playe rs durin g the 2009
regula r seaso n. Each record of the
file conta ins four fields -name, team, atBat s, and hits.
Some lines of the fil e are as follows :
Aaron Hill , Blue Jays, 682,1 95
Ic hiro Suzu ki,Ma riner s , 639 ,2 25
Derek Jeter ,Yan kees , 634,2 12
23. Wr ite a program using the file Baseball. txt that reque
ts a team a input from a list and dis-
plays the players from that team. The playe rs shoul d
be so rted in decreas ing orde r by the
numb er of h its they had durin g the season. T he outpu
t should d isplay each playe r's fu ll
name and numb er of hits. See Fig. 7. 19.

~~ ~ •1ajor Leagu e asebal l

Oick on a team.

Cardinals ,.. Plcrl er Hits


Cubs
Diamondbacks Pablo Sando ral 1&9
Dodgers -~
Rand>,. V>
linn 1 1
Indians Fred&,. Sanchez 1'
Marlins
·- Aaron Rowand p

FIGURE 7.19 Outco me of Exerc ise 23.

24. Write a program that req uests a team as input and


d isplay the playe rs from that team. T he
playe r should be sorted alphabet ica lly by their last na
me . Playe rs hav ing the sa me last
name should be ordered secon daril y by their first name
s. (Note : T he Sp li t metho d can be
used to extrac t first and last names fro m a perso n's fu
ll name . For instan ce, the va lue of
"Babe Ruth ".Spl it ( " "c) .Last is Ruth . )
T he outpu t hould display each playe r's full
name and battin g ave rage. See Fig. 7.20.

.
g ...J Baseba ll

Team: Rays

Displcrl Plcr1-ers

PLAYER B D ING
.A.\/ER.A.GE
Jason Bartlett .''2
Pat Burrell 1
-
Carl Crav.ford .3 5
Evan Longoria .281
Dioner Navarro

FIGURE 7.20 Outco me of Exerc ise 24.


316 • Chap ter 7 Arrays

g
batti ng average and the playe r (or playe rs) havin
25. Writ e a program that displays the highest . ee Fig. 7.21.
display each playe r's team
the highest batting ave rage. The ou tput also hould

11 Baseba ll a~ Base ba ll l = I @) ~~ J
Display Players Display Tearns
(

Angels
Best batting average : 0.365 Astros l]
Athletics
Player Team Blue Jays
Braves
Joe Mauer Twins Brewers
Cardinals

FIGURE 7.22 Outc ome of Exerc ise 26.


FIGURE 7.21 Outc ome of Exerc ise 25.

d
txt that disp lays the names of the team s sorte
26. Writ e a program using the fi le Baseball.
alpha bet ica lly. See Fig. 7 .22.
ces. txt that cont ains data abou t the Supr eme
In Exer cises 2 7 throu gh 30 use the file Justi last
d of the fil e cont ains six field s-fir st nam e,
Cou rt justi ces, past and prese nt. Each recor
h they were appointed, year appointed, and
nam e, appointin g president, the state from whic
the last field is set to 0.) The first five lines
the year they left the cour t. (For sittin g judges,
of the file are as follows:
6,0
Sam uel,A lito, Geo rge W. Bush , NJ ,200
30,1 844
Henr y ,Bald win , Andr ew Jack son, PA,l8
,VA ,l836 ,184 1
Phil ip , Barb our,A ndre w Jack son
t , AL,l 937, 1971
Hugo ,Blac k , Fran klin Roos evel
,l970 ,199 4
Harr y,Bl ackm an,R icha rd Nixo n,MN
the
g justices ord ered by the yea r th ey jo ined
27. Writ e a program that d isplays the sittin
Supr eme Cour t.
a president as inpu t from a list and then displays
28. Writ e a program that requests the name of
es should be orde red by the lengt h of time
the justices appo inted by that president. The justic
(Not e: For sitting justi ces, use Now . Year -
they served on the cour t in desce ndin g orde r.
yrAp poin ted as the ir time of serv ice. Othe
rwise, use yrLe ft - yrAp poin ted.) Use the file
file conta ins the names of the presidents in
USP res.tx t to fi ll the presidents list box. That
the ord er they served. See Fig. 7 .23.

a~ Supre me Court
,Appointees
Oick on the name of a president.
Calvin Coolidge William Douglas
Herbert Hoover Hugo Black
Franklin Roosevelt Felix Frankfurter
Hany Truman Stanley Reed
Dwight Bsenhower Robert Jackson
John Kennedy CJ Frank Murphy
Lyndon Johnson Wiley Rutledge
Richard Nixon James Byrnes

FIGURE 7.23 P ossible outco me of Exerc ise 28.


7.3 Arrays of Structures • 3 17

29. Write a program that requests a state abbreviation as input and displays th e justices
appo inted from that state. The justices sh ould be ordered by the ir year appo inted. The o ut-
put sho uld also display th e last name of the appointing pres ident and the length of tunc
se rved . (Note: For itting justices , use Now. Year - yrAppointed as the tr t tme of serv tce.
Otherwise, u e yrLeft - yrAppointed. ) A lso, the program sh ould info rm th e user if no
justices have been appointed from the req uested state. ee Fig. 7.24.

a;t S p e rne Co

Display Justices

State abbreviation :
~pointing
Justice
President
Display Justices
William Brennan Dwight Bsenhower

Appointing Potter Stewart D•.vigrrt Bsenhower


Justice Years Served
President
&,m n 'Nhite John 1'-enned-1
.Stephen Reid Uncoln
Thurgood Marshall Lyndon Johnson
1Nilliam Woods Hayes
Warren Burger Richard Nocon
Joseph McKenna Me \lnley 7
Harry Blackman Richard Nocon
Earl Varren Bsenhower 1S
Lewis Pov.•ell Richard Nocon
Anthony ennedy Reagan
~/i lli a m Rehnquist Richard Nocon

FIGURE 7.24 Possible ou tcome of Exercise 29. FIGURE 7.25 Outcome of Exercise 30.

30. Write a program th at displays the makeup of the Supreme Court at the beg inning of 1980.
The justices sho uld be ord ered by the yea r they were appointed, and the names of the
appo inting pres idents sho uld be d isplayed . See Fig. 7.25.
31. The Twelve Days of Christmas. Each year, PNC Advisors of Pittsburgh publishes a C hristmas
price index. See Table 7.3. Write a program that requests an integer from 1 through 12 and
then lists the gifts fo r that day a long with that day's cost. O n the nth day, the n gift are 1 par-
tridge in a pear tree, 2 turtle doves, ... , n of the nth gift. The program also should give th e
total co t up to and including that day. As an exa mp le, Fig. 7. 26 shows the output in the list
box when the user enters 3. The contents of Table 7.3 , along with the day corresponding to
each gift, are contained in the fi le G ifts.txt. The first three lines of the fi le are as follows:
l,partridge in a pear tree,159.99
2,turtle doves,27 .99
3,French hens , lS

Christmas price index for 2009.


Item C ost Item C ost
pa rtridge in a pear rree 159.99 swan-a-swimmin g 750.00
turtle dove 27.99 maid-a- milking 7.25
French hen 15.00 lady dancing 608.11
calling bird 149.99 lord-a- leaping 44 1.36
go ld ring 99 .99 piper pi ping 207.70
goose-a- lay ing 25 .00 drummer drumming 206.26
3 18 • Chapter 7 A rrays

The gifts for day 3 are


1 partridge in a pear tree
2 turtle doves
3 French hens

Cost for day 3: $260.97


Total cost for the first 3 days: $636.93
FIGURE 7.26 Sample output for Exercise 3 1.

The file Famous.t xt contains the names of some famous American s and their birthdays. U se
this file in Exercises 32 through 35. The first three lines of the fil e are
Paul Allen,l/2 1/1953
Lance Arrnstron g,9/18/19 71
Neil Arrnstron g,S/5/193 0
32. Tuesday's child is full of grace. Display a list of the people in the fil e Famous. txt born on a
Tuesday. (Hint: U se the FormatDa teTime function.) See Fig. 7.27.

a-:1 T esday's Child ren 0 ~


1970's Childre l=I§J L ~. J

Display the Names of Some


Famous People Bom on Tuesday
i Display the Names of Some
Famous People Bom in the 197 I
Neil .Annstrong Lance Amlstrong
Sergey Brin
I
Michael Dell
Robert De Niro
Nancy Pelosi
Jack Vl/elch
lKate Hudson
Angelina Jolie
GNyneth Pa~ro w

FIGURE 7.27 Output of Exercise 32. FIGURE 7.28 Output of Exercise 3 3 .

33. Display a list of the people in the fil e Famous. txt born during the 1970s. See Fig. 7.28.
34. Display a table showing all the people in the file Famous. txt along with their ages. The peo-
ple should be ordered by their ages in descendin g order.
35. Display a tab le show ing all the people in the file Famous.tx t who are in their forties along
with their ages in days and the days of the week they were born.
A campus club has 10 members. The following program stores informati on about the stu-
dents into an array of structures . Each structure contains the student's name and a list of
the courses h e or she is currently taking. Exercises 36 through 39 request that an additional
event procedure be written for this program.
Structur e Student
Dim name As String
Dim courses() As String
End Structur e

Dim club(9) As Student 'Holds all students in the club

Private Sub frrnStude nts _ Load( . .. ) Handles MyBase.L oad


Dim pupil As Student
pupil . name = "Juan Santana"
ReDim pupil.cou rses(2)
pupil.cou rses(O) = "CMSC 100"
7.4 Two-Dim ensional Arrays
• 3 19

pupil . course s(1 ) "PHIL 200"


pupil.c ourses (2) "ENGL 120"
club(O ) = pupil
'Enter data for second studen t
pupil . name = "Mary Carlson "
ReDim pupil.c ourses (3)
pupil.c ourses (O) "BIOL 110"
pupil . course s(1) "PHIL 200"
pupil.c ourses (2) "CMSC 100"
pupil.c ourses (3) "MATH 220"
club (1) = pupil
pupil.n ame = "George Hu"
ReDim pup i l.cours es(2)
pupil.c ourses (O ) "MATH 220"
pupil.c ourses (1) "PSYC 100"
pupil.c ourses (2) "ENGL 200"
c l ub(2) = pupil
'Enter names and course s for remain ing 7 people in the club
End Sub
36. W rite the code for a btnOisp lay_C lick event proced ure that displays
the names of all the
student s in the club in a list box.
37. Write the code for a btnOisp lay_Cli ck even t procedure that d isplays
the names of all the
students in the club who are registered for three courses .
38. Write the code for a btnOisp lay_C lick event procedure that displays
the names of all the
student s in the club who are enrolled in C MSC 100.
39. Write the code for a btnOisp lay_C lick event proced ure that d isp lays
the na mes of all the
students in the club who are not enrolled in C MSC 100.

Solutions to Practice Problems 7.3

1. The evenr procedu re conta ins two erro rs. First, the defi ni tio n of a struc
wre ca nn ot be inside a procedure; it
must be typed into the Declarati ons section of th e Code Editor. Second,
the state ments Team . school =
"Rice" and Team.m ascot = "Owls" are nor \'a lid. "1i am" should be replaced
by a va riable of type Tea m
th at has prev iously been declared.
2. Structu re Team
Dim school As String
Dim mascot As String
End Structu re

Private Sub btnDis play_ Click( ... ) Handle s btnDis play.C


lick
Dim squad As Team
squad. school = "Rice"
squad.m ascot = "Owls"
txtOut put.Te xt = squad.s chool & " " & squad.m ascot
End Sub

7.4 Two-Dimensional Arrays


Each array discussed o far held a single list of items. Such aLTay variables are called
one-dim ensional
or single-subscrip ted variables. An array can also hold the contents of a table
with several rows and
columns. Such aLTay variables are called two-dimensional or double- subscrip
ted variable s. Two
tables fo llow. Table 7.4 on the next page gives the road mileage between certain
cities. It has four
rows and four column s. Table 7.5 shows the leading universities in three graduate
-school programs.
It has three rows and five columns.
320 • Chapt er 7 Arrays

I@:JIUI Road mileage between selected U.S. cities.


Chicago Los Angeles N ew York Philad elphia

C hicago 0 2054 802 738


2054 0 2786 2706
Los Angeles
802 2786 0 100
New York
738 2706 100 0
Philad elphia

lt!1:JIIIW Rankings of U.S. university graduate-school programs.


2 3 4 5
1

Vande rbilt UCLA Co lumbia UofO R


Educa tion Sta nford
UC Berk GA Tech U of !L
Engin eering M IT Stanfo rd
Stanfo rd Co lumbia YU
Law Ya le Harva rd

Source: U.S. News and World RefJOrt , 2009.

of tables. They h ave the same types of


Two- dimen siona l array variab les store the conte nts
is that they have two subscr ipts, each with
name s as other array variab les. The only d ifferen ce
ined by the numb er of rows in the table,
its own upper bound . The first upper bo und is determ
er of co lumns.
and the secon d upper bound is de termi ned by the numb

Declaring a Two-Dimensional Array Variable


VideoN ote
The tatem ent
Two-dim ensiona l
arrays Dim arrayN arne(m , n) As DataT ype
a table with rows labe led from 0 tom and
declar es an array of type DataType corres pond ing to
row, hh co lumn is arrayName(j, I<). For
co lumns labe led from 0 to n. The entry in the jth
name d rm. The statem ent
instan ce, the data in Table 7.4 can be stored in an array
Dim rm(3, 3) As Doub le
the form rm(row, co lum n). The values of
wi ll declar e the array. Each eleme nt of the array has
the e lemen ts of the array are
rm(O , 1) = 205 4 rm(0 ,2) = 802 rm(O, 3) = 73 8
rm(O, 0) = 0
rm(1 , 1) = 0 rm(l, 2) = 2786 rm(1, 3) = 2706
rm(1 , 0) = 205 4
rm(2, 1) = 2786 rm (2, 2) = 0 rm(2, 3) = 100
rm(2, 0) = 802
rm(3 , 1) = 2706 rm(3, 2) = 100 rm(3, 3) = 0
rm(3, 0) = 738
iona l string array named univ. The
The data in Tab le 7.5 can be stored in a two-d imens
app ropria te array is declar ed with the statem ent
Dim univ( 2, 4) As Strin g
Some of the entries of the array are
univ(O, 0) = "Stan ford"
univ( 1, 2) = "UC Berk"
univ( 2, 3) = "Colu mb ia"

Implicit Array Sizing and Initialization


at the same time with a statem ent of the form
A two-dimens ional atTay can be declared and initialized
= {{ROWO}, {ROW1}, ... , {ROWm}}
Dim array Name (,) As Data Type
7.4 Two- Dimensio nal A rrays
• 321

where ROWO consists of the en tries in the top row of the correspo nd ing table delimited
by
commas, ROWl consi ts of the entries in the next row of the correspo nd ing table delimite
d by
commas, and o on .

Example 1 The fo llowing program stores and accesses the data from Table 7 .4.
OBJECT PROPERTY SETIING
a~ Interci Distanc es ~~ G JE§J frm Distances Text Intercity Distances
1. Chicago lblC h Text l. C hicago
2. Los .Angeles lblLA Tex t 2. Los A nge les
Origin :
lblNY Tex t 3. N ew York
3. Ne•.v York
Destination :
lb iPh Text 4. Philade lphia
. Philadelphia lblO rig Tex t O rigin:
mtbOrig Mask 0
Show Mileage Between
Origin and Destination lbiDest Text Dest inat io n :
mtbDes t Mas k 0
Mileage :
brnShow Tex t Sho w M ileage Between
O rigin and Destinat ion
lblM iles Text M ileage:
txtMiles Read O n ly True
Dim rm (,) As Double { { 0' 2054 ' 80 2 ' 738},
{2054, 0, 2 786 , 2706} ,
{802 , 2786, 0, 1 00},
{738 , 2706, 100, 0}}

Private Sub btnShow Click( ... ) Handles btnShow .Click


'Determ ine road mileage between cities
Dim row, c ol As Integer
row = Cint (mtbOri g.Tex t)
col = Cint (mtbDes t . Text)
If (row > = 1 And row <= 4) And (col > = 1 And col < = 4) Then
t x tMiles.T ext = CStr (rm( row - 1 , col 1))
Else
Message Box . Show( "Origin and Destina tion must be numbers from
1 to 4" ,
"Error" )
End If
End Sub

[Run, type 3 into the O rigin box, type 1 into the Dest ination box, and click on the button
.]
a ... In e rcity Dista nces

1. Chicago
2 . Los Angeles Origin : 3
3. New York
Destinat ion :
. Philadelphia

Show Mileage Between


Origin and Destination

Mileage : &
322 • Chapter 7 Arrays

The ReDim Statement


A prev iously decla red array can be re ized with

ReDirn array Name (r, c)

which loses the curren t conte nts, or with

ReDirn Prese rve array Name (r , c)

rd Prese rve is used, only the second


which keeps the curren t va lues. Howeve r, when the keywo
dimen sion of the array is given by
dimen sion can be resized. The upper bound of the first
arrayN ame. GetUp perBo und ( 0) , and the upper
bound of the second d imens ion is given by
array Name .GetU pperB ound( l) .
sto re data for con venie nt looku p. In
So far, two-d imens ional arrays have been used only to
mputa tion .
the nex t example, an array is used to make a va luable co

The C enter for Sci nee in the Public Interest publi hes
The Nutrition Score-
Example 2
in each of fiv e categ ories are show n in
book, a highly respected rating of foods. The top two foods
n . The following program comp utes
Table 7.6 along with some inform ation on their comp ositio
three array s-a one-dimens ional array
the nutrit ional conte nt of a meal. The table is read into
nutrients for the names of the five
foods for the names of the ten foods, a one-d imensional array
the numb ers from the table. (The value
nutrie nts, and a two-dimens ional array nutTable to hold
kth food.) The arrays foods and nutrients
of nutTable(k, i) is the amou nt of the ith nutrie nt in the
first three lines are as follows:
are filled from the files Foods. txt and Nutri ents.txt, whose

Foods. txt Nutrients. txt

cups of spina ch calor ies


mediu m sweet potat oes prote in (gram s)
8 oz servi ngs of yogu rt fat (gram s)

ltf1:JIIIM Composition of 10 top-rated foods .


Protei n Fat VitA Calciu m
(grams) (grams) (IU) (mg)
Calori es
3 0.3 8100 93
Spin ach (1 cup) 23
2 1 9230 46
Sweet potato (1 med.) 160
10 3 120 343
Yogurt (8 oz.) 230
8 0 500 302
Skim milk (1 cup) 85
3 1 0 24
Whole whea t bread (1 sli ce ) 65
3.8 0.9 0 18
Brown rice (1 cup) 178
2 1 25 10 30
Watermelon ( 1 wedge ) 11 0
2.4 0.4 7000 80
Papaya (llg.) 156
126.8 3.6 0 73
Tuna in water (1 lb) 575
28.8 26.6 984 190
Lobste r (1 med.) 405

the progra m.
The array nutTable is filled with eleme nts hard- coded into
name d nutFa cts of type NutFact and having fiv e ele-
The progra m uses an array of struct ures
two memb ers; the first mem r h [d-
ment (one fo r each nutrie nt) . The tructur N utF t ha
amou nt of that nutrie nt in the meal.
ing the name of a nutrie nt and the econd holding the total
7.4 Two-D imension a l A rrays
• 323

The program is written in the input-process ing-outp ut format. The input Sub procedur
e
GetAmo unts loops through 10 input dialog boxes that reque t the quant ities of each
food and
places them in to a one-dimensional array named servings . The processing Function
procedure
ProcessData u es the array servings, along with the arrays nutrients and nutTable, to fill the
array of
structures nutFacts. Finally, the output Sub proced ure ShowData uses the array nutFacts
to dis-
play the nutrition al content of the meal into a DataGridView control.
Structu re NutFact
Dim nutrien t As String •name of one of the f1ve nutr1en ts
Dim amount As Double 'amount of the nutrien t in the meal
End Structu re

Private Sub btnDete rmine Click( ... ) Handles btnDete rmine.C lick
Dim serving s(9) As Double
Dim nutFact s(4) As NutFact 'This array of structu res has an
element for each nutrien t.
GetAmo unts(ser vings) 'input
nutFact s = Process Data(se rvings) 'process ing
ShowDa ta(nutFa cts) 'output
End Sub

Sub GetAmo unts( ByRef serving s() As Double )


Dim foods() As String = IO. File . ReadAll Lines( "Foods. txt" )
Ge e numb r f serving s of each food
For i As Integer = 0 To 9
serving s(i) = CDbl (InputBo x( "How many serving s of" & foods(i
)))
Next
End Sub

Functio n Process Data( ByVal serving s() As Double ) As NutFact


()
Dim nutrien ts() As String IO . File .ReadAl lLines( "Nutrie nts.txt" )
Dim nutTabl e(,) As Double = {{23, 3, 0.3, 8100, 93},
{160, 2, 1, 9230, 46},
{230, 10, 3, 120, 343},
{as, a, o, soo, 302},
{65, 3, 1, 0, 24} ,
{178, 3.8, 0.9, 0, 18},
{110, 2, 1, 2510, 30},
{156, 2.4, 0.4, 7000, 80},
{575, 126.8, 3.6, 0, 73},
{405, 28.8, 26.6, 984, 190}}
Dim nutritio nFacts( 4) As NutFact 'This array of structu res has an
element for each nutrien t.
For i As Integer = 0 To 4
nutritio nFacts( i) . nutrien t nutrien ts(i) 'Place the name of a nutrien t
into an array element .
'The next five l1nes calcula te the total amount of the nutrien
t
' n the meal and Jlace it into the array element .
Dim sum As Double = 0
For k As Integer = 0 To 9
sum+= serving s(k) * nutTabl e(k, i)
Next
nutritio nFacts( i) . amount = sum
Place the amount of the nutrien t into
the array element .
Next
324 • Chap ter 7 Arrays

Retu rn nutr i tion Fac ts


End Fun ctio n

As NutF act )
Sub Show Data ( ByV al nutF acts ()
plac e the data from the arra y
'Cre ate a quer y and use it to
con trol .
'of ~tructures 1nto a Data Grid View
cts
Dim quer y = From elem ent In n utFa
Let Nut rien t = elem ent. nutr ient
t.am ount )
Let Amo unt = Form atNu mbe r(ele men
Sele ct Nut rien t, Amo unt
ist
dgvO utpu t.Da taSo urce = quer y . ToL
dgvO utpu t.Cu rren tCel l = Noth ing
End Sub
ium sweet
follo wing menu: .5 cups of spin ach, 1 med
[Run, click on th e butto n , and ente r the
a large papaya, and 1 med ium lobst er.]
potato, 2 lice of wh ole whea t bread, .25 of

l Det ennine Nutritional Contents of a Meal

Nutrient .Amount

calories 45.5

protein (grams) 3B.9

fat (gram s) 29.&5


vitamin A (IU) 16. 1 .
calcium (mg) 350.5

File
Filling a Two-Dimensional Array with a Text
ctu res.
s are simil ar to those used to fill arrays of stru
Text fi les used to fi ll two-dime nsio nal array fo r each row epa-
row of the table, with the entri es
Each line of the text file corresponds to a the text file
ge discussed earli er can be filled with
rated by com mas. Fo r insta nce, the array milea
lines:
Dista nces . txt cons isting of the fo llow ing four
0, 2 054 , 802, 738
2054 ,0,27 86 , 27 06
802 , 2786 ,0,10 0
738, 2706 ,100 , 0
mileage.
The fo llow ing code crea tes and fills the array
Dim mile age( 3 , 3) As Dou ble txt" )
. File . Read AllL ines ( "Di stan ces.
Dim r owOfNums ( ) As Stri ng = IO
Dim line As Stri ng
Dim data () As Stri ng
GetU pper Bou nd(O )
For i As Inte ger = 0 To mile age.
line = rowO fNum s(i)
data = line .Sp lit( ","c )
e.Ge tUpp erBo und( 1)
For j As Inte ger = 0 To mi leag
mile age( i, j) = CDbl (da t a( j) )
Next
Next
7.4 Two-D imensional A rrays • 325

Note: These eleven lines of code, with slight modifica t io n s, a re n eeded in man y of the
exercises. You can store this block of code (o r a ny freque ntl y used fragment of code ) fo r later use
by highlighting it a nd dragg ing it from the Code Edito r in to the Too lbox. To reuse the code ,
just drag it back from the Too lbox to the Code Editor. A copy of the code will rema in in the
Too lbox for further use. Alternate ly, you can cl ic k o n the locat io n in the Code Edi tor whe re
you wan t th e code to be inserted, and then do uble-cl ick o n the code in the Toolbox.
W e reco mme nd tha t yo u place these lines of code in a program, highlight th e m, and drag the m
into th e Too lbox . The n you can drag them o ut when ever you n eed them.

Using UNQ with Two-Dimensional Arrays


A lth o ugh LINQ is n o t as usefu l with two-d imen sio n a l as it is with o n e-dimen sio n a l arrays, it is
so met imes h e lpful. H o wever, LINQ n eeds a Cast me thod to conve rt the two-d imen sio n a l array
to a source data consisting of a o n e-dimension al a rray. S uppose nums i a two-dimen sio n a l array
of type Double and h av ing m rows and n co lumns. Then the code
Dim query = From num In nums . Cast(Of Double )()
Select num

produces a sequence con sisting of the m · n numbers in the array. The me th ods Count , M ax ,
Min , First, Last , A ve rage, and S um app ly to th e q ue ry. A lso, the sequen ce of numbers ca n be
d isp layed in a list box with the DataSource pro pe rty.

Comments
1. W e can define three- (o r high e r-) dimensio na l a rrays much as we do two-d ime nsio n a l
a rrays . A three-dime nsio na l array u es three subscripts, and the a signmen t of va lue
req uires a tr iple -nested loop. A s a n exa mple, a me teoro logist might use a three-dimensio n a l
a rray to record te mperature fo r va rio us da tes, t imes, and e leva tio ns. The a rray might be
decla red with the sta temen t
Dim temps(30, 23, 14) As Double

2. A Re Oim state m n.t canno t ch ange the number of d ime nsio ns of a n a rray. Fo r insta nce, it
cannot c h a nge a o ne-dime nsio na l into a two-dimensio na l a rray.

Practice Problems 7.4

1. Conside r th e road- mileage progra m in Exa mple 1. H o w can it be modified so the actua l
n a mes of the c ities can be supplied by the use r?
2 . ln wha t types of pro ble ms are two-dime nsio n a l a rrays upe rio r to arrays of struc tures?

EXERCISES 7.4

In Exercises 1 through 16, ass ume the array nums is of type Double and has been fill ed with
the contents of Table 7. 7.

lt,1:1!ft4
7 3 1 0
2 5 9 8
0 6 4 10
326 • Chapter 7 Arrays

In Exercises 1 through 12, determine or describe the output of the code.


1. lst0utput . Items.Add(n ums(O, 2))
2. l s tOutput. Items .Add (nums (2 , 1))

3. lstOutput.I tems.Add(n ums.GetUp perBound(l ))


4. lstOutput.It ems.Add(nu ms.GetUpp erBound(O ))
5. Di m total As Double = 0
For Each num In nums
total += num
Next
lstOutput. Items.Add (total)

6. Di m total As Doub le = 0
For c As Integer = 0 To nums.GetUp perBound(l)
total += nums(2, c)
Next
lstOutput . Items.Add (total)

7. Dim total As Double = 0


For r As Integer = 0 To nums.GetUp perBound(O )
total += nums(r, 2)
Next
lstOutput . Items . Add(total)

8. Dim total As Double = 0


For r As Integer = 0 To nums.GetUp perBound(O )
For c As Integer = 0 To nums.GetUp perBound(l)
total += nums(r, c)
Next
Next
lstOutput . Items.Add (total)

9. Dim query= From num In nums.Cast( Of Double)()


Where (num > 8 )
Select num
lstOutput.I tems.Add( query . Count)

10. Dim query = From num In nums.Cast( Of Double)()


Select num
lstOutput.I tems.Add( query . Max)

11. Dim query = From num In nums.Cast( Of Double)()


Select num
lstOutput .Items .Add(query . Sum)

12. Dim query = From num In nums.Cast( Of Double)()


Where (num Mod 2 = 0)
Order By num
Select num I 2
Distinct
For Each n As Double In query
lstOutput.I tems.Add( n)
Next

13. Write code that creates a new array who e entries are twice the en tries of nums.
7.4 Two-D imen iona l Arrays
• 327

14. Write code that uses a For Each loop to find the
average of the numbers in nums.
15. Write code that finds the sum of the even numb
ers in nums two way : first with a For Each
loop and then with a LINQ query.
16. Write code that finds the average of the odd
nun'lb ers in nums two ways: first with a For
Each loop and then with LINQ .
In Exerc ises 17 and 18, deter mine the outp ut of
the code.
17. Dim nums (1, 2) As Doub le
Dim rowO fNum s() As Strin g= IO.F ile.R
ead.A l1Lin es( 11 Digi ts.tx t 11 )
Dim line As Strin g
Dim data () As Strin g
For i As Integ er = 0 To nums .GetU pperB
ound (O)
line = rowO fNum s(i)
data = line .Spl it( 11 , 11 C)
For j As Integ er = 0 To nums .GetU pperB
ound (1)
nums (i, j) = CDb l(dat a(j))
Next
Next
lstOu tput. Item s.Ad d(nu ms(O , 1) + nums
(1, 0))
(Assu me the two lines of the file Digits. txt are
9, 7, 6 and 5, 4, 3.)
18. Dim name s(2, 1) As Strin g
Dim rowO fNam es() As Strin g= IO.F ile.R
ead.A l1Lin es( 11 Peop le.tx t 11 )
Dim line As Strin g
Dim data () As Strin g
For i As Integ er = 0 To name s.Get Uppe
rBou nd(O )
line = rowO fNam es(i)
data = line . Spli t( 11 , 11 C)
For j As Integ er = 0 To name s.Get Uppe
rBou nd(1)
name s(i, j) = data (j)
Next
Next
lst0u tput. Item s.Ad d(na mes( 2, 1) & 11 11
& name s(1, 1))
(Assume the three line of the file Peop le.txt are
Felix , Unga r; Osca r,Ma dison ; and
Henr y, Jame s.)

In Exerc ises 19 throu gh 29, write a progr am to


perfo rm the stated task.
19. A comp an y has two stores (1 and 2), and each
store se lls three items (1 , 2, and 3) . The fo l-
lowing tables give the inven tory at the begin ning
of the day and the amo unt of each item
sold du ring that day.

Beginning Inven tory Sales for Day


ITEM ITEM
1 2 3 1 2 3
Store 125 64 23 Sto re 1 7 45 11
2 30 82 19 2 4 24 8
(a) Record the values of each table in an array.
(b) Adju st the va lues in the first array to hold the
inven tories at the end of the day and dis-
play these new inven tori es.
(c) Calcu late and disp lay the numb er of items in each
store at the end of the day.
328 • Chap ter 7 Arrays

entr y
the uses of com pute rs in the workplace. Each
20. Tab le 7.8 gives the resul ts of a survey on the
the age catego ry t hat use the com pute r for
shows the perc entage of respo nden t from
indic ated purpose.
. (Use Wo rkers. txt.)
(a) Place the data from the tab le in an array
es in the Sp reads heet s colu mn.
(b) Dete rmin e the ave rage of the perc entag

luN!II:• Workers using comEuters on the job.


Inter net/ Cale ndar /
Word
e-mail Sche du le Prog ramm ing
Age Proc essin g Spre adsh eets
62.1 48.9 J 2.4
18-2 4 57.9 56.0
75.6 58.3 18.8
25-2 9 67.8 66.2
78.3 61.8 18.0
30-3 9 69.8 68.0
77.1 59.0 17 .7
40-4 9 69.7 66.9
76.5 54.6 15.1
50-5 9 68.1 62.5
7 l. 2 46. 1 10.6
60 and older 63.7 53 .8
t of Educational Statistics , 2003.
Source: U.S. Center of Educational Statistics, Diges

lled
three campu es. The num ber of stud ent enro
21. A universit y offer 10 cour ses at each of
in each cour e is prese nted in Table 7.9.
llme nts on each camp us.
(a) D isplay the total num ber of course enro
g each cour e.
(b) Disp lay the tota l num ber of stud ents takin

IM:J!B. Number of students enrolled in courses.


Cour se
5 6 7 8 9 10
1 2 3 4
12 25 16 11 17 23
1 5 15 22 21
25 32 35 32 52 25 21
Cam pus 2 11 23 51
32 25 26 29 12 IS II
3 2 12 32

sales for the top five resta uran t chai ns.


22. Tab le 7.10 gives the 2007 and 2008 U.S.
array. (U e Rest aura nts. txt.)
(a) Place the data into a two- d imen siona l ins.
chan ge in sales for these five resta uran t cha
(b) Display the num ber that gives the tota l

lfr1:UIIIel Top restaurant chain s.


2007 Sales $Bil 2008 Sales $Bil
28.7 30.0
1. McD ona ld's 9.6
8.2
2. Subway 9.3
8.7
3. Burger King 8.8
6.6
4. Starbu cks 8.0
8.0
5. Wen dy's

Source: QSR Magazine, October 2009.


7.4 Two- Dim ensio nal A rrays
• 329

23. The scores fo r the top fo ur golfe rs


at t h e 2009 U. S . W o me n 's Ope n are show
n in Tab le 7 .11.
(a) Plac e t h e data into a n arra y. (U se
Go lf. txt.)
(b) Disp lay the to ta l score fo r each p
laye r.
(c) Disp lay the ave rage sco re fo r each
roun d.

lfT1:J!IIII 2009 U.S. Women's Open .


R ound 1 2 3 4
Eun H ee Ji 71 72 70 71
Candi e Kung 71 77 68 69
ln-Kyung Kim 72 72 72 70
C ri ti e Kerr 69 70 72 75

24. Tabl e 7. 12 cont a ins part of the pay


sche dule for fed era l emp loye es in W
Tab le 7.13 give s the num ber ashi ngto n , D. C.
o f emp loye es in each class ifica tio n in
the d ata fro m the two tables into a rrays a cert ain divisio n . P lace
and co mpu te the a mo unt of mon ey
pays fo r sa la ries duri ng the year. (U se this divi sio n
G S -Pay .txt and G S- Emp loyees. txt.)

lfT1:J!IIfJ 2009 pay schedule for federal white-collar work


ers.
Step
2 3 4
GS-1 17,540 18, 126 18,709 19,290
GS-2 19,72 1 20,1 90
GS -3 20,8 42 21,396
21,5 17 22,23 4
GS-4 22,95 1 23,668
24,156 24,961 25,76 6
GS-5 27,026 26,5 71
27 ,92 7 28,828
GS-6 30, 125 29,729
31) 129 32, 133
GS-7 33,477 33,137
34,593 35,709 36,825

lt4:J!II@I Number of employees in each category.


1 2 3 4
GS-1 0 0 2
GS-2 2 3 0 1
GS-3 4 2 5
GS- 4 12 7
13 8 3
GS-5 4 5 0 1
GS- 6 6 2 4
GS-7 8 3
9 2

25. Con sid er Tabl e 7 .5 , the ra nkin gs of


thre e grad u ate -schoo l prog ra m . Wri
plac es the d a ta in to an a rray, a te a prog ram tha t
llo ws the na me of a univ e rsity to be
cate go ries in whic h it appe a rs. Of cour inpu t, and d isplays the
se, a un ive rsity m igh t appe ar mo re than
a t a ll. (Use R anki ng.t xt.) o nce o r no t
330 • Cha pter 7 Arrays

c ity d urin g a five -yea r


prec ipita tio n fo r a typ ica l N ebra ska
26. Table 7.14 gives the mon thly y and then disp lays
the tab le from a tex t fi le into an arra
peri od. Wri te a prog ram that reads
e Ra in.tx t.)
the outp ut sho wn in Fig. 7. 29. (Us
Nebraska cit~.
IN=I!IIII Monthly Erecipitation (in inches) for a t~Eical
Aug. Sept. Oct. N ov. Dec .
Feb. Mar. Apr. May Jun e July
Jan. 0.77
4. 23 4.3 4 4. 00 2.05 1.48
1.11 2.0 1 3.64 6.44 5.58
1986 0.88 3.72 2.21 1.24 0.80
3.29 4. 68 3.52 3.52 4.82
1987 0.76 0.94 2.09 1.88 1.21 0.61
4.0 1 3.88 3.72 3.78 3.55
1988 0.67 0.80 1.7 5 2.70 1.61 0.75
3.98 4.57 3.43 2.32
0.82 0.80 1.99 3.05 4. 19 4.44 0.92
1989 2.65 2.99 2.55 1.99 1.05
0.90 1.71 2.02 2.33 2.98
1990 0.72

.I
l= I@J I. S'2._

II Prec ipita tion

Average
Display Precipitati on for a Nebraska
City Month Precipitation
---
January 0.77
Tota l - ---
February 0.91
Year Precipitation - -- -
for the Year
-- - - March 1.91
1986 36.53 2.94
~ril - --
1987 131 .59 -- ---
- May 4.33
--
1988 28.56
- - June
--
4.08
- - -
1989 31.95
- - July 3.62
-
1990 22.81 - -
August 4.10
- -
1
September 3.45
- -- -
Octo ber 2.09
- - --
November 1.32 ~

December 10.77

FIGURE 7.29 Outcom e of Exercise 26.


ms are give n dur ing
pose that a cou rse has up to 15 stud ents enro lled and that fiv e exa
27. Sup es as inpu t, places
acce pts eac h stud ent's nam e and grad
the sem este r. Wri te a prog ram that -dim ensi ona l array.
y, and places the grad es in a two
the names in a one -dimens iona l arra . Also, the pro-
stud ent's name and sem este r ave rage
The prog ram sho uld then disp lay each grad es, the med ian
sho uld disp lay the med ian for each exam . (Fo r an odd num ber of
gram of grad es, it i
dle grad e afte r the grad es h ave bee n orde red. Fo r an eve n num ber
is the mid
es. )
the ave rage of the two mid dle grad
row, each co lum n, and
ed a magic square if the sum of each
28. A squa re array of num bers is call re. Wri te a prog ram
sho ws an exa mpl e of a mag ic squa
each diagona l are equal. Figu re 7.30 time one of the
u er is a magic squa re. Hin t: If at any
to dete rmi ne if an array inpu t by the sear ch is com plet e.
s is not equ al to the sum of the num bers in the first row, then the
sum

G~ ~)
FIGURE 7.30 A magic square.
7.4 Two-D imensional Arrays
• 331

29. A company h as three stores (1 , 2, and 3) , and each store sells fiv e items (1, 2, 3, 4, and
5).
The fo llowing tab les give the number of items sold by each store and category o n a
pa rticu-
lar day, and the cost of each item.

(a) Place the data from the left- hand tab le in a two-dim ensio nal array and the
data from
the righ t- hand tab le in a one-d imensio na l array.
(b) Co mpute and display the tota l dollar amount of sales for each sto re and for
the entire
company.

Number of Items Sold During Day


ITEM ITEM COST PER ITEM
1 2 3 4 5 1 $12.00
1 25 64 23 45 14 2 $17.95
Store 2 12 82 19 34 63 3 $95.00
3 54 22 17 43 35 4 $86.50
5 $78.00

Solutions to Practice Problems 7.4

1. Rep lace the masked text boxes with o rdin ary text boxes to ho ld city names.
The fun ction Fi ndC ityNum can be
useJ to dete rmine the subsc ri pt assoc iated with eac h city. This fun ct ion and the
mod ified eve nt procedure
btn how_Ciick are as follows:

Functio n FindCity Num(By Val city As String) As Integer


Select Case city.ToU pper
Case "CHICAGO"
Return 1
Case "LOS ANGELES"
Return 2
Case "NEW YORK"
Return 3
Case "PHILAD ELPHIA"
Return 4
Case Else
Return 0
End Select
End Functio n

Private Sub btnShow Click( ... ) Handles btnShow .Click


Dim orig, dest As St r ing
Dim row, col As Integer 'Determ ine road mileage between cities
orig = txtOrig . Text
dest = txtDest . Text
row = FindCity Num(ori g)
col = FindCity Num(de st)
If (row <> 0) And (col <> 0) Then
txtMile s.Text = CStr(rm (row- 1, col- 1))
Else
Message Box.Sho w("Inco rrect Origin and/o r Dest i nation" , "Error")
End If
End Sub
332 • Chap ter 7 A rrays

me of the data arc


l arrays are used w ho ld re lated data . If so
2. Both arrays of struct ures and two-d ime nsiona of a two-d imens iona l a rray must
must be used, beca use all en tries
nume ri c and so me are st ring, then stru ctures so rted. Two-d imens iona l arrays
a lso be used if the clam will be
be of the sa me type. Array s of struct ures should
are best suited to tab ul ar data.

7.5 A Case Study: Analyze a loan


l
a loan. Assume the loan is to be repaid in equa
This case study develops a program to analyze the
mon thly. The prog ram should req uest
mon thly paym ents and interest is co mpounded h
of interest, and the numb er of years over whic
amou nt (prin cipal ) of the loan, the annu al rate ws:
provided by butto ns are as follo
the loan is to be repaid. The fiv e optio ns to be
is
1. Calc u late the mont hly paym ent. The form ula
p·r
[monthly payment] = - -----
1 - ( 1 +r) - n

thly interest rate (ann ual rate divid ed by


wher e p is the principal of the loan, r is the mon
and 1 (for 100 perce nt), and n is the num -
12) given as a numb er betw een 0 (for 0 pe rcent )
d . Wh en a paym ent comp uted in this man-
ber of mon ths over whic h the loan is to be repai
ould be roun ded up to the next neare st cent .
ner results in fract ions of a cent, the va lue sh
the formu la
This corre cted paym ent can be ach ieved using
ayme nt + o. 005, 2)
[corrected payment] = Math. Roun d (orig inalP
of
a table showing for each mon th the amou nt
2. Disp lay an amorti zatio n schedule- that is,
and the balan ce on the loan at the end of the
inter est paid , the amou nt of princ ipal repa id ,
is the amou n t of mon ey that must be paid in
mon th. At any time, the balan ce of the loa n
consists of two part s-int eres t on the bal-
order to retire the loa n . The mon thly paym ent
mon th
ance and repay ment of part of the principal. Each
of mont h]
[inte rest payment] = r * [balance at begin ning
ent] - [inte rest paym ent]
[amo unt of princ ipal repaid] = [mon thly paym
h] - [amo unt of princ ipal repaid]
[new balan ce] = [bala nce at begin ning of mont
yea r. (This amou nt is dedu ctibl e when itemi z-
3. Ca lcula te the interest paid durin g a calend ar
The user should spec ify the num ber of the
ing dedu ction s on a Fede ral income tax retur n.)
nce, if the first paym ent was made in Sep-
payment made in Janu a ry of that year. For insta
ary 2010 wou ld be paym ent numb er 5.
temb er 2009, then the paymen t made in Janu
Disp lay a tab le giv ing the mont hly paym ent
4. Show the effect of chan ges in the interest rate.
e the spec ified annu al rate in steps of one-
for each interest rate from 1% be low to 1% abov
eigh th of 1%.
5. Q uit.

The User Interface


Table 7.15 gives the initia l settin gs for the form
Figure 7.3 1 shows a possible fo rm design and
7.35 show possible outp uts of the program~ r
and its cont rols. Figur es 7.32, 7.33, 7.34, and
each task ava ilable through the butto ns.

Designing the Analyze-a-Loan Program


s. Therefore, we creat e a Sub proce dure to read
Every routi ne uses data from the th ree text boxe
cont ents into a usab le form. Two of the routi nes
the cont ents of the text boxes and conv ert the
A Case Study: Ana lyze a Loa n
7.5
• 333

a ~ Analyze a Loan
~0000
.Amount of loan: 250000

Interest rate : 5

Number of loan years : 30

Calculate Monthly Payment

Display .Amortization Schedule

Show Interest Paid for One Year

Display Interest Rate Change Table

[ Qutt
I
- -
FIGURE 7.31 Temp late for the Analyze-a-Loan program.

lfi':JIU.J Objects and initial properties for the Analyze-a-loan progr


am.
Obje ct Prop erty Setting
frmLoan Text Ana lys is of a Loan
lblPrincipa l Tex t Amo unt of loa n:
txtPrincipa l
lblYearlyRate Tex t Interest rate:
txtYearlyR ate
lblNum Years Text Nu mber of loa n yea rs:
txtN umYears
btnPayment Text Ca lculate Mont hly Payment
btnA.mort Text Di play A morti zation Schedu le
btnShow Text Show Interest Paid for O ne Year
btnRateTable Tex t Disp lay Interest Rate C hange Tab le
btnQ uit Text Qu it
dgvOutput Row HeaderVisible False

d isp lay exten sive table s in a Oata G ridVi ew


cont ro l. The simp lest way to fi ll a tab le is to
array of struc tures and a LINQ query. We use a n
will n eed two types of struc tures -on e (na
Mon th) to h o ld the a mo rtizat ion data for a med
mon th and the othe r (nam ed Effec tOfR ate)
mon th ly paym e nts fo r diffe rent inte rest rates. to ho ld
S ince the a rray of Mon th stru ctu res is n eede
two routi nes, we use a Func tio n proce dure d by
to fill it so we won' t h ave to dupl icate
code . S ince the va lue of the mon thly paym the lengt hy
ent is n eede d sever a l times, we inclu de a Func
proce dure calle d Paym e nt. tio n
334 • Cha pter 7 Arrays

I= @] ~
u.. Analyze a loan

Amount of loan: 250000

Interest rate: 5
-
Number of loan years : 30

Calculate Monthly Paymer~


I Payment
lt: £j ::]

Mont hly paym ent: 51,342.06


Display Amortization Sched ule
J

I OK ]
Show Interest Paid for One Year I
Display Interest Rate Cl'tange Table I
[
Qu~

I
FIGURE 7.32 Mon thly paym ent for a loan.

D Analyze a loan

Amour« Paid Balance at


Amour~ Paid
Amour~ of loan: 2::.0000 Mor~h for Princ:ipal End of Mordh
forlr~ere~d

lrderest rate : 5 S1.&1 .67 S300. 39 S2"9.6S9.61

S1.& 0.42 301.64 S249,397.96


2
Number of loan years : 30
S1 .039.16 2.90 !'249,05 .06
J
S1.037.90 SJ .16 !'248.790.90
4
Calculate Monthly Pa:,'ITter~
S1 .036.G3 ' 0 .43 S248.4.&5.46
5
S1 .035.36 S306.70 !.'-248.17B.76
6
Sl .03408 '07.98 S247.870 78
7
Dtsplay nnortization Schedule Sl .032.79 S309.27 S2"7.561 51
8
Sl ,031 .51 S310. 55 S2"7. 250.96
9
Sl ,0'' 0.21 '311 .8 S2..!6,939.11
10
Show lrdere~1 Paid for One Year S313.l5 $246 .625.97
11 S'l.028 91
S1. 27.61 -:{14.45 1'246.''11 . 1
12
S315 .76 S2A5 ,995.7.
13 Sl.026.30
Display lrdere~1 Rate Cl'tang e Table $1,024 .98 - 17.08 ~QA5 , 678 . 67
14
$1,023.66 $318.40 S245 .3 0.28
15
S1.022.33 '319.73 S245 . 0.55
16
Quit S2"~ . 719.49
17 $1,021 .00 S321.06

FIGURE 7.33 A mor tization schedule for a loan .


7.5 A Case Study: A nalyze a Loan
• 335

a.. Analyze a l oan ~ j

Amount of loan: 250000

Interest rate : 5

Number of loan years: 30

l Calculate Monthly Payment


J
Interest For Year

l Display Amortization Schedule


J Interest Paid for y ear beginning with month 7: S12,323.06

l Show Interest Paid for One Year I OK

l Display Interest Rate Olange Table I


Quit

FIGURE 7.34 Interes t paid during one yea r.

a.. Analyze a loan


l = I @] h. ..n. .I

Amount of loan: 250000


Interest Rate Monthly
Payment
.
Interest rate : 5
4000%
- '--~

I51.193.54
Number of loan years : 30 4.125% 51 .211 .63
--
4.250~~
- --
51.229.85

l
4 . 375~~ 51.248.22
Calculate Monthly Payment
-
4.500~~ 51 .266.72
4.625~.
-
51.285.35
4 . 750~~ 51.304.12
Display Amortization Schedule
l 4.875%
-
-
51.323.03
-
-- -
5.000% 51.342.06
- -
l Show Interest Paid for One Year
5. 125 ~~

5.250"1~
-
51.361 .22
---
51 .380.51
- --
IDisplay Interest Rate Olange Table
5.375%
5 . 500~~

5 625~~
- -
T
51.399.93
51.419.48
51.439.15
-

5 . 750~.
- - -
51.458.94
- --
5. 875~~ 51.478.85
! Quit
I 6000%
- -
51.498.88 -....

FIGURE 7.35 Conse quences of interes t rate change .


336 • Chapter 7 Arrays

The program is d ivided into the fo llowi ng tasks:

1. Calcu late and display the mont h ly payment.


sched ule.
2. Calcu late and display a complete amortiza tion
specified one-year period.
3. Calcu late and display the intere st paid durin g a
t of different interest rates on the mont hly
4. Calcu late and disp lay a tab le showing the effec
payment.
5. Quit.

Let's consi der these tasks one at a time.

1. Calcu late and display the mont hly paym ent.


of the loan.
1.1 Input the princ ipal, intere st ra te, and durat ion
.
1.2 Apply the funct ion Payment and disp lay its value
2. Displ ay a comp lete amor tization sched ule.
of the loan.
2.1 Input the principal, interest rate, and durat ion
elements with type Mon th.
2.2 Assign va lues to each elem ent of the array of
2.2.1 Deter mine the mont hly payment.
of the payment into interest pay-
2.2.2 For each mont h, deter mine the appo rtion ment
mine the balan ce at the end
ment and amou nt of principal repaid , and then deter
mont h is the same as the bal-
of the mont h. The balance at the beginning of each
for the first mont h whe re the
ance at the end of the prev ious mont h, excep t
calculated with th e three fo r-
begi nning ba lance is the princ ipal. These va lues are
last mont h. Due to round ing,
mulas presented earlie r, with the excep tion of the
the prev ious payments. The
the last mont hly payment will be slight ly less than
as for the prev ious mont hs.
interest for the last mont h is calculated the same way
the balan ce at the begin ning
However, the amou nt of princ ipal repaid wi ll equal
the last mont h will be 0.
of the mont h. That way, the ba lance at the end of
array of Mon th elements.
2.3 Declare a LINQ query to hold the va lue in the
l.
2.4 Use the query to fill the DataG ridVi ew contro
2.5 Spec ify heade rs for the table.
a specified one-y ear perio d.
3. Calcu late and displa y the interest paid durin g
of the loan.
3.1 Input the principal, intere t rate, and durat ion
of elements with type Mont h. (See the
3.2 Assign va lues to each eleme nt of the array
details in 2.2 above.)
3.3 Request the numb er of the begin ning mont h.
to the interest paym ents for the twelve
3.4 Declare a LINQ query to limi t considerat ion
mont hs begin ning with the requested mont h.
of the interest paym ents for the year.
3.5 Use the query's Sum meth od to comp ute the total
effec t of diffe rent inter est rates on the
4. Calcu late and display a table show ing the
by one perce ntage point and the new
mont hly paym ent. First, the intere st rate is red uced
rate is increased by regul ar incre ment s
monthly pay ment is computed. Then the interest
al rate, with new mont hly payment
until it reaches one perce ntage point above the origin
rate. The subtasks for this task are then as
amou nts co mput ed for each interm ed iate interest
follows:
of the loan.
4.1 Input the princ ipal, interest rate, and durat ion
7.5 A Case Stud y: Ana lyze a Loa n
• 337

4. 2 Assign values to each elemen t of the array of elemen ts with type


EffectOfRate.
4.2.1 Reduce the interes t rate from the text box by 1%.
4.2.2 Calcul ate the new month ly payme nt and place the interes
t rate and payme nt
in to an elemen t of the array of type EffectOfRate.
4.2.3 Increase the interes t rate by 1/8 of 1%.
4. 2.4 Repeat until the interes t rate is 1% percen t above the interes
t rat in the text
box.
4.3 Declare a LINQ query to hold the va lues in the array of EffectO
fRate elemen ts.
4.4 Use the query to fill the DataG ridView contro l.
4.5 Specify headers for the table.
5. Quit. End the program.
The hierarc hy chart in Figure 7.36 shows the stepw ise refinem ent
for second, third, and
fourth tasks.

Analyze a Loan

Calculate Display Calculate Show effect Quit


monthly amortization interest for of interest rate
payment table one year changes

Assign Assign Specify Assign Assign Request Speficy Assign Assign Specify
values values to query values values to number of query values values to query
from elements & fill from elements beginning & show from elements & fill
text of array DGV text of array month Sum text of array of DGV
boxes of Months boxes of Months boxes EffectOfR ates

Calculate Calculate Set Compute Increase


monthly amortization interest new monthly interest
payment data for each month
rate lower payment rate
FIGURE 7.36 Hierarc hy chart for the Analyz e-a-Loa n program .

Pseudocode for the Analyze-a-loan Program


Calculate Monthly Payment button :
INPUT LOAN DATA (Sub procedure InputD ata)
COMP UTE MONT HLY PAYMENT (Function Payme nt)
DISPLAY MONT HLY PAYMENT
Display Amortization Schedule button:
INPUT LOAN DATA (Sub procedure InputData)
ASSIG N VALUES TO EACH MONT H IN ARRAY OF MONT
HS (Sub procedure
Gen.er ateMon thsArr ay)
DEFINE QUER Y TO HOLD DATA FROM ARRAY OF MONT HS
DISPLAY AMOR TIZAT ION SCHE DULE
Show Interest Paid in One Year button:
INPUT THE NUMB ER OF THE BEG INN ING MONT H
INPUT LOAN DATA (Sub procedure InputD ata)
338 • Chapter 7 Arrays

THS (Sub procedure Gen-


ASSIGN VALUES TO EACH MONTH IN ARRAY OF MON
erateMonthsA rray )
Y OF MONTHS
DEFINE QUERY TO HOLD RELEVANT DATA FROM ARRA
EVALUATE SUM OF QUERY AND DISPLAY
Display Interest Rate Change Table button:
INPUT LOAN DATA (Sub proced ure InputData)
Y OF EffectOfRates
ASSIGN VALUES TO EACH INTEREST RATE IN ARRA
Y OF EffectOfRates
DEFINE QUERY TO HOLD RELEVANT DATA FROM ARRA
DISPLAY INTEREST RATE CHANGE TABLE

The Analyze-a-Loan Program


Struc ture Month
Dim numbe r As Integ er
Dim inter estPa id As Doub le
Dim princ ipalP aid As Doub le
Dim endB alanc e As Doub le
End Struc ture

Struc ture Effec tOfR ate


Dim inter estR ate As Doub le
Dim month lyPay ment As Doub le
End Struc ture

les btnPa ymen t.Clic k


Priva te Sub btnPa ymen t_C lick( .. . ) Hand
loan
Dim princ ipal As Doub le 'Amou nt of the
yRat e As Doub le 'Annu al rate of inter est
Dim yearl
s to repay loan
Dim numM onths As Integ er 'Numb er of month
onths )
Inpu tData (prin cipal , yearl yRat e, numM
Dim mont hlyRa te As Doub le = yearl yRat e
I 12
Dim month lyPay ment As Doub le
'Calc ulate mont hly paym ent
hlyRa te, numM onths)
month lyPay ment = Paym ent(p r i ncipa l, mont
'Disp lay resu lts
Form atCur rency (mon thlyP ayme nt, 2),
Messa geBox .Show ( "Mon thly paym ent: " &
"Paym ent" )
End Sub

btnA mort. Click


Priva te Sub btnAm ort_ Click ( ... ) Hand les
'Amou nt of the loan
Dim princ ipal As Doub le
'Annu al rate of inter est
Dim yearl yRat e As Doub le
er of month s to repay loan
Dim numM onths As Integ er 'Numb
e, numM onths)
Inpu t Data (prin cipal , yearl yRat
Dim month s(num Month s - 1) As Month
Dim mont hlyRa te As Doub le = yearl yRat e
I 12
le = Paym ent(p rincip al, mont hlyRa te, numM onths)
Dim month ly Paym ent As Doub
mont hlyRa te, numM onths)
month s = Gene rateM onths Array (prin c ipal,
Dim query = From mnth In month s
Let num = mnth . numb er
estPa id)
Let inter est = Form atCur rency (mnth .inter
h.pri ncipa lPaid )
Let prin = Forma tCurr ency (mnt
mnth . endB alanc e)
Let bal = Forma tCurr ency(
Selec t num , in t erest , prin, bal
7.5 A ase Study: A nalyze a Loa n
• 339

dgvR esul ts.D ataS ourc e = quer y.To


List
dgvR esul ts.C urre ntCe ll = Noth ing
dgvR esult s.Co lumn s( "num " ) . Head erTe
xt = "Mon th"
dgvR esult s.Co lumn s( "int eres t" ) . Head
erTe xt = "Amo unt Paid for Inte rest
dgvR esult s.Co lumn s( "prin " ) .Hea derT "
ext = "Amo unt Paid for Prin cipa l"
dgvR esul ts . Colu mns( "bal " ) .Hea derT
ext = "Bal ance at End of Mont h"
End Sub

Priv ate Sub btnS how Clic k( ... ) Hand


les btnS how .Clic k
Dim prin cipa l As Doub le 'Amo unt of loan
Dim year lyRa te As Doub le 'Ann ual
rate of inte rest
Dim numM onths As Inte ger 'Num ber
of mont hs to repa y loan
Inpu tDat a(pr inci pal, year lyRa te,
numM onths )
Dim mont hs(nu mMo nths - 1) As Mont
h
Dim mon thlyR ate As Doub le = year
lyRa te I 12
Dim mont hlyP ayme nt As Doub le = Paym
ent(p rinci pal, mon thlyR ate, numM
mont hs = Gene rateM onth sArr ay (prin onths )
cipa l, mon thlyR ate, numM onths )
Dim begi nnin gMo nth As Inte ger =
Cint (Inpu tBox ( "Ent er begi nnin g mont
Dim quer y = From mont h In mont hs h: " ))
Wher e (mon th.nu mber >= begin ning Mon
th) And
(mon th . numb er < begi nnin gMo nth +
12)
Sele ct mon th.in tere stPa id
Mess ageB ox .Show { "Int eres t paid for
year begi nnin g with mont h " &
begi nnin gMo nth & ": " & Form atCu
rrenc y{qu ery . Sum) ,
"Int eres t For Year " )
End Sub

Priv ate Sub btnR ateT able _ Clic k{ ...


) Hand les btnR ateT able . Clic k
Dim prin cipa l As Doub le 'Amo unt of loan
Dim year lyRa te As Doub le 'Ann ual
rate of inte rest
Dim numM onths As Inte ger 'Num ber
of mont hs to repa y loan
Inpu tDat a{pr incip al , year lyRa te,
numM onths )
Dim rate s{l6 ) As Effe ctOf Rate
Dim mon thlyR ate As Doub le = year
lyRa te I 12
'Dim mont hlyP ayme nt As Doub le =
Paym ent(p rinci pal, mon thlyR ate,
'Fil l rate s arra y numM onths )
For i As Inte ger = 0 To 16
rate s(i ) . inte rest Rate = (yea rlyR
ate- 0 . 01) + i * 0.00 125
rate s(i) .mon thlyP ayme nt Paym ent(p rinci pal,
rate s(i) .inte rest Rate I 12, numM
Next onths )
Dim quer y From rate In rate s
Let annu alRa te = Form atPe rcen t(rat
e.int eres tRat e, 3)
Let mont hlyP ayme nt = Form atCu rrenc
y(rat e.mo nthly Paym ent)
Sele ct annu alRa te , mont hlyP ayme nt
dgvR esul ts.D ataS ourc e = quer y.To
List
dgvR esul ts.C urre ntCe ll = Noth ing
dgvR esult s.Co lumn s( "ann ualR ate" )
.Hea derT ext = "Int eres t Rate "
dgvR esult s.Co lumn s( "mon thlyP ayme
nt" ) . Head erTe xt = "Mon thly Paym ent"
End Sub

Priv ate Sub btnQ uit_ Clic k( ... ) Hand


les btnQ uit . Clic k
Me .Clo se {)
End Sub
340 • Cha pter 7 Arrays

l As Dou ble ,
Sub Inpu tDa ta( ByR ef prin cipa
ByR ef num Mon ths As Inte ger )
ByR ef year lyR a te As Dou ble ,
of inte rest , and dur atio n
'Inp ut loan amo unt, yea rly rate
, num Year s As Inte ger
Dim perc enta geR ate As Dou ble
l .Tex t)
prin cip al= CDb l (txt Prin cipa
lyR ate. Tex t)
perc enta geR ate = CDb l (txtY ear mal form
I 100 'Con vert inte rest rate to deci
yea rlyR ate = perc enta geR ate
t)
num Year s = Cin t (txtN umY ears .Tex
Year s * 12 'Du rati on of loan in mon ths
num Mon ths = num
End Sub
As Dou ble ,
a l As Dou ble , ByV al mon thly Rate
Fun ctio n Paym ent( ByV al prin cip Dou ble
ByV al numM ont h s As Dou ble ) As
'Est ima te of mon thly paym ent
Dim esti mat e As Dou ble onth s))
yRa te I (1- (1 + mon thly Rate ) A (-nu mM
esti mat e= prin cip al* mon thl
e are frac tion s of a cen t
'Rou nd the paym ent up if ther
i mat e, 2) Then
If esti mat e = Math .Rou nd(e st
Retu rn esti mat e
Else
0.00 5, 2)
Retu rn Math .Rou nd(e stim ate +
End If
End Fun ctio n

ByV al prin cipa l As Dou ble ,


Fun ctio n Gen erat eMo nths Arra y(
ByV al mon thly Rate As Dou ble ,
As Mon th ()
ByV al num Mon ths As Inte ger )
Mon th
Dim mon ths(n umM onth s - 1) As
'Fil l the mon ths arra y
, num Mon ths)
Pay men t(pr inci pal, mon thly Rate
Dim mon thly Paym ent As Dou ble
th
'Ass ign valu es for firs t mon
mon ths(O ) .num ber= 1
thly Rate * prin cipa l
mon ths(O ) .int eres tPa id = mon stP aid
thly Pay men t- mon ths(O ) .int ere
mon ths(O ) .pri ncip alPa id = mon alPa id
ipa l - mon ths(O ) .pri ncip
mon ths(O ) .end Bala nce =pr inc
inte rior mon ths
'Ass~gn valu es for
= 1 To num Mon ths - 2
For i As Inte ger
mon ths( i) . num ber= i + 1
alan ce
thly Rate * mon ths( i - 1) . endB
mon ths( i) .int eres tPa id = mon i) . inte rest Pai d
thly Paym ent - mon ths(
mon ths( i) .pri ncip alPa id = mon e- mon ths( i) .pri ncip alPa i d
s(i - 1) .end Bal anc
mon ths( i) . endB alan ce = mo nth
Nex t
'Ass ign valu es for last mon th
mon ths(n umM onth s 1) .num ber= num Mon ths
*
mon ths(n umM onth s 1) .int e rest Paid = mon thly Rate
nce
mon ths(n umM onth s - 2) .end Bala
.end Bala nce
1) .pri nc ipal Paid mon ths(n umM onth s - 2)
mon ths(n umM onth s
mon ths(n umM onth s 1) .endBala nce = 0
Retu rn mon ths
End Fun ctio n

CHAPTER 7 SUMMARY
an array.
are m t effic ientl y proces ed if stored in
1. For prog ramm ing purposes, lists of data al va lues .
t, whic h also can spec ify its size and initi
A n array is decl ared with a Dim state men or ReDim
n be spec ified or chan ged with a ReDim
The size of an alrea dy declared array ca
Progra mming Projects
• 34 1

Preserve statem ent. The metho ds Count, First, Last, Max, and
Min return the size of the
array, first eleme nt, last eleme nt, largest eleme nt, and sma
llest eleme nt, re pectiv e ly. Fo r
numeric arrays, the metho ds Average and Sum retu rn the
average and total of the n umbers
in the array.
2. The lO. File.ReadAllLines metho d return s a string array
conta in ing the conten ts of a fi le.
3. The Split metho d conve rts a line consisting of strings
separa ted by a delim iter (usua ll y a
comm a or a blank space ) to a str ing array. T he join functi on
is its inverse.
4. A For Each loop repeat s a group of statem ents fo r each
eleme nt in an array.
5. U NQ is a powerful M icroso ft techno logy that provid es a stand
ardized way to set criteri a for
info rmatio n retriev a l fro m data o urces, includ ing arrays.
Ope rators such as Fmm, Where,
Distinct, Order By, Let, and Select are used to crea te a query express
ion th at can retriev e a list
of info rmatio n from the data so urce . When each eleme nt
of t he list is a single value, the
ToArray method conve rts the list to an array. UNQ prov ides
an easy way to sort the con -
tents of an array.

6. The DataS ource proper ty can be used to d isplay the sequ


ence return ed by a query. If the
Select clause conta ins a single exp ress io n, a state ment of
the fo rm
lstOu tput . DataS ourc e = query .ToLi st

displays the sequ ence in a list box. If the se lect clause conta
ins two o r more express ions, a
sta temen t of the fo rm

d gvOut put. DataS o u r c e = query . ToLis t

disp lays the inform at ion return ed by the query as a table in


a DataG ridVie w contro l.
7. The binary search metho d prov ides an effic ient way to look
for an eleme nt of an ord ered
array.

8. A structure is a compos ite progra mmer-design ed data type


with a fi xed numbe r of memb ers,
each of which can be of any data type. LINQ ca n be u ed
to ort and ar h stru ctures anJ
to create new stru ctures of anonymous data types.

9. A table can be effective ly sto red and accessed in a two-di


mensional array .

CHAPTER 7 PROGRAMMING PROJECTS


1. Table 7.16 conta ins some length s in terms of feet. Wr ite
a progra m th at displays the nine
differe nt units of measure; req uests the un it to conve rt from,
the un it to conve rt to, and the
quanti ty to be conve rted; and then d isplays the conve rted
quant ity. A typica l o utco me is
shown in Fig. 7.3 7 on the nex t page.

lf4:J!UIJ Equivalent lengths.


1 inch = .0833 foot 1 rod = 16.5 feet
1 yard = 3 feet 1 furlong = 660 feet
1 meter = 3.28155 feet 1 kilometer = 328 1.5 feet
1 fat hom = 6 feet 1 mile = 5280 feet
342 • Chap ter 7 Arrays

c... Unit Co versio n

1. inch Length to convert : 2


2. fathom
Original units (1-9): 7
1 foot
14.furlong Desired units (1-9): 3
5. kilometer
6. meter
?. mile Convert
B. rod
S. yard Desire d length :

FIGURE 7.37 Possi ble outco me of Progr ammi ng Proj ect 1.

devia tion to descr ibe a co llect io n of


2. Stati stic ian s use the conc epts of mean and stand ard
rd devia tion meas ures the
data. The mean is the ave rage va lu e of the items , and the stand a
n. Fo rma lly, if x 1, Xz , x3, . . . , xn, is a co l-
sp read o r dispe rsal of the numb e rs abo ut the mea
lectio n of data, then
XI + Xz + X] + .. · + Xn
1nean = m = n

a nd stand ard devia tio n =


2
=
2 2
~ (x 1 - m) + (x z - m) + (:3 - m) 2 + · · · + (xn - m)
5

first fo ur lines of the file h o ld the numb er


The file Score s.txt conta ins exam scores. The
mea n a nd stand ard devia tion of the
59, 60, 65, and 75. Write a program to ca lcula te the
score , ES, as foll o ws, and then display a list
exam scores, ass ign letter grade s to each exam
ing grades, as sho wn in Fig. 7.38.
of the exam score s a long with their corre spond
ES ;::: m + l.Ss A
m + .Ss :s ES < m + l.Ss B
m - .Ss :s ES < m + .Ss C
m - l .Ss :s ES < m - .Ss D
ES < m - l.Ss F
grade s of 88 o r abov e would rece ive A's,
For insta nce, if m were 70 and s were 12, then
so o n . A process of this type is referr ed to
grade s betw een 76 and 87 would rece ive B's, and
as curvin g grades .
sh word s a nd the ir Fren ch and Germ an
3. Rudimentary Translator. Table 7.17 giv es Engli
to the fi le O ic tio n a ry. txt. The first two lines
equ iva lents. These words h a ve been place d in
of the fi le a re
YES, OUI,J A
TABL E, TABL E, TISCH
nce as input a nd tran slates it into Frenc h
Write a progra m that requests an Engli sh sente
n in th e Engli h se nten ce is a perio d a t the
and Ge rman. Assu me that the o nly punc tu at io
t in th dict i n a ry, it sh o uld
nd f th. nt n e. (Note: If a word in the nt n ee i n
lat io ns. This will a llo w prope r noun s to be
appea r as itself in the Frenc h and Germ an trans
tran lated corre ctly.) See Fig. 7.39.
Prog ramm ing Proj ects
• 343

a~ Curving Grades l = l @) l~~

[ Analyze Grades
I Score
- --
Grade
-
59 D
Number of Exams : - - -
14 :00 D
-
Mean : 71.00 65 c
-
- -- - - -
Standard Deviation : 1 .42 75 Tc
-
~6 D
-- ---
50 B
- ---
66 c
-
47 F
-- ---
9& A
-
:72 c
- --
95 JA
-
71 c
- -
63 D
- - -
77 c

FIGURE 7.38 Outp ut of Programm ing Proj ect 2.

English words and their French and German equivalent


s.
English Fren ch Germ an English Fren ch Germ an
YES our ]A LARGE GROS GROSS
TABLE TABLE TI CH NO NON NEIN
THE LA DEM HAT CHAPEAU HUT
IS EST IST PENCIL CRAYON BLEISTIIT
YELLOW JAU NE GELB RED ROUGE ROT
FRIEND AMI FREUND ON SUR AUF
SICK MALADE KRANK AUTO AUTO AUTO
MY MON MEIN OFfE N SOUVENT OFf

aj Rud imen tary Trans lator

English Sentence : My pencil is on the table .

Translate Sentence

French Sentence : MON CRAYON EST SUR


LA TABLE.

Gennan Sentence: MEIN BLEISTIFT 1ST AUF


OEM TISCH .

FIGURE 7.39 Poss ible outc ome of Prog ramm ing Proje ct
3.
344 • Cha pter 7 Arrays

200 6 in ce rta in
e lo r degrees con ferred in 198 1 and
4. Tab le 7.18 shows the num ber of bach ch ange and a hist ogra m of 2006
les 7. 19 and 7.20 show the percentage
fields of stud y. Tab of these tab les
that allows the user to di p lay any one
leve ls, resp ective ly. Wri te a progra m lly by fi e ld of
on. Tab le 7.18 is ord ered alph abet ica
as an opti o n and to quit as a fo urth opti ered by increas-
ing perc entages, and Tab le 7. 20 is o rd
study, Table 7.19 is orde red by decreas
is a large dot.
ing num be r of degrees. Not e: C hr(l 49)

IM:Jifll:l Bachelor degrees conferred in certain fields.


1981 200 6
Field of Stud y
200,52 1 3 18,042
Bus iness 47,4 80
15,12 1
Com pu ter and info. sc ience 107, 238
108,074
Ed ucat ion 67,0 45
63 ,642
Engineering 161,485
100,513
Soc ial sc iences and history
ion S tatisti cs.
Source: U.S. Nat iona l Cen ter of Ed ucat

erred.
IM:JIUQI Percentage change in bachelor degrees conf
%C hange (198 1 - 200 6 )
Field of Stud y
214. 0%
Com pute r and info. sc ienc e
60.7 %
Socia l scien ces and hi to ry 58 .6%
Business 5.3%
Engineer ing -0.8 %
Education

fields.
1t!1:Jifll•l Bachelor degrees conferred in 2006 in certain
Field of Stud y
• • • • • 47,4 80
Com p uter and info. sc ience
• • • • • • • 67,0 45
Engineer ing
• • • • • • • • • • • 107,238
Ed ucat ion
• • • • • • • • • • • • • • • • 161,485
Soci a l sc iences and history ••• ••• • 3 18,042
••• ••• ••• ••• ••• ••• ••• ••• •••
Bu ines

le 7.2 1 hows the


ue played each othe r tea m onc e. Tab
5. Each team in a six- team socc er leag
wi nne rs. Wri te a prog ram to
ber of win s.
(a) Plac e the team nam e in an arra
y of st ructu res that also hold s the num
a two -dim ensiona l array.
(b) Plac e the data from Tab le 7.2 1 in

lt!1:Jif1JI Soccer league winners.


Owls R ams C u bs Zips
Jazz Jets

Jazz Jazz Rams C ubs Jazz


Jazz
Jets Jets C ubs Zips
Jets Jazz
Rams Ow ls Ow ls
Owls Jazz Jets
Rams Rams Rams
Ra m Ram Jets
O wls Rams ub
C ubs C ubs C ubs
Zi ps O wls Rams C ubs
Zip Jazz
Programmi ng Projects • 345

(c) Place the number of gan1es won by each team in the array of structures.
(d) Display a listing of the tea ms giving each tea m's name and number of games won. The
list should be in decreasing ord er by the number of wins.
G. A poker hand can be sto red in a two-dimen sional array. The statement
Dim hand(3, 12) As Integer

declares an array with 52 elements, where th e fir t subscript ranges over the four suits and
the second subscript ranges over the thirteen denomina tions. A poker hand is specified by
plac ing l's in the eleme nts co rre ponding to the cards in the hand. S e Figure 7.40.

A 2 3 4 5 6 7 8 9 10 Q K

Club "- 0 0 0 0 0 0 0 0 1 0 0 0 0

Diamond+ 1 0 0 0 0 0 0 0 0 0 0 0 0

Heart¥ 1 0 0 0 0 0 0 0 0 0 0 1 0

Spade • 0 0 0 0 1 0 0 0 0 0 0 0 0

FIGURE 7.40 Array for the poker hand A 'I A + 5 ill 9 "- Q 'I.

Write a program that requests the five cards as input from the user, creates the related
array, and passes the array to procedures to determine the type of the hand: flush (all ca rds
have the sa me suit) , straight (cards have consec utive denom inations-a ce can co me either
before 2 or after King), traight flu sh , four-of- a- kind , fu ll house (three ca rd of one denom-
ination, two ca rd s of another denom inat ion) , three-of-a- kind , two pairs, one pair, or none
of the above.

7. Airline Reservations. Write a reservation yste m for an airline flight. Assume the airplane
has 10 rows with 4 seats in each row. Use a two-dimen siona l array of strings to maintain a
seating chart. In adJ it ion, create an array to be used as a waiting list in case the plane is fu ll.
The wa it ing list should be "first come, first se rved"; that is, people who are added ea rly to
the list get priori ty over tho e added later. A llow the user the fo llowing three options:
(a) Add a passenger to the flight or waiting list.
1. Request the passenger's name.
2. Di play a chart of the seats in the airplane in tabular form .
3. If sea ts are ava ilab le, let the passenger choose a seat. Add the passenger to the seat-
ing chart.
4. If no sea ts are ava ilab le, place the passe nge r on the wait ing list.
(b) Remove a passenger from the fli ght.
1. Request the passenger's name.
2. Sea rch the seating chart for the passenger's name and delete it.
3. If the wait ing list is empty, update the array so the seat is ava ilable.
4. If the wa iting list is not empty, remove the first person from the list, and give him or
her the newly vacated seat.
(c) Q uit.
346 • Chapter 7 Array

laws for birth,


8. The Ga me of Life was invented by John H . Conway to model some natural
array of sq uares. Each
death, and surviva l. Consid er a checkerboard consisting of an n-by-n
(d enoted by - ).
square ca n contain one indi vid ua l (d enoted by 1) o r be empty
future of each
Figu re 7.41(a) shows a 6-by-6 board with four of the sq uares occ upied. The
period of time, called a
indi vidua l depends on the number of his neighbo rs. After each
or over-
generation, ce rta in indi viduals will survive, others will die due to e ither lone liness
ight neighbo ring
crowd ing, and new individu als will be born. Each nonbo rd er square has e
squares. After each generat ion, the status of the squares changes as follows:
ring squares.
(a) An individu al survives if there are two o r three individu a ls in neighbo
in neighbo ring
(b) An individu a l dies if he has more than three individu als or less than two
squa res.
indi vidua ls as
(c) A new individu al is born into each empty square that has exactly three
ne ighbo rs.

(a) (b)

FIGURE 7.41 Two generati ons.

the following:
Figure 7.41(b) sh ows the status after one generation. Write a program to do
to h old the
1. Declare a two-dim ensiona l array of size n by n, where n is input by the user,
configu ration,
status of each squ are in the current generation. To specify the initial
1's or dashes
h ave the user input each row as a string of length n, and break the row into
with the S ubstring method.
square in the
2. Declare a two-dim ensiona l array of size n by n to hold the status of each
and produce the display in
n ext generat ion. Compu te th e status for each square
cells are used
Figure 7.41(b) . Note: The generat ion changes all at once. Only current
to determi ne which cells will contain individu als in the next gen eration.
as often as
3. Assign the next-ge neration values to the current generat ion and repeat
desired.
the program is
4. Display the individu als in each generation. (Hint: The h ardest part of
cell has. In general , you must ch eck a 3-by-3
determi ning the number of neighbo rs a
be made when the cell is on the
square around the cell in q ues tio n. Excepti ons must
edge of the array. Don't forget that a cell is not a ne ighbo r of itse lf.)
(Test the program with the in itial configurat ion show n in Figure 7 .42. It
is known a the
figure-e ight configurat ion and repeats afte r e ight generat ions.)
Numbe r (ISBN) ,
9. Every book is identifi ed by a ten-ch arac ter Interna tional Stand ard Book
the book. The first nine ch aracte rs are d igits
which is usually printed on the back cove r of
stands for ten). Three exam-
and the last charact er is e ither a digit or the letter X (which
hyphen sepa-
s
ples of ISBNs are 0-13-03 065 7-6, 0-32- 108599-X, and 0-471-5 8719-2. The
single digit and
rate the charact e rs into four blocks. The first block usually consists of a
, etc. ). The second block
identifi e the language (0 for English , 2 for French , 3 for German
Progra mming Projects
• 347

FIGURE 7.42 The figure eight.

identif ies the publis her (for exa mple, 13 for Prenti ce Hall,
32 fo r Addison -Wes ley-Lo ng-
man , and 471 for Wiley ). The third block is the numb er the
publ ish er has ch ose n fo r the
book. The fourth block, which always consists of a single charac
ter called the check digit, is
used to test for erro rs. Let's refer to the ten
charac ters of the ISBN as
d 1, d 2, d3 , d4 , d5 , d6, d 7, d8 , d9, and d . The check digit is chose
10 n so that the sum

is a multip le of 11. (Note : A numbe r is a multip le of 11 if it


is exactl y divisib le by 11.) If the
last charac ter of the IS BN is an X, t hen in the sum (*), d
10 is replac ed with 10. For exa m-
ple, with the ISBN 0-32-1 08599 -X, the sum wou ld be

10.0 + 9. 3 + 8 . 2 + 7. 1 + 6 . 0 + 5. 8 + 4. 5
+ 3 ·9 + 2 · 9 + 1·10 = 165
S ince 165/11 is 15, the sum is a multiple of 11. This check ing
scheme will detect eve ry single-
digit and transposition-of-adjacent-digits error. That is, if while
copying an IBSN numbe r you
miscopy a single charac ter or transpose two adj acent charac
ters, then the sum (*) will no
longer be a multip le of 11.
(a) Write a progra m to accept an ISBN type numbe r (inclu ding
the hyphe ns) as input, ca l-
culate the sum (*),an d tell if it is a valid ISBN . (Hint: The
numbe r n is divisible by 11
if n Mod 11 is 0.) Before ca lculati ng the sum, the progra m
should check that each of
the first nine ch aracte rs is a dig it and that the last charac ter
is either a digit o r a n X.
(b) Write a progra m that begins with a va lid ISBN (such a
0-13-0 3065 7-6 ) and then con -
firms that the check ing schem e described above detects eve
ry single- digit and transpo-
sition- of-adj acent- d igits error by testing eve ry poss ible error.
[Hint: If d is a digit to be
replac ed, then the nine poss ibilities for the replac ements are
(d + 1) Mod 10, (d + 2)
Mod 10, (d + 3) Mod 10, ... , (d + 9) Mod 10.]
10. User-Operated Directory Assistance. H ave you ever tried
to ca ll someo ne at a place of busi-
ness and been to ld to type in some letters of their name o n
your teleph one's keypad in o rd er
to ob ta in the ir extens ion ? Write a progra m to simula te this
type of direct ory ass istanc e.
S uppose the names and teleph one ex tensio ns of a ll the empl
oyees of a compa n y are con-
ta ined in the text file Emp loyees. txt. Each se t of three lines
of the file has three pieces of
inform atio n: last name, first and middle name (s), and teleph
one ex tensio n. (We have fill ed
the file with the names of the U.S. presid ents so that the names
will be fam ili ar.) The user
sho uld be asked to press button s fo r the first three letters of
the person 's last name followed
by the first letter of the first name. For insta nce, if the person
's name were Gary Land , the
348 • Chap ter 7 Arrays

ed to as the "push -butt on en codin g" of


user wou ld type in 5264. T h e n umbe r 5264 is referr
have the sa me push -butt on e ncod ing-
the name . Note: Peop le with diffe rent na mes can
use r pre ses four keys o n the keypa d, the
for instan ce, Herb Jame s a nd G a ry Land . After the
of a ll the empl oyees hav ing the spec ifi ed
progr am should disp lay the name s and exten s ions
push- butto n encod ing. See Fig. 7.43.

D~ User-Opera ed Directory Assist ance


l=J @) I~ J

[ 1
l[ 2 ABC
l[ l 3 DEF [ Get Instructions l
[ 4 GHI
l[ 5 .JKL
l[ l 6 MNO [ Look Up Another Person l
-

[ 7 PQRS
l[ & TUV
l (9WXYZ ) Willi am Henr y Harr i3cn x2034
ila r ren Gama li el Hard ing x4040

[ * l[ 0
l[ l tf.

Push.{)utton code : 4279 -I

FIGURE 7.43 Sample run of Programming Proje ct 10.

mode ls of cars. Each car was drive n 100 miles,


11. A fuel-e conom y study was carried out for five
of ga llons used were place d in a line of the
and then the mode l of the car and the numb e r
entri es of the file. Write a progr am to dis-
file Mi leage. txt. Tab le 7.22 shows the data for the
n in decre asing orde r with respe ct to
play the mode ls a nd their avera ge mi les per gallo
struc tures with uppe r boun d 4, wher e each
milea ge. The progr am sh ould utilize an array of
sh ould recor d the n ame of each mode l of
struc ture has three memb ers. The first me mbe r
er of test vehic les for each mode l. The
car. The secon d mem ber sh ou ld recor d the numb
of ga llons used by that mode l. [Hint: Two
third mem ber shou ld record th e tota l numb er
eaders Func tion NumCars (ByVal make As
Func tion proce du res that are he lpfu l have the h
(ByVal make As Strin g) As Doub le.
Strin g) As Integ er and Func tion NumGals
ified mode l in the table, and NumG als
NumCars calcu lates the numb er of ca rs of the spec
l. Both Func tion proce dures are easi ly
calcu lates the numb er of gallo ns used by the mode
coded with LINQ queries.]

li;j:Jift!l Gallons of gasoline used in 100 miles of driving.


Gal Model Gal
Model Gal Model
Accord 4.1 Accord 4.3
Prius 2. 1
Camr y 3.8 Prius 2.3
Camry 4.1 4.2
4.2 Camry 3.9 Camry
Sebring 4.4
Mustang 5.2 Accord
Mustang 5.3
Text Files

8.1 Managing Text Files 350


• Prelimin aries • WriteA llLines Method • Sorting a Text File • Reorganizing the
Data in a CSV Text File • Set Operations • Searchi ng a CSV Text File
• The OpenFi leDialo g Control
8.2 StreamReaders, StreamWriters, and Structured Exception Handling 366
• Read ing a Text File with a StreamR eader • Creatin g a Text File with a Stream Writer
• Adding Items to a Text File • System.IO N amespac e • Structured Exceptio n Handlin
g
8.3 XMl 382
• Format of XML Files • LINQ to XML
8.4 A Case Study: Recording Checks and Deposits 388
• Design of the Program • User Interface • Coding the Program
Summary 396

Programming Projects 397

349
350 • Chapte r 8 Text Files

8.1 Managing Text Files


combin e, and retriev e inform a-
This section presen ts efficien t ways to sort, search, reorgan ize,
You can skip the m if you h ave
tion from tex t fil es. The section begins with so me prelim ina ries.
read Sectio n 7.3.

Preliminaries
piece of data per line. Fo r
The tex t fil es consid ered in Sectio ns 7.1 and 7.2 h ave a single
of a sta te, a nd each line of the file
instan ce, each line of the fi le States. txt conta ins the n ame
t file, called a C SV format ted
U SPres. txt contai n the n ame of a pres ide nt. Anoth er type of tex
by comm a . (C SV sta nds for
fil e, h as several ite ms of data on each line with the items sepa rated
each line contai ns four
Comma Se parated Values .) An examp le is the fil e USS tates.tx t, where
squ are miles ), and population in the year
items fo r each sta te-na me, abbreviation, land area (in
2000. The first four lines of the file are

Delaw are,DE ,l954,7 59000


Pennsy lvania ,PA,44 817,12 29600 0
New Jersey ,NJ,74 17,813 5000
Georgi a,GA,5 7906,7 637000

ries of data is a field. That is,


Each line of the file is called a record, and each of the four catego
field, an area field , and a pop-
each record consist s of four fi elds-a n ame fie ld , an abbrev iati on
ulati on field .
For instan ce, if the string
The Split method is used to access the fields of C SV formatted files.
value of line. Split ( ", "c l ( o l
variable line holds the first record of the fi le U SStates. txt, then the
Cint (line . Split( ", "c ) (2 ll is
is Delaware, th e value of line. Split ( ", "c ) (1) is DE, the value of
is the numbe r 759000.
the numbe r 1954, and the value of Cint (line. Split ( ","c ) (3))
the conten ts of the fil e
The fo llowing code can be used to create a LINQ que ry h olding
U SStates. tx t:
s( "USSt ates.tx t" )
Dim states () As String = IO . Fl.le .ReadA llLine
Dim query = From line In states
Let data line.S plit( ","c )
Let name data(O )
Let abbr data(l )
Let area Cint (data( 2))
Let pop = Cint (data( 3))
Select name , abbr , area, pop

each elemen t co nsistin g of


A fter this code is executed , query wi ll be a sequen ce of ele ments,
ts, then the four compo n ents
four com pon ents. If the va riable state i ass ign ed on e of the elemen
ea, and state. JJO/J. For insta nce,
assoc iated with state are denoted state. name, state.abbr, state.ar
the fo llow ing code fills a list box with the na mes of the states.

For Each state In query


lstBox .Items .Add( state . name )
Next

lect clause can conta in an y


The Select cla use in the que ry above contai ns four items. A Se
the seque nce re turned by the
numbe r of items. When a Select clause conta ins just on e item,
conta ins two o r more items, all
q uery can be displayed in a list box . If a Select clau e of a query
using a DataG ridVie w contro l.
the values returned by the query can be displayed in a table by
s Forms and Data groups. )
(The DataG ridView contro l is found in the Toolbo x's All Window
8.1 Managing Text Files • 35 1

The standa rd prefix fo r the name of a DataG ridVie w contro


l is dgv. With the query above, the
statem ents
dgvSt ates . DataS ource = query .ToLi st
dgvS tates. Curre ntCel l = Nothi ng
disp lay the va lues return d by the query in the grid shown in
Fig. B. l. (Note: The second state-
ment is option al. It preven ts havin g a shaded cell in the gnd
.) Vtsual Baste auto mattea lly gen-
erates the colum n headin gs.

c_. States

Displcrt State Data

I name abbr area pop ...


Dela•Nare
Pen mr,~van i a
DE
P.A.
1 !15~

&17
7~ 9t I=
0
New Jerset/ NJ 1717 813S
Georgia
- --- --
G l 57. fi 7 l7
Connecticut CT "i·B 5 3271

FIGURE 8.1 Displa ying a table in a DataG ridVie w contro l.

The blank colum n at the left side of the DataG ridVie w co


ntro l can be re moved by set-
ting the RowH eaders Vis ible prope rty of the contro l to False.
The co lumn h eaders in the
DataG ridView contro l can be customized with code that
sets the H eaderT ext property.
Figure 8.2 res ults when the RowH eaders Visibl e prope rty
is set to False at des ign time and
the fo llowin g four lines of code are added to the two lines
of code above:
dgvSt ates.C olumn s( "name " ) . Heade rText
"State "
dgvSt ates.C olumn s( "abbr " ) .Head erTex t = "Stat
e Abbre viatio n"
dgvSt ates.C olumn s( "area " ) .Head erTex t = "Land
Area"
dgvSt ates.C olumn s( "pop" ) .Head erTex t = "Popu
lation "

c... States

Displaj• State Data

State State
Abbrevi ation Land .Area Populat ion f

~=r
Delaware DE 1 .S~
PennS'1~van i a P.A. ... a17 1229tfi
New Jerse'f NJ 7 17 &1
Georgia GA 575 6 7517
Connecticut CT 85 l271

FIGURE 8.2 States table with modifi ed header s.


352 • Chap ter 8 Text Files

textb ook have been ca refu lly sized to


Note: The DataG ridVi ew con trols appearing in this
on 7.3 expla in how this was accom p lished.
exactly fit the data. Com ment s 2 and 3 of Secti
when working the xe rcises.
Ther e is no need for you to strive for such prec ision

WriteAIILines Method
with the Read A llLines meth od. We can
In Chap ter 7 we copied the conte nts of fil es into arrays
The fo llowing line of code creat es a new
reverse the proces with the Write AllLi nes meth od.
Video Note
Manag ing text fil e (or a LINQ query that return s string values)
text file and cop ies the conte nts of a string array
into the file, plac ing one element on each line.
strAr rayO rQue ryNa me)
IO . File . Writ eAll Line s("fi leNa me.t xt",
file by first conv erting the array to a
A simp le nume ric array can be copied into a text
a file using eithe r of the follow ing two sets
string array and then copy ing the string array into
of code:
ount - 1
Dim uppe rBou nd As Integ er = numA rray.C
Dim strAr ray(u pperB ound ) As Strin g
For i As Integ er = 0 To uppe rBou nd
strA rray (i) = CStr (num Array ( i ))
Next
" , strA rray)
IO. File .Wri teAll Line s( "file Nam e.txt

Dim query = From num In numA rray


Sele ct CStr (num)
IO. File .Wri teAll Line s( "file Nam e.txt " , query )

isting file, the file will be ove rwrit ten.


Note: If the Write AllLi nes meth od refere nces an ex

Sorting a Text File


.
Any text file can easily be sorted with a LINQ query

Example 1 The first four lines of the file AgeA tinau g.txt are

Geor ge Wash ingto n,57


John Adam s,61
Thom as Jeffe rson ,57
Jame s Madi son,5 7
ent's name and his age at inaug uratio n. The
Each of the 44 lines in the file conta ins a presid
the age at inaugurat ion and creat es a new
fo llowing program order s the data in the file by
sorted file.
les btnS ort.C lick
Priv ate Sub btnS ort_ Click ( .. . ) Hand
'Sor t the file AgeA tinau g.txt by ages
.Rea dAllL ines( "Age Atin aug.t xt" )
Dim agesA tinau g() As String = IO. File
g
Dim query = From line In a gesA tinau
Let age= Cint ( line .Spl it( ","c ) (1))
Orde r By age
Sele ct line
IO. File .Wri teAll Line s( "Sor ted.t xt" , query )
End Sub
8.1 Managing Tex t Files • 353

[Run, click on the button, and terminate the program. Then cl ick on the Refresh button in the
Solu tion Explorer wi ndow, click on the View A ll Files button, and double-click on the new text
file Sorted .txt in the bin \Debug subfolder. The first four lines of the file are as fo llows.]
Theodore Roosevel t,42
John Kennedy,4 3
Ulysses Grant,46
Bill Clinton,4 6

Example 2 The following var iation of Example 1 displays th e data in the file
A geAtlnaug.txt in a table ord e red by the ages at ina ugurat ion.

Private Sub btnSort Click( ... ) Handles btnSort.C lick


'Sort the file AgeAtina ug.txt by ages
Dim agesAtin aug() As String = IO. File .ReadAll Lines( "AgeAtin aug.txt" )
Dim query = From line In agesAtina ug
Let name= line.Spl it( ","c )(O)
Let age= Cint (line.Sp lit( ","c ) (1))
Order By age
Select name, age
dgvOutpu t.DataSo urce = query.To List
dgvOutpu t.Current Cell = Nothing
End Sub

[Run, and click on the button.]

g _. Unit ed St.a es Presid ent:; [ = I @) III""&S J

[ Sort the Rle ~e At In aug .txt ]


name age ""
Theodore Roosev e ~ 42 I

I
1

John Kenned}• 3
i
Ulysses Grant "16
1
Bill Ointon 14£- -1 '"

Reorganizing the Data in a CSV Text File


LINQ can retri eve spec ific data from a file and use it to create a new fi le co ntaini ng that data.

Example 3 The fi rst fo ur lines of the file Justices. txt are


Samuel,A lito,Geor ge W. Bush,NJ, 2006,0
Henry , Baldwin,A ndrew Jackson,P A , l830,1844
Philip,Ba rbour,An drew Jackson,V A,l836,18 41
Hugo,Bla ck,Frank lin Roosevel t,AL,l937 ,1971
354 • Chapter 8 Text Files

me Co urt justice :
Each line of the file conta ins the fo llowing informa tion a bout a S upre
re a ppo inted , yea r
fir t na me, las t name, appo inting pres ide n t , state from whic h they we
, the las t fi e ld is se t to 0.) The
appo inted, and yea r they left the co urt. (For sitting justices
of a justi ce a nd t he
fo llow ing p rog ram c rea tes a ne w fil e, wh ere each line is the full na me
inted in a ce nding
yea r they we re appo inted. The just ices a re so rted by th e yea r appo
na me in as cendin g
ord er. ] usti ces appo inted during the a me yea r a re so rted by the ir first
o rd e r.
rganize .Click
Private Sub btnReo rganize Cl i ck( ... ) Handle s btnReo
T .e data from a file Sort and restruc ture the data,
'a, d rite t to a new file
es.txt" )
Dim justice s() As String = IO. File .ReadA llLines ( "Justic
Dim query = From line In just ices
Let data= line .Split( ","c )
Let firstNa me = data(O)
Let lastNam e = data(l)
Let yrAppo inted = Cint (data(4 ))
Order By yrAppo i nted, firstNa me
inted
Let newLin e= f ir stName & " " & lastNam e & "," & yrAppo
Select newLin e
IO. File .WriteA llLines ( "NewF i le.txt" , query)
End Sub

button in the
[Run, click on the button , and termina te the program. Then click on the Refresh
the new text file
Solu tion Exp lorer window, click on the View All Files button, and double-click
in the bin \ Debug subfolde r. The first four lines of the file are as follows.]

James Wilson ,l789


John Blai r ,l789
John Jay ,l789
John Rutl e dge,l78 9

in
Example 4 The followin g variatio n of Exampl e 3 d isplays th e requested info rmation
a table.

ze. Click
Private Sub btnReo rganize _ Click( ... ) Handle s btnReo rgani
a text file Sort and restruc ture the data,
'Ta :e data from
and display it in a table
es . txt" )
Dim justice s() As String = IO. File .ReadA llLines ( "Justic
Di m query = From line In justice s
Let data= line.S plit( ","c )
Let firstNa me = data(O)
Let lastNam e = data(l)
Let yrAppo inted = Cint (data(4 ))
Let fullNam e = firstNa me & " " & lastNam e
Order By yrAppo inted, firstNa me
Select fullNam e , yrAppo inted
dgvOut put.Dat aSourc e = que ry .ToLis t
dgvOutp ut.Cur rentCe ll = No t hing
End Sub
8.1 Managing Text Files • 355

[Run, and click on the button.]

a:;1 s p .:me Co Jus·-ces l = I@] 1.-ES .]

I Sort Ju<;tic:ec; by Year Appointed

,.
1
tuiiNarne yrA+Jpointed
---~-- -- I_
Jarnes Wibon 1
--
John Blair 17 9
lJohn Jay 17
--
John Rutledge 17&.9 ....

Set Operations
Often we want to create a new text file from two existing text files. For instance, we might want to
merge the two files (with or without duplications). Or, we might want to update one file by deleting
the items that also appear in the other fi le. Or, we might want the new fi le to contain the items that
appear in both of the existing fi les. The steps we will use to carry out such operations are as follows:
1. U se the ReadAllLines method to fill two arrays with the contents of the two existing text files.
2. A pply a se t operation such as Concat, Union, Intersect, or Except to the arrays or to UNQ
qu eries derived from the arrays.
3. Use the WriteAllLines method to write the resulting array into a new text file .
If array 1 and array2 are string arrays, then
array l.Conca t( array2 ).ToArray is an array containing the elements of array} with array2
append ed, poss ibly with duplications.
array l.Union( array2 ).ToArray is an array containing the elements of array} with array2
append ed, without du plications.
array l.Intersect(array2 ).ToArray is an array containing the elements that are in both
array } and array2 .
array l. Except( array2 ).ToA rray is an array containing the elements of array } with the
elements of array2 removed.
Note: When one of the four operations above is used as the second parameter of a
WriteA llLines method, the ToArray method can be omitted.
These four set operat ions are demonstrated with two simp le fil es in Example 5 and then
with more complex files in Example 6.

Example 5 The contents of two fi les are as fo llows:

File1 .txt File2 .txt

A lpha Bravo
Bravo Delta
C harl ie
356 • Chapter 8 Text Files

The following program combines these two files in four ways. Figure 8.3 shows the form for the
program.

a_. Combine Files

Concatenate the Two Ales (with Repetitions)

Concatenate the Two Ales (without Repetitions)

And the Intersection of the Two Ales

Delet e the ~ em s in the Second Ale from the Arst Ale

FIGURE 8.3 Form for Example 5.

Dim firstSet() As String = IO . File .Read.AllLine s( "Filel.txt" )


Dim secondSet() As String = IO . File .Read.Al1Line s ( "File2.txt" )

Private Sub btnConcat Click( ... ) Handles btnConcat.Cl ick


IO. File .WriteAllLine s( "Conca t .txt" , firstSet.Conc at(secondSet ))
End Sub

Private Sub btnUnion_ Click( ... ) Handles btnUnion.Cli ck


IO . File .WriteAl lLines( "Union . txt" , firstSet . Union(second Set))
End Sub

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


IO. File .WriteAllLin es( "Inters ect.txt" , firstSet.Inte rsect(second Set))
End Sub

Private Sub btnExcept_ Click( ... ) Handles btnExcept.Cl ick


IO. File .WriteAllLine s( "Except . txt" , firstSet.Exce pt(secondSet ))
End Sub

[Run, click on each button, and term inate the program. Then click on the Refresh button in the
Solu tion Explorer window, click on the View A ll Files button, and look at the new tex t fi les in
the bin \ Debug subfolder.]
The file Concat.txt contains the five words A lpha, Bravo, C harlie, Bravo, and Delta.
The file Union.txt contains the four words A lpha, Bravo, C harlie, and Delta.
The file lntersect. txt contains the single word Bravo.
The file Except. txt contains the two words A lpha and C harlie.

In the four set operation , one or both of the arrays can be replaced with LINQ queries.
This allows the programmer to ord er, filter, and proj ect the data before co mbining files.

Example 6 The fo llowing program demonstrates the set operations with the two files
Ju tices.txt and USPres.txt. The file U Pr .txt i a ingl -fi ld t xt fil c nt inin th n m
of the 44 presiden ts. The first four lines of US Pres.txt contain the names Geo rge Washingto n,
8.1 M anagin g Tex t Fi les • 357

John Adams, Thomas Jefferson, and James Madison . Note: The file Justi ces.txt shows all
Supreme Court appointm nts as of January 1, 2010 .

OBJECT PROPERTY SETTING


D_. Pre:s idents & Justic es G?JI @) !Em frmPn] Tex t Pres idents & Justices
btn Both Text Both ] ustices And
Both Justices And Presidents
l btnN o Text
Pres ide nts
Pre idents with No
Presidents with No Appointments
l bt nO r Tex t
Appointments
Pres ide n ts O r] ust ices

Presidents Or Justices
l
Dim justices() As String = IO. File .Read.Al1Lines( 11 Justices.txt 11 )
Dim presidents() As String = IO. File .Read.AllLines( 11 USPres . txt 11 )

Private Sub btnBoth_ Click( . .. ) Handles btnBoth.Click


'Display justices who were also presidents
Dim queryJustices = From line In justices
Let firstName = line.Split( 11 , 11 C ) (0)
Let lastName = line.Split( 11 , 11 C ) (1)
Let fu l lName = firstName & 11 11 & lastName
Select fullName
IO. File .WriteA11Lines( 11 Both.txt 11 , queryJustices.Intersect(president s))
End Sub

Priva t e Sub btnNoAppointments_ Click( . . . ) Handles btnNoAppo intments .Click


'Display presidents who made no Supreme Court appointments
Dim queryAppointers = From line In justices
Let president= line.Split( 11 ,"c ) (2)
Select president
Dim queryNoAppoint From pres In presidents.Exc e pt(queryAppointe rs)
Order By pres
Select pres
IO . File . WriteAllLines( "NoAppointments.txt" , queryNoAppoint)
End Sub

Private Sub btnOr_ Click( . . . ) Handles btnOr.Click


'Display a combined list of presidents and justices
Dim queryJustices = From line In justices
Let firstName = line.Split( ","c ) (0)
Let lastName = line.Split( 11 ,"c ) (1)
Let fullName = firstName & 11 11 & lastName
Select fullName
Dim queryEither From person In presidents.Union(queryJusti ces)
Order By person
Select person
IO. File .WriteA11Lines ( "PresOrJustice.txt 11 , queryEither)
End Sub

[Run, click on each button, and terminate the program. Then click on the Refresh button in the
Solution Explorer window, click on the View All Files button , and look at the new text files in
the bin \Debug subfo lder.]
358 • C hapter 8 Text Files

The file Both .tx t conta ins the single name "William Taft".
The fi le NoAppo intments.tx t contains the names of four presidents.
The file PresOrjustice.txt contai ns 154 names.

Searching a CSV Text File


In Section 7.3 we sea rched fi les having several fields by loading the data into arrays of stru c-
tures and searching the arrays. The next example prov ides a more d irect way of search ing for
data-no user-defined structure is used .

Example 7 Each reco rd of the file USStates.txt contains a name field, an abbreviat ion
fie ld, an area field, and a population fi eld. The first two records of the file are
Delaware,DE,l954,759000
Pennsylvania,PA,448 17,1229 6000

The fo llowing program looks up the name of the state whose abbrev iat ion is given . Note:
The method First is required in the line txtName . Text = query . First because query is a
seque nce-namely, a sequ ence of one ite m.

Dim stat es() As String = IO. File .ReadAllLines( "USStates . txt" )

Private Sub btnFind_ Click ( .. . ) Handles btnFind.Click


'Note: mtbAbbr has the mask LL
Dim que r y = From line In states
Let name= line .Split ( ","c )(O)
Let abbreviation = line.Split( ","c ) (1)
Where abbreviation = mtbAbb r.Text.ToUpper
Select name
If query . Count 1 Then
txtName.Text = query.F irst
Else
Dim str As String = " is no t a valid state abbreviation."
MessageBox .Show(mtbAbbr.Text.ToUpper & str, "Error" )
mtbAbbr . Clear ()
mtbAbbr. Focu s ()
End If
End Sub

[Run, enter a state abbreviation into the masked text.box, and click on the button.]

State abbreviation : MD

Rnd Name of State

Name: Mar,o!and
• 359
8.1 Ma n agi ng Te xt Files

tes hav ing


m sea rch es th e fil e US St ates .tx t for th e sta
Th e fo llo wi ng pro gra th e sta tes
Example 8
pe r sq ua re mi le an d di plays th e na me s of
s th an 9. 5 pe op le asc en din g ord e r) in
po p ula t ion de ns ity les rd ere d by th eir po pu lat ion de ns iti es (in
de ns iti es o
a nd th e ir po pu lati on
a tab le.
bt nS ea rc h. Cl ick
nS ea rc h_ Cl ick ( ... ) Ha nd les .tx t" )
Pr iv at e Su b bt llL in es ( "U SS tat es
() As St rin g = IO . Fi le .R ea dA
Di m st at es
lin e In st at es
Di m qu er y = Fro m
Sp lit ( "," c )
Le t da ta = lin e.
O)
Le t na me = da ta( CD bl (d ata (2 ))
y = CD bl (d ata (3 )) I
Le t po pD en sit be r(p op De ns ity )
t fo rm att ed De ns ity = Fo rm atN um
Le
< 9.5
Wh ere po pD en sit y
en sit y As ce nd ing
Or de r By po pD
rm att ed De ns ity
Se le ct na me , fo
er y. To Li st
rce = qu
dg vO utp ut. Da taS ou ng
nt Ce ll = No thi
dg vO ut pu t.C ur re ex t = "S tat e"
Ou tpu t.C olu mn s( "na me " ) . He ad erT t "P op ul ati on De ns
ity "
dg v
( "fo rm att ed De ns ity " ) .H ea de rT ex
ns
dg vO utp ut. Co lum
En d Su b

bu tto n .]
[Run, an d cli ck on th e

l = l @l l. Si. -'
a~ U.S. St a es

.td
Search the File USStates

Population
State Density

Alaska
1.22

Wyoming 5.34

Montana 6.2 6

North Dakota 9.

ntrol
The OpenFileDialog Co same sta nd ard Op en
an d N ote pad, all prov ide th e
suc h as W ord , Ex ce l, en dial g box
W indows app licati on s, yo u wa nt to op en . Figure 8.4 sh ows an Op
spec ify th e fil e th all its
dia log box to he lp yo u a tex t file. Th e sam e Op en dia log box, wi
th N otepad to op en eOialog co ntrol.
th at co uld be used wi sic pro gra ms co urtesy of th e Op enFil
b le to Vi sua l Ba he n yo u do uble-
fun cti on ality, is av a ila th e Di alo gs sec tio n of the Toolbox. W
Th e Op enFi leOialog co
nt rol is in be low th e Fo rm
nt ro l wi ll ap pe ar in th e co mp on en t tray
e To olbox, the co , ince th e
cl ick on th e ico n in th leO ial og l. (W e wi ll no t ch an ge the na me
lt na me Op enFi pe rty we will et for th
e
Designe r wi th th e de fau the co nt ro l' fun cti on. ) The only pro ov e
de c rib es e co mb o box ab
de fau lt na me co mp let ely de ter mi ne s th e tex t tha t appea rs in th
pe rty, wh ich
co n tro l is th e Filter pro
360 • Chapter 8 Text File

Jl Open
u ... I << EXT ORNE (F:) ~ MAJO R_TEXT_FilES "' l"-t j J Sea'dl M/J.JOF_TEX I JILES

Organize ..,. New folder

Download~ LJ Add e dCo l or~ . txt LJ Famou~ .txt LJ Proverb~ . txt LJ T ow n~ .txt
Recent Plac e~ '--' Gift~. txt Rain.txt LJ UN.txt
LJ AgeAtln aug .txt LJ

'--' Golf.txt Ranking .txt LJ UnitedState ~ .txt


LJ Ba~ e ball.txt LJ

Librarie~ Li Citie~ .txt Ju~ice~ .txt '--' Retired( olors.txt LJ Universities.txt


~

L..J Colleges.txt '--' Members.txt LJ Retired Sen.txt '--' UPC.txt


4 Homegroup L..J Colors.txt ~ Mileage.txt '---' SBWinn ers.txt L..J USPres.txt

I= LJ Cowboy.txt LJ Nam e~ .txt LJ SenatellO.txt "-' USSenate.txt


USSt ate~ . txt
Computer I u Crayons.txt L..J Nations.txt '--' Senatelll .txt L....,j

OS (C:) Degrees. txt LJ NewSen.txt LJ Sonnet. txt L..J


VPres.txt
LJ

KINGSTON (E:) LJ Distances.txt '---' PopularNames.txt L..J States.txt '--' Words.txt


L.Jf EXT DRNE (F:) ,___. Employees.txt '--' Prel990Colors.txt LJ Top25HR.txt

File name: ... [Text Documents (*.txt)

FIGURE 8.4 An Open dialog box.

The simples t set-


the O pen button and the types of files that will be displayed in the dialog box.
ting has the form
text for combo box I* .ext
display. For our pur-
where ext is a two- or three-le tter extensio n describing the types of fi les to
poses, the most used setting for the Filter property wi ll be
Text Docume nts (*.txt) ! * . txt
The stateme nt
OpenF ileDial ogl . ShowD ialog( )
button pressed , the
displays the Open dia log box. After a file has been selected and the O pen
va lue of
OpenF ileDial ogl . Fil e Name
will be the file's filespec- includ ing drive, path, filename, and extensio n.

Example 9 The followin g program displays the contents of a text file selected by the
user with an O pen dialog box.
OBJECT PROPERTY SETTING
ll
- Display a File ~I 8 llctiJ frmDisp layFi le Text Display a File
btnSelec t Text Select a Text File
Select a Text Rle
l lstOutpu t
OpenFil eDialog 1 Filter Text Docume nts
1st Output
(*.txt) I* .txt
8.1 Manag ing Text Files
• 361

Priva te Sub btnS elect Click ( ... ) Hand les btnS


elect .Clic k
Dim textF ile As Strin g
Open FileD ialog l.Sho wDia log() 'Open dialo g box
appea rs and progr am
pause s until a selec tion is made
textF ile = Open FileD ialog l.File Name
lstOu tput.D ataSo urce = IO. File . Read AllL ines(
textF ile)
lstOu tput. Selec tedit em = Nothi ng
End Sub

[Run, a nd cl ick on the butto n. (Assu me that t he use


r make c h o ices leadin g to the situat io n in
Fig. 8.4.) Se lect the file USPres. txt, and click on the
Open butto n in the d ialog box. ]

a... Disp lay ;3 File l = I @) lr.,. a ,~j

I- Select a Text File


J
George Washington -;.

rAdom•
Thomas Jefferson
ames Madison
--,
'-""

ames Monroe
ohn Q . Adams .,...

Comments 8.1
1. In Exam ple 7, the a rray states could h ave been omitted
a nd the first line of t he query
c h anged to

Dim quer y= From line In IO.Fi le.Re adAl lLine


s( "USS tates .txt" )
Howe ver, with thi s c h an ge the tex t file wou ld be
read each t ime the use r req uested the
name of a state. Id ea ll y, a file sho uld be read o nly o
n ce from a disk each time the progr am
is run.

1. Cons ide r Exam ple 7. Suppo se the last line of the que ry we re c hanged to
Selec t name, abbr

What chang e wou ld have to be made to t h e fo llowin


g line?
txtNa me.T ext = quer y.Fir st

2. The secon d clause of the query in Exam p le 1 is


Let age= Cint (line .Spli t (","c ) (1))

The progr am wou ld produ ce the correc t result even


if the C lnt functi on we re omitt ed.
Why is th at so, and why sh ould C lot be used in gener
al ?
3. Does the a rray array l.Con cat(a rray2 ) . ToAr ray
conta in the sa me set of va lu es (d isre-
gard ing order) as the array array 2. Conc at (arra yl)
. ToAr ray ? Is th e same true for Un io n,
Inters ect, and Excep t?
362
• Chapter 8 Text Files

EXERCISES 8.1

Ex erc ise s 1 thr ou gh


10 ref er to the fil e }u
Su pre me Co ur t jus tic es, sti c es .tx t tha t co nta ins
pa st an d pre sen t. Ea ch da ta ab ou t the
las t na me , ap po int ing rec ord co nta ins six fie
presid en t, ho me sta te, ld s-f ir st na me ,
co ur t . (F or sit tin g jud ge ye ar ap po int ed , an d ye
s, the las t fie ld is set to ar the y lef t the
fo llo ws : 0.) Th e fir st tw o lin es
of the fil e are as
Sa mu el, Al ito ,G eo rge
W. Bu sh ,N J,2 00 6,0
He nry ,B ald wi n,A nd
rew Jac ks on ,PA ,18
30 ,18 44
In Ex erc ise s 1 thr ou gh
6, de ter mi ne the fir st tw
o lines of the ne w file cre
ate d by the co de .
1. Dim qu er y= Fro m lin
e In IO .F ile .R ea
dA llL in es ("J us tic
Le t da ta = lin e.S es .tx t")
pl it( "," c)
Le t fir stN am e = da
ta( O)
Le t las tN am e = da
ta( l)
Le t ful lN am e = fir
stN am e & " " & las
Le t sta te = da ta( tN am e
3)
Se lec t ful lN am e &
" , " & sta te
IO .F ile .W rit eA llL
ine s(" Ne wF ile .tx t",
qu ery )
2. Dim qu er y= Fro m lin
e In IO . Fi le. Re ad
Al lL in es ("J us tic es
Le t da ta = lin e.S .tx t")
pl it( "," c)
Le t fir stN am e = da
ta( O)
Le t las tN am e = da
ta( 1)
Le t ful lN am e = (fi
rst Na me & " " &
Le t yrA pp oin ted = las tN am e) .To Up pe r
Ci nt( da ta( 4) )
Se lec t ful lN am e &
" wa s ap po int ed in
IO .F ile .W rit eA llL " & yrA pp oin ted &
ine s(" Ne wF ile .tx t",
qu ery )
3. Dim qu er y= Fro m lin
e In IO .F ile .R ea
dA llL in es ("J us tic es .tx t")
Le t las tN am e = lin
e.S pl it( "," c) (1)
Le t pr es = lin e.S
pl it( "," c) (2)
Le t pre sL ast Na me
= pr es .S pl it( " "c)
Le t ph ras e = la stN .L as t
am e & " wa s ap po int
Se lec t ph ras e ed by " & pre sL ast
Na me
IO .F ile .W rit eA llL
ine s(" Ne wF ile .tx t",
qu ery )
4. 'N ote : To da y. Ye ar
is the cu rre nt ye
Dim qu er y= Fro m ar
lin e In IO .Fi le. Re
ad Al lL in es ("J us tic
Le t las tN am e = lin es .tx t")
e.S pl it( "," c) (1)
Le t yrA pp oin ted =
Ci nt (li ne .S pl it( ","
Le t ye ars = To da c) (4) )
y.Y ea r- yrA pp oin
Le t ph ras e = las tN ted
am e & " ap po int ed
Se lec t ph ras e " & ye ars & " ye ars
ag o"
IO .Fi le. W rit eA llL
ine s(" Ne wF ile .tx t",
qu ery )
5. Dim qu er y= Fro m lin
e In IO .F ile .R ea
dA llL in es ("J us tic
Le t da ta = lin e . Sp es .tx t")
lit (" ,"c )
Le t fir stN am e = da
ta( O)
Le t las tN am e = da
ta( l)
Le t yrA pp oin ted =
Ci nt( da ta( 4) )
8.1 Man aging Text Files
• 363

Let new Line = lastN ame & "," &


first Nam e & "," & yrA ppoi nted
Sele ct newL ine
IO.F ile.W riteA llLi nes( "Ne wFi le.tx
t", quer y)
6. Dim que ry= From line In IO .Fi
le.R eadA llLi nes( "Jus tice s.tx t")
Let data = line .Sp lit(" ,"c)
Let lastN ame = data (l)
Let pres = data (2)
Let stat e = data (3)
Let pres Last Nam e = pres .Spl it("
"c) .Las t
Let new Line = pres Last Nam e & ","
& lastN ame & "," & stat e
Sele ct newL ine
IO.F ile.W riteA llLi nes( "Ne wFi le.tx
t", quer y)
In Exer cises 7 thro ugh 10, desc ribe the new
file crea ted by the code .
7. Dim que ry= From line In IO.F ile.R
eadA llLi nes( "Jus tice s.tx t")
Let data = line .Sp lit(" ,"c)
Let first Nam e = data (O)
Let lastN ame = data (l)
Let yrAp poin ted = Cin t(da ta(4 ))
Let fullN ame = first Nam e & " "
& lastN ame
Let newL ine = fullN ame & II II & yrA
' ppoi nted
Whe re lastN ame .Sta rtsW ith(" B")
Orde r By yrAp poin ted
Sele ct newL ine
IO.F ile.W riteA llLi nes( "Ne wFi le.tx
t", quer y)
8. Dim que ry= From line In IO.F ile.R
eadA llLi nes( "Jus tice s.tx t")
Let data = line .Sp lit(" ,"c)
Let first Nam e = data (O)
Let lastN ame = data (l)
Let stat e = data (3)
Let yrAp poin ted = Cin t(da ta(4 ))
Let fullN ame = first Nam e & " "
& lastN ame
Let new Line = stat e & "," & fullN
ame
Whe re (yrA ppoi nted >= 1990 ) And
(yrA ppoi nted < 2000 )
Orde r By stat e
Sele ct newL ine
IO.F ile.W riteA llLi nes( "Ne wFi le.tx
t", quer y)
9. Dim que ry= From line In IO.F
ile.R eadA llLi nes( "Jus tice s.tx t")
Let data = line .Sp lit(" ,"c)
Let first Nam e = data (O)
Let lastN ame = data (l)
Let pres = data (2)
Let new Line = first Nam e & ","
& lastN ame & II
& pres
II

Sele ct newL ine '


IO.F ile.W riteA llLi nes( "Ne wFi le.tx
t", quer y)
10. Dim que ry= From line In IO.F ile.R
eadA llLi nes( "Jus tice s.tx t")
Let data = line .Sp lit(" ,"c)
Let first Nam e = data (O)
Let lastN ame = data (l)
Let yrA ppoi nted = Cin t(da ta(4 ))
364 • Chapter 8 Tex t Files

Let yrL eft = Cin t(da ta(S ))


" " & last Nam e
Let full Nam e = firs tNa me &
" & yrA ppo inte d
Let new Line = full Nam e & "
Whe re yrL eft = 0
Ord er By yrA ppo inte d
Sel ect new Line
ile. txt" , que ry)
IO. File .Wr iteA llLi nes ("N ewF
ume the file
the new file crea ted by the code . Ass
In Exe rcis es 11 thro ugh 14, desc ribe es and the file
the subs crib ers to the New York Tim
NY Tim es.t xt con tain s the nam es of
crib ers to the Wall Street Journal.
WS J.tx t con tain s the nam es of the subs
txt" )
File . Rea dAl lLin es ( "NY Tim es.
11. Dim tim es() As Stri ng = IO. SJ.t xt")
.Re adA llLi nes ("W
Dim wsj () As Str ing = IO. File
ile. txt" , tim es.U nion (ws j))
IO. File .Wr iteA llLi nes ("N ewF
.txt ")
ile.R ead AllL ines ("N YTi mes
12. Dim tim es() As Str ing = IO.F SJ.t xt")
.Re adA llLi nes ("W
Dim wsj () As Str ing = IO. File
ile. txt" , tim es.I nte rsec t(w sj))
IO. File .Wr iteA llLi nes ("N ewF
txt" )
File . Rea dAl lLin es ( "NY Tim es.
13. Dim tim es() As Stri ng = IO . J. txt" )
. Rea dAl lLin es ( "WS
Dim wsj () As Stri ng = IO. File
ile. txt" , tim es.E xce pt(w sj))
IO. File .Wr iteA llLi nes ("N ewF
txt" )
File . Rea dAl lLin es ( "NY Tim es.
14. Dim time s () As Stri ng = IO. SJ.t xt")
.Re adA llLi nes ("W
Dim wsj () As Stri ng = IO. File
= time s.U nion (ws j) .ToA rray
Dim unio nAr ray( ) As Stri ng .ToA rray
ing = tim es.I nte rsec t(w sj)
Dim inte rsec tAr ray () As Str t(in ters ectA rray ))
ile. txt" , uni onA rray .Ex cep
IO. File .Wr iteA llLi nes ("N ewF
presidents
s 15 thro ugh 18, use the file USP res. txt that contains the names of all the
In Exe rcise ~presidents.
t that contains the names of all the vice
of the Uni ted States and the file VPr es.tx
pres iden t wh o also
fil e co ntai ning the nam es of every
15. Wri te a prog ram that crea tes a e pres iden ts
also should display the num ber of thos
served as v i ce~ pres id e nt . The prog ram
in a message box.
who served a
Wri te a prog ram that crea tes a file con tain ing the nam es of every person
16. ber of those
program also should display the num
e ithe r vice -preside nt or pres iden t. The
names in a message box.
who served as
con tain ing the names of ever y person
17. Wri te a prog ram that crea tes a file lay the num.-
not both. The program also sh ould disp
eith er vice -preside nt or pres iden t, but
be r of those names in a message box .
iden t who did not
18. Wri te a prog ram that crea tes a
fil e con tain ing the names of eve ry pre
of those pres i-
ram also should display the num ber
also serve as vice-preside nt. T he prog
den ts in a message box.
from Section 7.3
ram for the stated example or exercise
In Exercises 19 thro ugh 26, write a prog
with out using a stru ctur e.
20. Sec tion 7.3, Exa mpl e 4
19. Sec tion 7.3 , Exa mpl e 2
22. Sec tion 7.3, Exe rcise 19
21. Sec tion 7.3 , Exercise 18
24. Sec tion 7.3, Exe rcise 21
23. Sec tion 7.3 , Exe rcise 20
26. Sec tion 7.3, Exe rcise 24
25. Sec tion 7.3 , Exercise 22
8.1 Managing Text Files • 365

27. At the beginning of 1990, a complete box of Crayola 1 crayon s had 72 colors (in th e file
Pre 1990.txt). During the 1990s, 8 colo rs were retired (in th e file Retired.txt) and 56 new
colors were added (in the fi le Add ed.txt). Write a program th at creates a text fi le li t ing the
post-1990s set of 120 colors in alphabetica l order.
Exercises 28 throu gh 34 should u se the file Justices.txt discussed at the beginning of this
exercise set.
28. Write a program to create a file in which each record consists of two fie ld - the full name
of a Supreme Court justice, and the just ice's state.
29. Write a program to create a file similar to ] ust ices.txt, but with the state field de leted.
30. Write a program that disp lays the entire contents of the file Just ices. txt in a DataG ridView
control.
31. The fi le USStates.tx t contains information about each of th e 50 states. Each record
conta ins four fie lds-name, abb reviat io n , land area (in sq uare miles), pop ulat ion in t he
year 2000. The record s are o rde red by t he states' date of entry into t he un ion. The first
fo ur lines of the file a re
Delaware,D E,1954,759 000
Pennsylvan ia,PA , 448 17, 1229 6000
New Jersey ,NJ , 7417 , 8135000
Georgia,GA ,5 7906,76370 00
Write a program that creates a file consisting of the states that have not prod uced any
upreme Court justices.
32. The first Supreme Court justice was appo inted in 1789 . Write a program to create a file
that lists the years from 1789 through 2009 in which no S upreme Court justices we re
appo inted . The first fo ur lines of the file will be 179 2, 1794 , 1795, and 1797 .
33. Write a program to create a file that lists the states that have produced Supreme Court jus-
tices, along with the number of justices prod uced. The states shou ld be in alphabetica l order
bythe irabbreviations.Thefir stfour lin softhe filewill be AL,3 ; AZ, 2; CA , 5; co,L
34. Write a program to create a file that lists the pres idents who have appo inted S uprem Court
justices, a long with the numbe r of ju rices appo inted. The pres idents should be in a lphabet-
ical order by the ir fu ll names. The first two lines of the file will be Abraham Lincoln, 5;
Andrew Jackson , 5.
35. Consider the file USStates.tx t described in Exercise 31. Write a program to display the
entire contents of the file in a DataGridView control with the states in alphabetica l order.

Solutions to Practice Problems 8.1

1. The line would have w be changed to

txtName . Text = query .First.nam e


2. The ages of the pres idents are all two-di git numbers and th erefore wi ll be ordered co rrectly wh en so rted as
strings. In ge nera l, howeve r, with arbitary ages, the query would not produce a correct result. For insta nce, a
nine-yea r-old would be considered to be o lder th an an eighty-yea r-old, and a centena rian would be co nsidered
to be younger than a nine-yea r-o ld.
3. The answe r to the first quest ion is "Yes ." The sa me is true for Union and Inte rsec t. H owe ve r, the two array
are different when Except is used. For instance, if the two a rray were reve rsed in the las t eve nt procedure of
Exa mpl e 5, then th e co ntents of the fil e Except.txt would be the single word De lta.

1
C rayola is a regi tered trademark of Binney & Sm ith.
366 • Chapter 8 Tex t Files

8.2 StreamReaders, StreamWriters, and Structured Exception Handling


the fil e and
So fa r we h ave accessed the da ta in a text file by filling an array with the lin es of
fil e directly o ne
the n access ing th e array. H oweve r, sometim es we want to read or write a text
line at a time without using a rrays a intermed ia rie .

Reading a Text File with a StreamReader


teps:
Lines of a tex t file can be read in o rde r and as ign ed to variab les with the fo llowing
VideoNote
rrca mReadcrs ami
1. Execute a state ment of the form
Strea m Writers

Dim srVar As IO.Strea mReade r


of ch ar-
A Strea mReade r is a class fro m the Input/O utput na mespace that can read a stream
variable srVar to be of type
acters coming from a disk. The Dim sta te ment decla res the
SrreamR eader.
2. Execute a sta tement of the form

srVar = IO.File. OpenTe xt(files pec)

filen a me
wh e re fi lespec id e ntifies the tex t file to be read. If filesJJec consists o nly of a
p rogra m 's
(th a t i , if n o pa th is give n) , V isual Bas ic will look fo r the fil e in the
bin \ Debug fo ld e r. This sta te me nt , which es ta blish es a commun ica tions link be twee n the
a file for
comp ute r a nd th e disk drive fo r reading da ta fro m the d isk, is sa id to open
varia bles in the
input . Da t a the n can be input fro m the pec ified fi le a nd ass ign ed to
prog ra m .
and 2
Just as with o the r variables, th e declarati on and ass ignmen t state ments in S teps 1
can be comb ined into the single state ment

Dim srVar As IO .S treamRe ader = IO.File. OpenTe xt(files pec)

Each line is
3. Read lines in ord er, on e at a time , from the file with the Readlin e method.
retrieved as a string. A state men t of the form

strVar = srVar.R eadLine

it to the
causes th e program to look in the file for the next unread line of data and ass ign
variab le strVar.
The OpenTex t method set a po inte r to the first line in the sp cified fil e. Each time
a
is read, a nd the po inter is then moved to
Readlin e method is executed, the line po inted to
the nex t line. Afte r all lines h ave been read from the file, th e va lue of

srVar.En dOfSt ream


to cycle
will be True. The En.dO fS tream property can be used in the conditio n of a Do loop
through every line of a tex t file. S uch a loop might begin with the stateme nt Do until

srVar. EndOfSt ream.


link se t
4. A fte r the des ired lines h ave been read from the fi le, te rminate the co mmunic ations
in. Step 2 with the tatemen t

srVar.C lose()
8.2 Stream Reade rs, StreamWri ters, and Struct ured Exception
H and ling • 367

Example 1 The follow ing progra m uses a Strea mReader to carry out
th e same task as th e
progra m in Exam ple 7 of the prev ious sectio n . That
is, it finds the name of the state who e
abbrev iation is given in a maske d tex t box.
Priva te Sub btn Fin d Click ( ... ) Hand les
btnF ind.C lick
Dim s r As IO. Stre~eader = IO. File .Open
Text( "USS tates .txt" )
Dim a b br As Strin g = mtbA bbr.T ex t . ToUp •mask is LL
per
Dim l i ne As Strin g
Dim found Flag As Boole an = False
Do Until found Flag Or sr.En dOfS tream
line = sr.Re adL i ne
If line. Spli t( ","c ) (1) = abbr Then
txtNa me . Text = line. Spli t( " , "c ) (0)
found Flag = True
End If
Loop
If Not found Flag Then
Dim s tr As Strin g = " is not a valid state
abbre viati on."
Messa geBox .Show (mtbA bbr.T ext . ToUp per &
str, "Erro r" )
mtbAb b r. Cle a r ()
mt bAbb r . Focus ( )
End If
End Sub

[Run, en ter a state abbrev iat ion in to the maske d tex t


box, and click on th e butto n.]

c.. Stat es l = I [§] 1-~ ~~J


State abbreviation : MD

Rnd Name of State

Name : Maryland

Creating a Text File with a StreamWriter


In Sectio n 8.1 we create d tex t fi les by copyi ng t he conte
nts of an array into the fil es with the
Write AliLines metho d. Howeve r, so metim es we want
to wri te to a text fi le d irectly o ne line at
a time witho ut using an array. The fo llowin g steps create
a new tex t file and wr ite data to it.
1. C hoose a filesfJec .
2. Execu te a state ment of the form
Di m swVar As IO. S tream Write r = IO.F ile.C
reate Text (fi lespe c)
where swVar is a variab le name. This process is sa id to
open a file for outpu t. It establ ishes
a comm unica tio ns link betwe en the progra m and the
di k drive for storin g data onto the
d isk. It allows data to be outpu t fro m the progra m
and record ed in the spec ified file. If
filespec consists onl y of a filena me (that is, if no path is
given ), Visua l Bas ic will place the
file in the progra m's bin \ Debug folder. Cauti on: If
an existing file is opened for outpu t ,
Visua l Basic will rep lace the file with a new empty fil
e.
368 • Chap ter 8 Text Files

ess ion
e meth od. If info is a literal, var iable, or expr
3. Place data into the fi le with the WriteLin
of any data type, then the statemen t
swV ar.W riteL ine( info )
file .
writes the infor mation into a new line of the
the fil e, exec ute
4. Afte r all the data have been reco rded in
swV ar. Clos e ()
a
Writ eLin e meth od actu a lly places data into
This state men t is very impo rtant beca use the if you
fers the data to the di sk. The refo re,
temporary buffer, and the C lose meth od trans
migh t be los t. The state men t also brea ks the
om it the state men t swVa r . Clos e (), some data
e its omission migh t prev ent othe r proced ures
com mun icati ons link with the file. The refor
from accessing the file.

isting of seve ral last names of


Example 2 The fo llow ing prog ram crea tes a text file cons
e cont ents of the file in a list box.
com pute r pioneers and then displ ays the entir
ick
k( ... ) Han dles btnC reat eFil e.Cl
Priv ate Sub btnC reat eFil e_ Clic
'Cre ate the file Pion eers .txt )
. File .Cre ateT ext( "Pio neer s.tx t"
Dim sw As IO .Stre amW riter = IO
sw. Writ eLin e ( "Ata naso ff" )
sw.W riteL ine( "Bab bage " )
sw.W riteL ine( "Cod d" )
sw.W riteL ine( "Dij kstr a" )
sw.W riteL ine( "Eck ert" )
sw.W riteL ine( "Fag gin" )
sw.W riteL ine( "Gat es" )
sw.W riteL ine( "Ho lleri th" )
file will be emp ty.
sw. Clos e() 'If this line is omi tted the
in file " , "Fil e Stat us" )
Mess ageB ox . Show ( "Nam es reco rded
End Sub
k
... ) Han dles btnD ispl ayF ile . Clic
Priv ate Sub btnD ispl ayF ile_ Cl ick( n a 1 st box
Pion eers .txt
'Dis play the con ents of the file
eade r = IO. File .Ope nTex t( "Pio neer s.tx t" )
Dim sr As IO. Stre amR
lstN ame s.Items.C lear ()
Do Unt il sr. EndO fStre am
lstN ame s.I tems .Add (sr .Rea dLin e)
Loop
End Sub
ick on the seco nd button.]
[Run, click on the first butto n , and then cl

a.. Co mpu .in g Pio n e er~

Atanasoff
Babbage
Create File Codd
Dijkstra
Eckert
Display File Faggin
Gates
Hollerith
8.2 StrcamR eade rs, Stream Writers, and Stru
ctur ed Exceptio n Han d ling
• 369

Adding Items to a Text File


Dat a can be add ed to the end of an ex
istin g tex t file with the follo win g step
s.
1. Execute the state men t
Dim swVar As IO . Stre amW r i ter
= IO. File . App endT ext ( f i lesp
ec)
whe re swV ar is a va riab le name and files
pec iden t ifies the file. T hi process is sa
a fil e for append . It allows data to be id to ope n
outp ut and reco rded at the end of the
If files pec co nsists on ly of a filen ame (tha spec ified fil e.
t is, if no path is give n) , Visual Bas ic
the fi le in the prog ram's bin\ Debug fold will look for
er.
2. Place data in to the file with the W
ri teLine met hod .
3. Afte r all the data have been reco rded
into the file, close th e fi le with the stat
eme nt
swV a r. Clo se ()

The lO. File .Ap pen dTex t option is used


to add data to an ex ist ing file. Howeve
be used to crea te a new fil e. If the fi le r, it also can
does not ex ist, then the IO. File .Ap pen
ates the fi le. dTe x t op ti on cre-
The three stat es "ope n for inpu t," "ope
n for output," and "ope n for app end "
as mod es. A fi le should not be ope n in are refe rred to
two mod es at the sa me t ime. For insta
been ope ned for outp ut and da ta have nce, afte r a fi le has
been writ ten to it, the file shou ld be clos
ope ned for inpu t. Had the stat eme nt ed befo re being
swv ar. Clo se () in Exa mpl
gram wou ld have cras hed whe n th e seco e 2 been om itted , then the pro-
nd butt on was cl icked on.
An atte mpt to ope n a non ex isten
t fi le for inpu t term inat es the prog
File N otFo und Exc ep ti on mes age box ram with a
, stat ing that th e file co uld not be
met hod that te lls us whe the r a ce rtain fo und . T h ere is a
file already ex ists. lf the va lue of
IO . F i le.E xis ts(f iles pec )

is True , then the spec ified file ex ists. T


herefore , prud enc e dict ates that fi les be
with cod e such as ope ned for inpu t

Dim sr As I O. Stre amR ead er


If IO . File . Exi sts( file spe c)
The n
s r = I O. File .Ope nTe xt(f iles
pec )
Els e
mes sage = "Ei ther no file
has yet bee n cre ated or the
mes sage &= file spe c & " is file "
not whe re exp ecte d."
Mes sage Box .Sho w(m essa ge, "Fi
le Not Fou nd" )
End If

The re is one file- man age men t ope rat


ion th at we have yet to disc uss: cha ngin
an item of info rma t ion fro m a tex t g or dele t ing
file. An indi vidu al item of a fi le can
dele ted dire ctly. A new file must be not be cha nged or
crea ted by read ing each item from the
reco rd ing it, with the sing le item cha orig inal file and
nged or dele ted, into the new file. The
erased, and the new fil e is rena med with old file is then
the name of the orig inal file. Regard ing
tasks, the Visual Bas ic state men t these last two

I O.F ile . Del ete ( file spe c )

removes the spec ified fi le from the d isk,


and the state men t
IO. Fil e. Mov e( o1d fi1e spe c ,
new files pec )

cha nges the fil espec of a file. Not e 1:


The lO .Fil e. Dele te and lO. File .Mo ve
be used with ope n fi les; doing so ge nera met hod s ca nno t
te an exce ptio n. Not e 2: No thin g hap
pen s if the file
370 • Cha pter 8 Tex t Files

iste n t oldfi lespec in an


renc ed in an IO.F ile.D elet e met hod doe sn't ex ist. Howeve r, a non ex
refe
exc eption.
IO.File .Mo ve met hod ge nera tes an

System .IO Namespace


the stat eme nt
a prog ram that has exte nsiv e file han dlin g can be simplified by placing
C reat ing

Imp orts Sys tem . I O


n there is no need to
top of the Cod e Edi to r, befo re the Cla s s frmN ame stat eme nt. The
at the File.
ds S trea mR ead er, Stre am Wri ter, and
insert the prefix "IO ." before the wor

lean
ames. txt, a file of names. The Boo
Example 3 The followin g program man ages N e ente red in the
nam
e if the fi le N ame .txt ex ists and the
fun ctio n Isln File retu rns the va lue Tru
text box is in the fi le.
PROPERTY SETTING
OBJECT

a M anage Fil e ~~ 8 ~ ~ frmN ames Tex t Man age File


lblName Tex t Nam e
Name:
txtN ame
Tex t Add Person to Fil e
bmA dd
Add Person to Rle
btnD eter min e Tex t Dete rmin e if Person
is in Fi le
Determine if Person is in Rle btnDelete Tex t Dele te Person from File

Delete Person from Rle

tor
Imp orts Sys t em .IO 'Ap pea rs at top of Cod e Edi

( ... ) Han dles btn Add .Cli ck


Pri vat e Sub btnA dd_ Cli ck
file
'Add a per son 's nam e to the
= t x t Nam e.Te xt
Dim p e rs on As Str ing
If per s o n < > "" The n
If Isi nFi le(p ers on ) The n , "Al ert" )
" is alre ady in the file ."
Mes sage Box .Sho w(p erso n &
Els e )
Fil e . App end Tex t ( "Na mes . txt"
Dim sw As Stre amW rite r
sw . Wr iteL ine (pe rso n)
sw. Cl ose () e Add ed" )
" add ed to file ." , "Nam
Mes sage Box .Sho w (per son &
tx t Nam e.C lear ( )
txtN ame . Foc us ( )
End If
Els e atio n Inc omp lete " )
t ent er a nam e.• , "In form
Mes sage Box .Sho w( "Yo u mus
End If
End Sub
erm ine . Cl i ck
Cl ick ( .. . ) Han dles btn Det
Pri vat e Sub b tnD eter min e _
in the file
'De term ine if a per son is
tNam e .Te x t
Dim p e rs on As Str ing = tx
8.2 Strea m Read ers, S tream Writ ers, and S tr
uctu red Exce pt ion H and li ng
• 371

If pers on < > "" Then


If Isin File (per son ) Then
Mes sage Box .Sho w(p erso n & " is
in the file .• , "Yes " )
Else
Mes sage Box .Sho w(p erso n & " is
not in the file ." , "No" )
End If
Else
Mes sage Box . Show ( "You mus t ente
r a nam e." , "Inf orm atio n Inco
mpl ete" )
End If
txtN ame .Cle ar()
txtN ame . Focu s ()
End Sub

Priv ate Sub btnD elet e Clic k(


... ) Han dles btnD elet e.C lick
'Rem ove the pers on in text box
fron tle file
Dim pers on As Stri ng = txtN ame
.Tex t
If pers on <> "" Then
If Isin File (per son ) Then
code to Lem ove per o
Dim sr As Stre amR eade r File . Ope nTex t ( "Nam es. txt" )
Dim sw As Stre amW riter File . Crea teTe xt ( "Tem p. txt" )
Dim indi vidu al As Stri ng
Do Unt il sr.E ndO fStr eam
indi vidu al = sr . Read Line
If indi vidu al < > pers on Then
sw.W rite Lin e(in divi dua l)
End If
Loop
sr.C lose ()
sw . Clo se()
File . Del ete ( "Nam es. txt" )
File .Mov e ( "Tem p. txt" , "Nam es.
txt" )
Mes sage Box . Sho w(p erso n & " remo
ved from file ." , "Nam e Rem oved
Else ")
Mes sage Box .Sho w(p erso n & " is
not in the file ." , "Nam e Not
End If Foun d" )
Else
Mes sage Box .Sho w( "You mus t ente
r a nam e." , "Inf orm atio n Inco
End If mpl ete" )
txtN ame .Cle ar()
txtN ame . Focu s ()
End Sub

Fun ctio n Isin File ( ByV al pers


on As Stri ng ) As Boo lean
'Det erm ine if pers on is cur ren
tly in a file nam ed Nam es.tx
If File . Exi sts( "Na mes .txt" ) t
Then
Dim sr As Stre amR eade r = File
.Ope nTe xt( "Na mes .txt" )
Dim indi vidu al As Stri ng
Do Unt il sr.E ndO fStr eam
indi vidu al = sr.R eadL ine
If indi vidu al = pers on Then
sr . Clos e ()
Retu rn True
End If
Loop
Cha pter 8 Tex t Fil es
372 •
sr.C los e()
End If
Ret urn Fal se
End Fun ctio n
the prog ram , clic k
, de lete som e nam es, or sea rch fo r so me names. Aft er term inat ing
[Run, add All Files butt on, and
Explore r window, cl ick on th e View
on the Refresh butt on in the Solution
subfolder.]
look at N ame .txt in the bin \Debug

Structured Exception Handling


oun ter whe n it exe-
are two cate go ries of prob lem s that a software prog ram might enc
The re as inte nd ed. Com -
first is a logic erro r, whi ch is caused by cod e that does not perfo rm
cutes. The access ing the wro ng
typos, using the wrong fo rmula, and
mon exa mples of log ic erro rs are urs due to circ um-
is an exce ption , whi ch typicall y occ
prope rty va lue. The seco nd category are whe n inva lid
nd the prog ram 's con tro l. Two situ atio ns whe re exc epti ons occ ur
stan ces beyo sho wed ano ther way to
not be accessed. (In C hap ter 4, we
data are inpu t and wh en a file can rs a wo rd wh en th e
occ urri ng. ) Fo r exa mpl e, if a user ente
prev ent inva lid-d ata exc epti ons from ram term inat es abru ptly.
exc epti on is gen erat ed and the prog
prog ram prom pts for a num ber, an . If the use r had fo l-
situ atio n , the prog ram mer did not emp loy faul ty log ic or mistype
In this at fault, how-
ctio ns, no prob lem wou ld hav e occ urred . Eve n tho ugh the user is
lowed th e dire and to incl ude cod e to
ons ibility to anti c ipat e exc epti ons
eve r, it is still the prog ram mer 's resp
work arou nd the ir occ urre nce. s can use to find
Vis ual S tudi o env iron men t con ta ins powerful tools that prog ram mer
The ppe ndix D. Thi s sect ion
too l are disc usse d ex tens ive ly in A
and co rrec t bugs. The e debugg ing ram min g term s, this is
te and dea l with exc epti ons (in prog
describes tech niqu es used to anti c ipa
call ed "ha ndli ng exc epti ons") . prog ram mer does
une xpe cted prob lem cau ses Visu a l Bas ic to raise an exc epti on. If the
A n al Bas ic h and les an
dlin g cod e in the prog ram, then Visu
not exp licitly incl ude exce pt ion- han disp lays the exc ep tion 's
This han dler term inat es exe cuti on,
exc eption with a defa ult han dler. n occ urre d . Con side r a
the line of cod e whe re the exc e ptio
message in a window and high ligh ts
cod e:
prog ram that con tain the follow ing

Dim tax Cre dit As Dou ble


e.C lick
ck( ... ) Han dles btn Com put
Pri vat e Sub btnC omp ute_ Cli
ger
Dim num Dep end ents As Inte ))
utB ox( "How man y dep end ents ?"
num Dep end ents = Cin t (Inp
end ents
tax Cre dit = 100 0 * num Dep
End Sub
clic k on the OK
leav e the inpu t dialog box blan k and
A user with no depend ents mig ht just in Fig. 8.5. (Th e
so, Visu a l Bas ic term inat es the prog ram and displays the box sh own
butt on. If emp ty stri ng ,
cau sed by the fact that the defa ult valu e in an inpu t dialog box, the
problem was g as their defa ult va lu e. )
Tex t boxes also h ave the emp ty strin
can not be con vert ed to an integer. wn whi le exe cuti ng the
cod e, sinc e the exc epti on was thro
It also high ligh ts the four th line of d in an answer like
func tion . The prog ram also wou ld hav e cras h ed had the user type
C lnt
"TWO". pro tect ing the cod e
han dles the prev io us exc epti on by
A mo re robu st prog ram exp lic itly rdless of whe ther o r not
allo ws the prog ram to con tinu e rega
in a Try -Ca tch -Fin a lly bloc k. Thi s bloc k. A s oo n
o n was thro wn. The co mpu ter tries to exe cute the cod e in the Try
an exc epti k. Regardl ess of whe ther
jum ps to the cod e in the Ca tch bloc
as an exc epti on occ urs, exe cut ion
8.2 StreamReaders , StreamWriters, and Structu red Exception Hand ling
• 373

InvalidCastExce ption was unhandled


Conversion f rom string '"' to type 'Integer ' is not vali d .

Trouble shootin g tips:


::w.E~~:: ~~~ii~:si:hg;:r.;:: ~::6.Y.:6.l.~:~:r: :i&.~::v.:~ :i Y.:~::;:r.;:y~f~:~: ~::6.Y.:~~:~i:::~:~~ :~Fa.:6.::; ~f:i~:i ::: :
Make sure the source type· s convert ible to the destinat ion type
Get general help for this exceptio n.
InnerException: Make sure your method argume nts are m the nght
format.
InnerException: When convert ing a stnng tc Date Time, parse the
strmg tc taketh
l-- ---
Search for more Help Online ...

Actions :
View Detail
1._Co_Py exception detail to the clipboard
FIGURE 8.5 Excepti on handled by Visual Basic.

an except ion occurred, the code in the Fin ally block is th en execut
ed. The fo llowing code is
illustra tive:
Dim taxCr edit As Double
Privat e Sub btnCom pute_ Click( ... ) Handle s btnCo
mpute .Click
Dim nurnDe penden ts As Intege r , messag e As String
Try
nurnDe penden ts = Cint (Input Box( "How many depen dents?
" ))
Catch
messag e = "You did not answer the questi on with
an " &
"integ er value. We will assume your answer is
zero."
Messag eBox . Show(m essage , "Impro per Respon se" )
nurnDe penden ts = 0
Finall y
taxCr edit = 1000 * nurnDe penden ts
End Try
End Sub

This type of except io n h and li ng is known a data validat ion .


It ca tch es itu at ions where
invalid da ta cannot be conve rted to a part ic ular type. A n except
ion is th rown if th e user ente rs
data tha t cannot be conve rted to an integer using th e C ln t funct
ion . Ta ble 8. 1 o n the next page
li ts several except io ns a nd descrip tions of wh y they a re thrown
.
The Ca tch block a bove wi ll be execut ed wh e n any except ion
occurs. V isual Bas ic a lso
a llows Try-Ca tc h -Finall y b locks to h ave on e or more spec ialized
Catch cla uses th at h and le o n ly
a specific type of except ion . T h e gen era l form of a spec ialized Ca
tch clause is
Catch exc As Excep tionTy pe

whe re the varia ble exc will be ass ign ed th e n ame of the except
io n . The code in this block will
be execut ed on ly whe n the pecifie d except ion occurs .
The gen e ral fo rm of a Try-Ca tch -Finall y block i
Try
norma l code
Catch excl As Fi rstEx ceptio n
excep tion-h andlin g code for FirstE xcepti on
374 • C hapter 8 Text Files

lfi!:JIJ:IM Some common exceptions.


Excep tion Name Descr iption and Examp le

Argum entOu tOfRa ngeExcept ion A n argu ment to a method is out of range.
str = "Good bye" . Subs tring (l2,3 )
I ndexO u tOfRa ngeEx ceptio n A n array's sub cript is o ut of range .
Dim arr (3) As Integ er
ar r ( 5) = 2
In va IidCast Excep tion A va lue canno t be conve rted to anoth er type .
Dim num As Integ er = Cint ( "one" )
Nu llRefe renceE xception A method is called on a variab le that is et to Noth ing.
Dim str As Strin g, len As Integ er
len = str.L ength
Overflow Excep tion A num be r too big fo r the data type is assign ed.
Dim num As Integ er = 2 00000 0000
num = 2 * num
I0. DirectoryN otFou nd Excep tion A fil e within a miss ing fo lde r is accessed.
Dim sr As IO . Strea mRea der =
)
IO . File.O penT ext(" C: \ BadD ir \ File. txt"
IO.Fil eNotF oundE xception A miss ing file is acces ed.
Di m sr As IO.St reamR eader =
I O. Fil e . Open Text( "Miss ing . txt")
IO .IOEx ceptio n Any file- hand ling excep tion , includ ing those mentioned
e an
above. For instance , an attemp t is made to delete or renam
a closed fi le to an alread y used
open file, to change the name of
ified conta ins nodi k. Note: If
name, or when a disk d ri ve spec
tested with Catch cla uses,
a series of IO excep tio ns is be ing
thi s excep t ion should be th e last one tested.
e)
IO .Fil e. Mov e(fil espe c, Alrea dyEx ist i ngNam

Catch exc2 As Se c ondEx cepti on


e p ti on
excep tion - h andli ng code for Sec ondEx c

Catch
e xc eptio ns
excep t ion - hand ling code f o r any rema ining
Fina lly
c lean- up code
End Try

r excep tions. If an excep tion occur s


The normal code is the code that you want to monit or fo
n, Visua l Basic transfe rs contro l to the
dur ing execu tion of any of the state ments in this sectio
block, the Catch clauses are considered
code in one of the Catch blocks. A with a Selec t Ca e
d. T he last Catch clause in the preced-
one at a time until the first matchi ng excep tion is locate
ing code funct ions like the Case Else clau e. The clean-
up code in the Finall y block always exe-
has execu ted. In most situations, this
cutes last regard less of wheth er any exception-handling code
d du ring the normal code. If clean -up is
code cleans up any re ources uch as files that were opene
Howeve r, to comp lete a Try block, a
not necessary, then the Finall y block can be omitt ed.
Catch block or a Finall y block must appear.
8.2 StrcamReaders, Stream W riters, and Structu red Exception H andli ng • 375

ln addition to data validation , a popular use of exception hand ling is to account for errors
when accessing files. Visual Bas ic has th e capab ility to access files sto red on remote se rvers via
the Internet. A n exception is th rown if a desired file is mi sing (IO. FileN otFoundExcept ion ) or
if th e file cannot be read beca use the Internet connection between the computer and the serve r
is broken (IO .IO Exception) .

Example 4 The following program reads the first line fro m a file on a CD. The program
expects the file to res ide in the folder DataFiles of the C D. Note that the clean-up code,
sr. close ( l , in the Finally block is enclosed in a Try-Catch block of its own. This protects the
C lose method fro m any excep tions that might occur.

Private Sub btnDisplay_ Click( ... ) Handles btnDisplay.Click


Dim sr As IO . StreamReader
Dim message As String
Try
sr = IO . File.OpenText( "E:\DataFiles\US Pres.txt" )
message = "The first President was " & sr.ReadLine & " "
MessageBox.Show( message, "President" )
Catch exp As IO.DirectoryNotFo undException
message= "The requested folder is not on the CD."
MessageBox.Show( message, "Error" )
Catch exp As IO.FileNotFoundE xception
message= "The file is not in the specified folder of the CD."
MessageBox.Show( message, "Error" )
Catch exp As IO.IOException
message= "Check to see if there is a CD in drive E:."
MessageBox.Show( message, "Error" )
Finally
Try
sr. Close()
Catch
' 1~ ·egard any exceptions during the Close() method

End Try
End Try
End Sub

[Remove the C D fro m the E: drive, run the program, and then click on the button .]

Erro r

Ch eck to see if th ere is a CD in drive E.:.

OK
376 • Chapter 8 Text Files

[In ert the CD containing the file USPres. txt (in the folder DataFiles) in to theE: drive and then
click on the button.]

residen

The fir>t Presid ent was George •Va5 hin gton.

OK

Comments
1. Any variable decla red within a Try-Catch-F inally block has bl ock- level scope. That is, it
will not be ava ilab le after the block terminates.
2. Text fi les are also called sequential files because a SteamReade r reads the records one at a
time in sequence.

1. Give three different ways to display the last record of the file USStates.tx t in a message box.
2. Consider the fo llowing event procedu re.
Pr ivate Sub btnCreate_ Click( ... ) Handle s btnCreate. Click
Dim sw As IO.StreamW riter = IO.File . CreateText ("ABC.txt" )
sw . WriteLine( "abc")
End Sub

Describe the file ABC. txt after the button is pressed.

In Exercises 1 through 10, determine the output displayed in the text box when the button
is clicked.
1. Private Sub btnDisplay_ Click( .. . ) Handles btnDisplay .C lick
Dim salutati on As String
Dim sw As IO.StreamW r i ter = IO . File.Cr eateText(" Greetings. txt")
sw.WriteLi ne("Hello" )
sw.WriteL ine("Aloha ")
sw.Close()
Dim sr As IO.StreamR eade r IO.File . OpenText( "Greetings .txt")
salutation = sr.ReadLin e
txtOutput. Text = salutat i on
sr.Close ()
End Sub
treamRea ders, Stream Writers, and tructured Exception Handling
8.2
• 377

2. Private Sub btnDisp lay_ Click(oo ol Handles btnDisp layoClic k


Dim salutati on, welcome As String
Dim sw As IOoStre amWrite r = IOoFile oCreate Text("G reetings otxt")
swoWri teLine(" Hello")
sw Wri teLine ("Aloha" )
0

swo Close ()
Dim sr As IOoStrea mReader IOoFile oOpenT ext("Gr eetingso txt")
salutat ion = sroRead Line
welcome = sroRead Line
txtOutp utoText = welcome
sr oClose ()
End Sub

30 Private Sub btnDisp lay_ Click(oo o) Handles btnDisp layoCli ck


Dim salutat ion As String
Dim sw As IOoStre amWrite r IOoFile oCreate Text("G reetings otxt")
swoWri teLine(" Hello")
swoWrit eLine("A loha")
swoWrit eLine("B on Jour")
swoClos e()
Dim sr As IOoStrea mReader IO oFileoO penTex t("Gree tingsotx t")
Do Until sroEndO fStream
salutat ion = sroRead Line
txtOutp ut oText = salutat ion
Loop
sro Close ()
End Sub

40 Assume that the contents of the file G ree tings. txt are as shown in Figure 8.6.

Hello
Aloha
Bon Jour
FIGURE 8.6 C ontents of the file Greetingsotxto

Private Sub btnDisp lay_ Click(oo o) Handles btnDisp layoClic k


Dim file, welcome As String
file = "Greeti ngsotxt "
Dim sw As IOoStre amWrite r = IOoFile oAppen dText(fi le)
swoWrit eLine("B uenos Dias")
swoClos e()
Dim sr As IO oStream Reader IO oFileoO penTex t(file)
For i As Integer = 1 To 4
welcome = sr oReadLin e
txtOutp utoText = welcome
Next
sroClos e()
End Sub

50 Private Sub btnDisp lay_ Click(oo o) Handles btnDisp layoClic


k
Dim num As Integer
'Assume that txtBox is empty
378 • Chapte r 8 Text Fil es

Try
num = Cint(t xtBox .Text)
txtOu tput.T ext = "Your numbe r is " & num
Catch
txtOut put . Text "You must enter a numbe r."
End Try
End Sub
splay. Click
6. Privat e Sub btnDis play_ Click( ... ) Handle s btnDi
", "Mexic o"}
Dim nafta( ) As String = {"Cana da", "Unite d States
Try
" & nafta( 3)
txtOu tput.T ext = "The third membe r of NAFTA is
Catch exc As IndexO utOfRa ngeEx ception
txtOu tput.T ext = "Error occurr ed."
End Try
End Sub

7. Privat e Sub btnDis play_ Click( ... ) Handle s btnDi splay. Click
Try
Dim usPop As Intege r = 304000 000 'Appro x popul ation of U.S.
Dim worldP op As Intege r
worldP op = 21 * usPop
txtOu tput.T ext = CStr(w orldPo p)
Catch exc As Argum entOut OfRan geExce ption
txtOu tput.T ext = "Oops"
Catch exc As Overfl owExc eption
txtOu tput.T ext = "Error occurr ed."
End Try
End Sub

8. Privat e Sub btnDis play_ Click( ... ) Handle s btnDi splay. Click
tter As String
Dim flower As String = "Boug ainvil laea", lastLe
Try
lastLe tter = flowe r.Subs tring( l4, 1)
txtOu tput.T ext = lastLe tter
Catch exc As Invali dCastE xcepti on
txtOu tput.T ext = "Oops"
Catch exc As Argum entOut OfRan geExce ption
txtOu tput.T ext = "Error occurr ed."
End Try
End Sub
the folder bin and the fir t
9. Assume that the file Ages. txt is located in the Debug subfold er of
line of the file is "Twent y-one" .
splay. Click
Privat e Sub btnDis play_ Click( ... ) Handle s btnDi
Dim sr As IO.Str eamRe ader
Dim age As Intege r
Try
sr = IO.Fil e .OpenT ext ("Ages .txt") 'FileN otFoun d if fails
age = Cint(s r.Read Line) 'Inval idCas t if fails
txtOu tput.T ext = "Age is " & age
Catch exc As IO.Fil eNotF oundE xcepti on
txtOu tput.T ext = "File Ages. txt not found"
8.2 Strea mReade rs, Strea m Write rs, and Struc tured Excep
t ion H andlin g • 379

Catc h exc As Inva lidC astE xcep tion


txtO utpu t.Tex t = "File Ages .txt cont
ains an inva lid age . "
Fina lly
Try
sr.C lose( ) 'This code exec utes no matt
er what happ ens abov e
Catc h
'Disr egar d any exce ption s throw n durin
g the Clos e() meth od
End Try
End Try
End Sub

10. Redo Exerc ise 9 with the assumption that the


file Ages. txt is not locat ed in the Debug sub-
folde r of the folde r bin.
11. As ume that the conte nts of the file Gree tings
.txt are as show n in Figur e 8.3 (on page 356) .
Wha t is the effect of the following program?

Priv ate Sub btnD ispla y_ Click ( ... ) Hand


les btnD ispla y.Cl ick
Dim g As Strin g
Dim sr As IO.S tream Read er IO.F ile.O penT ext(" Gree tings . txt")
Dim sw As IO.S tream Writ er IO.F ile.C reate Text ("We lcom e.txt ")
Do Unti l sr.En dOfS tream
g = sr.Re adLi ne
If (g <> "Alo ha") Then
sw.W riteL ine(g )
End If
Loop
sr.C lose ()
sw. Clos e ()
End Sub

12. Ass ume that the file Names. txt conta ins a list
of name in alpha bet ical ord er. Wha t is the
effect of the Myste ry funct ion ?

Priv ate Sub btnF ind_ Click ( . . . ) Hand


les btnF ind . Click
Mess ageB ox.Sh ow(C Str(M yster y("L aura"
)))
End Sub

Func tion Myst ery(B yVal name As Strin


g) As Bool ean
Dim sr As IO.S tream Read er IO . File . Open Text ("Nam es. txt")
Dim input Name As Strin g
Dim miss ingF lag As Bool ean False
Do Unti l sr.En dOfS tream
input Name = sr . Read Line
If input Name = name Then
Retu rn True
Else if input Name > name Then
Retu rn False
End If
Loop
Retu rn False
End Func tion
380 • Chapter 8 Tex t File

of the file
any erro rs. Ass ume that the cont ents
In Exe rcises 13 thro ugh 18, iden tify
Gre etin gs.tx t is as show n in Fig. 8.6.
... ) Han dles btnD ispl ay.C lick
13. Priv ate Sub btnD ispl ay_ Clic k( Gre etin gs.t xt)
IO.F ile.A ppe ndT ext(
Dim sw As IO.S trea mW riter =
sw.W riteL ine( "Gu ten Tag" )
sw . Clo se()
End Sub

... ) Han dles btnD ispl ay.C lick


14. Priv ate Sub btnD ispl ay_ Clic k(
Dim term As Stri ng xt")
IO.F ile.C reat eTe xt(" Gre etin gs.t
Dim sw As IO . Stre amW riter
term = sw.R eadl ine
txtO utpu t.Te xt = term
sw . Clo se()
End Sub
lick
k( ... ) Han dles btnD ispl ay.C
15. Priv ate Sub btnD ispl ay_ Clic New Gre et.tx t
Gre etin gs.t xt into the file
'Cop y the con tent s of the file
Dim nam e, gree ting As Stri ng .txt ")
IO.F ile.O pen Tex t("G reet ings
Dim sr As IO.S trea mRe ader
name = "Ne wGr eet. txt"
IO. File . Cre ateT ext ("na me" )
Dim sw As IO.S trea mW riter
Do Unt il sr.E ndO fStr eam
gree ting = sr.R eadL ine
sw.W r i teLi ne(g reet ing)
Loop
sr.C lose ()
sw. Clos e ()
End Sub

... ) Han dles btnD ispl ay.C lick


16. Priv ate Sub btnD ispl ay_ Clic k( xt(" Gre etin gs.t xt")
Dim sw As IO.Strea mRe ader = IO.F ile.C reat eTe
"Gr eeti ngs .txt ".C lose ()
End Sub
k
k( ... ) Han dles btnD ispl ay . Clic
17. Priv ate Sub btnD ispl ay_ Clic
Try
Dim age As Inte ger
r age . "))
age = Cin t(In putB ox(" Ente r you
Catc h
.")
Mes sage Box .Sho w("I nval id age
End Try
age & " yea rs old" )
Mes sage Box .Sho w("Y ou are " &
End Sub

... ) Han dles btnD ispl ay.C lick


18. Priv ate Sub btnD ispl ay_ Clic k(
Dim sw As IO.S trea mW riter
Try
kes .txt ")
sw = IO. File .Cre ateF ile( "E: \La
Catc h IO.I OEx cept ion
CD in the E: driv e?")
Mes sage Box .Sho w("I s ther e a
End Try
8.2 Strea mReaders, Stream Wri ters, and Structured Exception
Hand ling • 381

sw.C lose( )
End Sub
Exerc ises 19 throu gh 25 are related and use the
data in Table 8 .2. The fil e creat ed in Exer-
cise 19 shou ld be used in Exerc ises 20 throu gh
25.
19. Write a program to creat e the text file Cowboy.
txt conta ining the inform at ion in Table 8.2.

ltr1:Jif:IW Prices paid by cowboys for certain items in mid-1800s.


Colt Peacemaker 12.20
Holster 2.00
Levi Strauss jean 1.35
Saddle 40.00
Stetson 10.00

20. Suppose the price of sadd les is red uced by 20%.


Use the file Cowboy.tx t to creat e a fi le,
Cowb oy2.t xt, conta ining the new price list.
21 . Write a program to add the data Winc hester Rifle,
20.50 to the end of the file Cowboy. txt.
22. Suppose an order is placed for 3 Colt Peace
make r , 2 Ha l ters, 10 pairs of Levi Straus
jeans, 1 Sadd le, and 4 Stet ons. Write a program to
perfo rm the fo llowing tasks:
(a) Crea te the file O rd er.txt to hold the numb ers 3,
2, 10, 1, and 4.
(b) Use the files Cowboy. txt and Order. txt to d isp
lay a sa les rece ipt with three colum ns
giving the quan t ity, name, and cos t for each item
ordered.
(c) Com pute the tota l cost of the item and disp lay
it at the end of the ales receipt.
23. Write a program to req uest an add itiona l item
and price from the user. Then creat e a file
called Cowb oy2.t xt conta ining all the informat ion
in the file Cowb oy.tx t with the addi-
tiona l item (and price) inserted in its prope r alpha
betic al eq uence. Run the program for
both of the follow ing data item : Boots, 20.00 and
Horse, 35.00.
24. Write a program to allow addit ional items and
prices to be input by the user and added to
the end of the fi le Cowboy. txt. Include a meth od
to termi nate the process.
25. Write a program using a Strea mReader that disp
lays the co ntents of the fi le owboy.txt in
a DataG ridVi ew contr ol.
26. Visua l Basic cann ot delete a file that is open.
Attem pting to do so generates an excep tion.
Write a short program that uses struc tured excep tion
hand ling to handle such an excep tion.
In Exerc ises 2 7 throu gh 32, write a progr am to
carry out the task witho ut using arrays or
LINQ . Assu me that the file Num bers. txt conta ins
a list of integers.
27. Display the numb er of numbers in the file Num
be rs.txt.
28. Display the largest numb er in the file Num bers.
txt.
29. Display the small est numb er in the fi le Num bers
.txt.
30. Display the sum of the numb ers in the fi le Num
bers. txt.
31. Display the average of the numbers in the file
Numbers. txt.
32. Display the last numb er in the file Num bers. txt.

Solutions to Practice Problems 8.2

1. First: Dim sr As IO. Strea mRea der IO.F ile . Open Text( 11 USS tates .txt 11 )
Dim temp As Strin g = 1111
382 • Cha pter 8 Text Files

Do Unt il sr.E ndO fStr eam


temp = sr.R eadL ine
Loop
Mes sage Box .Sho w (t emp )
sr. Clos e ()
.txt ")
IO.F ile.R ead AllL ines ("U SSt ates
Second: Dim stat es() As Stri ng=
Mes sage Box .Sho w(st ates .Las t)
")
ile.R ead AllL ines ("U SSt ates .txt
Third: Dim stat es() As Stri ng= IO.F
Cou nt- 1))
Mes s ageB ox.S how (sta te s (sta tes.
e fil e wi ll be empt y. ln o rd er for
program's bin \Debug fo lder. How eve r, th
2. The file AB .txt will be prese nt in the e () must be execu ted.
e state ment sw . Clos
th e string abc to be placed in the fi le, th

8.3 XM l
mandat d
l. However, the expa n ion of the Inte rnet
As we have seen , CSV fi les are quit e usefu Con sort ium reco m-
ting data . The World Wid e Web
a standard text file form at for tran smit
Markup Language ) to be that stan dard.
men ds a format called XML (eXtensible lines
look at a text file cons istin g of the first two
Con side r the CSV file USS tate s. txt. Let's
the new file are
of USS tate s. txt. Tha t is, the two lines of

Dela war e,DE ,l95 4,75 900 0


0
Pen nsyl vani a,PA ,448 17,1 229 600
showed
wha t each fi eld represen ts. How ever, if we
We are fam iliar with the e reco rds and know rma tion . One way to
know how to inter pret the info
this file to someone else, they migh t not
d form at wou ld be as fo llows:
pres ent it in great deta il and in an orga nize
u.s. Stat es
stat e
nam e: Dela ware
abb revi atio n: DE
area : 1954
pop ulat ion: 7490 00
stat e
nam e: Pen nsyl van ia
abb revi atio n: PA
area : 4481 7
pop ulat ion: 1229 600

Format of XMl Files


above, is as
h has th e look and fee l of the prese ntation
The XML format for the state data, whic
Vid eo Note
follows:
XML
<? xml vers ion= ' l.O ' ?> -->
on two of the 50 U.S. stat es.
<!-- This file con ta1n s data
<us stat es >
<sta te >
<nam e >De lawa re </na me >
n>
<ab brev iatio n >DE </ abb revi atio
<are a >195 4 </ area >
>
<po pula tion >749 000 </ pop ulat ion
</ stat e >
8.3 XML • 383

<sta te >
<name >Pen nsylv ania< /name >
<abb revia tion>PA</ abbr evia tion >
<area >44817 </ area >
<pop ulati on>1229600 </po pula tion>
</ state >
</ us_s tates >

Comments on XML format


1. Don 't be conce rned abou t the coloriza tion. lf the
file is creat ed in the Visua l Bas ic l DE and
given th e ex tensio n ".xml ", Visua l Bas ic will autom
atica lly color it .
2. The first line ident ifies the forma t of the file.
3. The econd line is a comm ent and is treated like
any Vi ual Bas ic comm ent. It may appea r
anywhe re in th e file, is colored green, and will be
totall y ignored by any program access ing
the file. Co mme nts start with <!- - and end with
--> .
4. A line such as <area >1954 </are a > is called
an elem ent and the bracketed entiti es are called
tags. Spec ificall y, <area > is the start tag for the eleme
nt and </are a > is the end tag. The two
tags are ident ical excep t for the prese nce of a forwa
rd slash (/) following the less-t han sign in
the end tag. The word inside the bracket , in this case
area, is called the name of the element.
T he text surro unded by the two tags, in this case 1954,
is called the conte nt of the eleme m .
5. Elem ent names are case sensitive. For insta nce,
the tag <Are a > is different than the tag
<area >. Also, sta rt and end tags must have the same
case.
6. Elem ent names sh ould conv ey the mean ing
of the conte nt of the element. Element names
cann ot start with a numbe r or punc tuatio n character
and can conta in numbe rs and charac-
ters. H oweve r, they ca nnot conta in spaces and cann
ot start with the letters xml.
7. In the XML file above, the conte nt of the elem
ents name, abbreviation, area, and population
is text. However, the conte nt of an elem ent can
be other elem ents. For instan ce, in the
XML file above ,
<sta te >
<name >Dela ware </name >
<abb revia tion >DE </ abbr evia tion >
<area >1954 </are a >
<pop ulati on>749000 </po pula tion>
</ state >
is such an ele ment . Its start tag is <sta te > and its
end tag is </ state >. The elem ents that
const itute its conte nt are aid to be its child ren.
For insta nce, we say that name is a child
of state. W e also say that state is a paren t of name
, and that name and abbreviation are
siblin gs.
8. The elem ent us_sta tes is ca lled the root elem ent of
the file. An XML file can have only one
roo t ele ment .

LINQ to XML
LINQ ca n be used with XML fil es in mu ch the
sa me way as wi th CSV fil es-w ith three
diffe ren ces:

1. ln tead of being loade d into an array, the


file is loaded into an XEle ment obj ect with a
sta teme n t of th
e fo rm
Dim xmlE lemen tNam e As XElement XEle ment .Loa d(fil espe c)
384 • Chap ter 8 Text Files

to be cons idered- namely, the child


ren of each
2. The From clause references the elements
chi ld of the root element.
n of
the value of a field , queries use an expressio
3. Instead of using the Split meth od to ex tract
the fo rm <c h i ldNa me >. Va lue.

show n abov e to all 50 states. The


Example 1 T he file USS tates.x ml ex tend s the reco rds n with
popu lat ion dens it ies of the states that begi
fo llow ing program uses the fi le to d isplay the
dec reas ing ord er of their dens it ies.
the word North. The states are displ ayed in
.. . ) Han dles btnD ispl ay .C lick
Priv ate Sub btnD ispl ay_ Clic k (
XEl emen t . Load ( "US Stat es.x ml" )
Dim st ateD ata As XEle ment =
ta.D esce ndan ts( "sta te" )
Dim que ry= From st In s t a teDa
Let name = st . <n ame > . Valu e
Let pop = Cint (s t . <pop ulat ion > .Val ue)
Let area = Cint ( s t . <are a > .Val ue)
Let den sity = pop / area
mbe r(de nsi ty )
Let form atted Den s ity = Form atNu
Orde r By dens i ty Desc endi ng
)
Whe re name . St ar t s With ( "No rth"
Sele ct name , fo rmat tedD ens i ty

dgv Stat es .Da t aSou rce = quer y .ToL ist


dgv S t at e s .Cur rent Cell = Noth ing
erTe xt = "Sta te"
dgv S t a te s . Co l umn s( "nam e" ) . Head "De nsity "
ensi ty" ) .Hea derT ext
dgvS ta t e s.Co lumn s( "for matt edD
End Sub

[Run , and click on the butto n.]

g-j lJ.S. State s

Display State s

State Density

North Caroli na 156.37

North Dakot a 9.09

ion 8. 1 uses an XML fi le rathe r


Example 2 The following rewr ite of Exa mple 7 in Sect not
n class- level scope so that the XML file will
than a CSV file. The varia ble stateData is give
ev iatio n is ente red.
be reread from disk each t ime a new state abbr
men t. Load ( "US Stat es.x ml" )
Dim s t a teDa t a As XEle men t = XEle

Han dles btnF i nd . Clic k


Priv ate Sub btnF ind_ Clic k ( . . . )
ts ( "sta te" )
Dim que ry From st In s t ateD ata.D esce ndan
Let name = st. <nam e > .Val ue
ue
Let abbr = s t . <abb revi at i on > .Val
mtbA bbr. Text . ToU pper
Whe re abbr
Sele ct name
8.3 XML • 385

If quer y.Co unt 1 Then


txtNa me.T ext quer y.Fi rst
Else
Dim str As Strin g = " is not a valid
state abbr evia tion. "
Mess ageB ox .Show (mtbA bbr.T ext.T oUpp
er & str, "Erro r" )
mtbA bbr. Clea r ()
mtbA bbr.F ocus( )
End If
End Sub

[R un , enter a state abbre viatio n into the mask ed


text box, and click o n th e butto n.]

a~ U.S. Sta es l = l @) ~~ •.,]

State Abbreviation : CA

Find Name of State

Name: Califomia

Comments
1. The conte n t of an e lemen t can conta in any
characters excep t for" <" and "&". T hese ch ar-
actersmust be replaced with "&lt; " and "&amp; ", respe
ctive ly. For insta nce, the follow ing
two line migh t appea r in XML files :

<coll ege >Wil liam &amp; Mary </ colle ge


>
<ine qual ity > x &lt; ? </ ineq ualit y>

Practice· Problems 8.3

1. S uppose the q uery in Exa mp le 1 is repla ced by


Dim quer y= From st In state Data .Des
cend ants( "stat e")
Let name = st. <nam e > .Valu e
Let pop = st .<po pulat ion> .Valu e
Orde r By pop Desc endin g
Sele ct name , pop
Expla in why t his query will not display the states
in desce nd ing order of the ir population .
2. Cons ide r Examp le 2. S uppose the last line of the
q uery is chan ged to
Sele ct name , abbr

Wh at chan ge would have to be made to the follow


ing line?
txtNa me.T ext = query . Firs t

In Exercises 1 throu gh 6 , deter mine if the name is


a prope r name for an eleme nt of an XML file.
1. 7up 2. vice pres ident 3. 77 4. Fred 5. xmlT itle 6. ?mark
386 • C hapte r 8 Text Fil es

expr essio n is a prop er elem ent.


In Exer cises 7 thro ugh 10, dete rmin e if the
7. <beg in >He llo</ e nd> 8. <Tea m>O akla nd Raid ers< /tea m>
10. <first name>Jo hn< /first name>
9. <city>N ew York <city>
.txt are
11. T he first two lines of the file AgeA tl naug
Geor ge Was hing ton,5 7
John Adam s,61
reate
president and his age whe n inaugura ted. C
whe re each reco rd has two field s-na me of
an XML fil e cont aining these two reco rds.
12. The first two li ne of the file ] ustic
es .txt are
006, 0
Samu el,A lito, Geo rge W. Bu s h , NJ,2
A,l8 30,1 84 4
Henr y, Bald win, And rew J acks on,P
las t nam e, appo in t ing pres ide n t , the state
whe re each reco rd has six field s-first n ame,
appo inted, a nd yea r they left the co urt. (For
from whi ch the justi ce was appo inted , year
C rea te an XM L file co ntai n ing these two
sitti ng judges, the las t field is se t to 0.)
reco rds.
info rma-
ram to extract and disp lay th e requ ested
In Exer cises 13 thro ugh 20 , write a prog
tion from the file USS tates .xml.
s in the year 2000 .
13. The total populatio n of the U n ited State
14. The total area of the Un ited States.
15. The pop ulat ion dens ity of the U n ited
Stat es.

16. The state (or states ) with the longes


t name.
area of
17. The states with area grea ter than 100,
000 squa re mi les. Display both the name and
r by area .
each sta te, with the states in decreas ing orde
latio n of
18. The states with popu latio n less than
one million. Disp lay both the name and popu
r by populatio n.
each state , with the states in increasing orde
the most J iffere nt vowe ls.
19. T he state (or states ) whose name cont ains lay
than the fi rst two lette rs of their names . Disp
20. The tates whose abbrev iat ion is diffe rent evia tion.
in alph abetical orde r by the abbr
both the name and abbrev iatio n of each state
een
colleges foun ded befo re 18 00. The first thirt
The file Coll eges .xml contains data on the
this fil e in Exer cises 2 1 thro ugh 24.
lines of the file are show n in Fig. 8 . 7. U se

<? xml v ersi on= 'l . O'? >


the earl iest U.S. coll eges - - >
<!-- This file cont ains data on
<col lege s >
<col lege >
<nam e >Har v ard U. </na me >
<sta te >MA< / stat e >
>
<yea rFou nded >l6 36< /yea rFou nded
</ coll ege >
<col l ege >
>
<nam e >Wi lliam &amp; Mary </na me
<sta te >VA< / stat e >
<yea rFou nded >l69 3 </ye arFo unde d>
</co lleg e>
FIGURE 8.7 Begi nnin g of the file Colleges.x ml.
8.3 XML • 387

21. W ri te a program that disp lays the colle


ges alph abeticall y orde red (alon g with their
foun ded ) that are in the state spec ified in a year
masked tex t box. See Fig. 8.8 .

a - Ea lies Coll eges l = I @] l;....l.J d


State : NY C1ick on the name of a college .
~--------
,
Bowdoin College
I Display Colleges
1 Brown U.
Columbia U.
S'tate : V

Colum bia U. 17>:: Dartmouth College Year


Hartv ick Colle ge 1797 Dickin son College founded : 1776
Uni cm Colle ge 1795 Georqetown U.

Hart•Nic:k College
Harvard U.

FIGURE 8.8 Poss ible o utcom e of Exer cise 21. FIGURE 8.9 Poss ible outco me of Exer cise 22.

22. Wr ite a program that prov ides informati


on abou t a college selec ted fro m a list box
use r. The college should be disp layed in alph by the
abetical ord er. See Fig. 8.9.
23. W rite a prog ram that fills a list box
with the years befo re 1800 in whic h colle
founded. Whe n the use r selects a year, the colle ges were
ges found ed that year should be displayed in
anot her list box. See Fig. 8. 10.

a -' Ea lie:>~ Coll eges D


J
a·lies ~ Colleges I = l @l l....a ' I
C1ick on a year.

IBoy,•doin College
U. of Tenne~;see
I Display Colleges
)
College State ....
Yale U.
Georgeto'l..n U.
U. of Delaware
CT
DC
DE
-
-y
U. of Georg ia GA ..
FIGURE 8.10 P ossible outc ome of Exer cise 23.
FIGURE 8.11 Outc ome of Exer cise 24.

24. W rite a prog ram that displays the colle


ges and their states in a Data G ridView cont
whe re the colleges are orde red alph abeti cally rol
by their state abbrev iatio ns and seco ndarily
by the year they we re fo und ed. See Fig. 8. 11.
25. The CSV file Sena te 111 .txt co nta ins
a reco rd fo r each mem be r of the 111 th U .S.
(The 11 1th U.S. Sena te was insta lled in 2009 Sena te.
. ) Each reco rd cont ains three fi elds -nam
state , and party affili at ion . Some reco rds in e,
the files are
John McC ain,A rizon a,R
Jose ph Lieb errn an,C onne cticu t,I
Kirs ten Gill ibra nd,N ew York ,D

(a) Write a prog ram that uses the fil e Sena te


lll.t xt and crea tes an XML file cont ainin g
same info rmation . the
388 • Cha pter 8 Text Files

es, stat es, and


L file from part (a ) to disp lay the nam
(b) Wri te a prog ram that uses the XM the ir stat e. The two
a Dat aGr idView orde red by
part y affiliatio n of all the sen ators in
ed by the ir first names.
sena to rs fro m each state shou ld be o rder
itters of all time in
stati stics for the top 25 ho me- run h
26. The file Top 25H R.xm l co ntains .
lines of the fi le are show n in Fig. 8.12
majo r leag ue ba ebal l. The first nine
iew con tro l in
con tent s of th is fi le in a Dat aGr idV
(a) W rite a prog ram that disp lays the
e runs h it.
descend ing o rder by the num ber of hom con ta inin g the
Top 25H R.x ml and crea tes a CSV file
(b) W rite a prog ram that uses the file
sam e infor mat ion.

<?xm l v ersi on= 'l.O '?> e -- >


on the all - time top 2 5 hom
<!- - Thi s file con tain s data r to 2010 . -- >
leag ue bas eba ll prio
<! -- run h i tter s in ma jor
<hom e run hitt ers >
<pl a y er >
<nam e>B abe Rut h</n ame >
<atB ats >83 9 9</ atB a ts >
<hom eRun s> 714 </ hom eRun s >
</p l aye r >

FIGURE 8.12 Beginning of the file Top 25H R.xm l.

Solutions to Practice Problems 8.3

1. T he prob lem is with the clause


lue
Let p op = st. <po pula ti on >.Va
cla use, local type infe rence wi ll
or nume ri c con versio n fun ction s in the
S ince there are no ari thm etic opera tors listed wil l be Rhod e Islan d , whose
hen the program is run , the first state
inte rpret pop to be a strin g va ri ab le. W
run as intend ed on ly if the cla use is
popu lat ion is 998,0 00. The prog ram will
ion > .Va lue )
Let pop = CD bl(s t. <pop ul a t

2. The line wou ld have to be chan ged


to

.nam e
txtN ame .Te x t = que ry.F i rs t

Deposits
8.4 A Case Study: Recording Checks and
tion of a qua lity
yo u thro ugh the des ign and imp lem enta
The purpose of this sect ion i to take ok man agem en t
agem ent. Tha t a use r-fri end ly chec kbo
prog ram fo r persona l chec kbo ok man al Bas ic's abi lity to
four pages of cod e clea rly shows Visu
prog ram can be writ ten in less than nce prog ram , sim-
rove the prod ucti vity of prog ram mers. lt is easy to imag ine an enti re fina
imp in on ly a few
prog ram s that hav e gen erat ed mill ions of doll ars of sa les, bein g wr itten
ilar to
weeks by using Visua l Bas ic !

Design of the Program


man age men t, they
ugh man y com mer cial prog ram s are ava ilab le for persona l fina nc ial
Tho k of tran sactions
the ir or igin al purp ose - keep ing trac
incl ude so man y be lls and whistles that sect ion was des igned
me obsc ured . The prog ram in this
and repo rting bala nce s-h ave beco os its and prod uces a
It keeps trac k of exp end itures and dep
spec ifica lly as a chec kbo ok prog ram. in Visual Bas ic.
of the tech niques and too ls ava ilab le
repo rt. The prog ram showcases man y
8.4 A Case Stud y: Reco rdin g Checks
and Depos its
• 389
The gen eral des ign goa ls fo r the prog
ram incl ude the follo win g abil ities
• Au tom atic ally ente r the use r's nam :
e on each che ck and depos it slip .
• Au to matically prov ide the nex
t con secutive che ck o r depos it slip
ove rrid e this fea ture if necessa ry. ) num be r. (Th e user can
• A utom atic ally prov ide the date.
(Again, this fea ture can be ove rridd
en.)
• Fo r each che ck, reco rd the paye
e, the amo unt , and opti ona lly a mem
o.
• For each dep os it slip, reco rd the
sour ce, the amo unt, and opti ona lly
a mem o.
• Display the curr ent bala nce at all
times.
• Prod uce a repo rt deta iling all tran
saction s.

User Interface
Wit h Visu al Bas ic, we can plac e a
replica of a che ck or dep osit slip on
user supp ly the info rma tion as if actu the scre en and let the
ally filling out a che ck or dep osit
the form in its che ck mod e. The Dat slip. Figure 8.13 sho ws
aGr idV iew con trol at the bo ttom of
to display a repo rt deta iling all the the form will be used
tran sact io ns. The purp oses of the four
box abo ve the Dat aGr idV iew con tro butto ns and the text
l are obvious.

g~ Chec
l=J@l l: s.

David Schn e1der


# 1

Date: 4/21/201Oj
Pi3'J' TO
.AmountS
Memo

[ Record This Oleck I [ Swftch to Deposfts I[ Repo rt


l0 Current Balance S1. .00

FIGURE 8.13 Template for entering a check.

The first time the prog ram is run , the


use r is aske d for his or h er n ame , the
and the num bers of the first che ck star ting ba lanc e,
and dep os it slip . Suppose the user 's
the star ting bala nce is $ 100 0, and nam e is Dav id Sch neid er,
both the first che ck num ber and dep
Figure 8.13 shows the fo rm afte r the os it slip num ber are 1.
fo ur piec es of info rma ti on are ente
the form looks like a che ck. The fo red. The upp er part of
rm has a colo r of ligh t blue whe n in
box is auto maticall y se t to today's date ch eck mod e. The Dat e
but can be alte red by the use r. The
amo unt, and opti ona lly a memo. user fills in the payee,
Wh en the user clic ks on the Reco
info rma tio n is writ ten to a tex t fil e, rd This Check butt on, the
the ba lanc e is upd ated, and che ck
To reco rd a depos it, the user clic ks num ber 2 appears .
on the Switch to Deposits butto n. The
as in Fig. 8.14 . The fo rm's t ide bar form then app ears
now read s Depos it S lip, the wo rds
Pay To cha nge to So urce ,
390 • Cha pter 8 Tex t Files

l = /@J _M

D_. Deposit Slip


f:l 1

David Schneide r
Date : 5/ 5/2010

AmountS
Source

Memo

[ Record This Depostt II Swttch to Checks II Report


II Qutt
I Current Balance S1 .000 .00

.
FIGURE 8.14 Tem plat e for ente ring a dep osit

the bot tom of the slip ,


the form cha nge s to ligh t ye llow. A lso, in the but ton s at
and the colo r of same way as a
Dep osit are inte rch ang ed. A deposit is reco rd ed in mu ch the
the words Check and the one in Fig. 8. 15 is disp layed
ck. W hen the ReJJort but ton is clic ked on, a report similar to
che
in the Dat aG ridView con tro l.

Recipient or Amount Balance


Transact ion Memo
Description Source
-~lS75.9 5
Date S924 .05
Land 's End shirts
4/21 /201 0 Check P.1
S125 .00 S799 .05
Whole Foods groceries
4/29/2010 Check P.2 ____, S1. .05
Pearson production costs e 245.00 ---
5/ 5/2010 1 Depostt #1 S965 .00
books S79.05
Check f:l3 Borders
5/ 6/2010 S990 .
1refund S25.00
Depostt #2 Staples
5/ 10/2010

FIGURE 8.15 Sam ple tran sact ion repo rt.

to be used for
des ign for the che ck and dep os it slip allo ws one set of con tro ls
T he com mo n e, while the tex t of the labe l
llblNa me is set to the use r's nam
bot h items. Th e tex t of the labe
fo rth betw een Pay To and Source.
lblToFrom will cha nge bac k and ause the progra m will
lists the objects and the ir init ial pro perty sett ings. Bec
Tab le 8.3 kCo lor prop-
disp lay ing the nex t che ck, all the tex t for the labe ls and the Bac
always beg in by se ass ign -
ld hav e bee n se t at des ign tim e. We chose inst ead to leave the
erty of the form cou switch from depos it en try to
Set upC hec k met hod, whi ch norma lly is use d to
men ts to the to pre pare the init ial
ry but also can be call ed by the form 's Load eve nt proced ure
che ck ent
fo rm.
mo de (ch eck or deposit) fo r the named lnitiall nfo.tx t and Tra nsa
ctio ns.t xt.
CS V form atte d tex t file
Th e pro gra m uses r co mm a-d elim ited pieces of
e file ln itia llnfo. txt con sist s of a sing le line co nta inin g fou
Th
8.4 A Case Stud y: Reco rdin g C hecks and
Deposit • 391

ltr1:JII:IM Objects and initial prop erty settings for the checkboo
k management program.
Obje ct Prop erty Sett ing
frmA ccou nt
lbl ame
lbl um Tex t
txtN um
lblD ate Text Date:
txt Date
lblTo From
txtToFrom
lblA mou nt Text Am oun t$
txtA mou nt
lblM emo Tex t Mem o
txtM emo
btnR ecor d Text &Re cord This C heck
btnM ode 0 xt &Sw itch to Deposits
btnR eport Text Re& port
btnQ u it Text &Qu it
lblCurBal Text C urre nt Balance
txtB alan ce Read Onl y True
dgv Transacti ons Row Heacle rVisib le False

informa t ion: the name to appe ar on the


chec k and deposit slips, the star ting bala
ber of the first check, and the num ber nce, the num -
of the first depos it slip. The file Tran sact
a line for each tran sact ion -th at is, ions . txt con ta in
writing a chec k or mak ing a deposit.
recorded as a sequ ence of eigh t com ma- Each tran sact ion is
deli mited items: the type of tran saction,
txtToFrom, the curr ent balance, the the con tent s of
num ber of the last chec k, the num ber
sli p, the amo unt of mon ey, the memo, of the la t depo sit
and the date.

Coding the Program


The seco nd row of the hier arch y cha
rt in Fig. 8. 16 identifies the different
program must respond. Tab le 8.4 lists eve nts to whi ch the
the corr e pon ding eve nt proc ed ures and
cedures they call. the ge nera l pro-

Record
Transactions

Set up Record
first text file Togg le Display Quit
check or between check
and form transaction
deposit slip and deposit sl ip report

Create
text file
Read Set up Reset
h
Va lidate Reset Set up
I
Set up Reset
text file check input input input check deposit input
fields fields slip fields
FIGURE 8. 16 Hier arch y char t for ch eckb ook ma
n agem ent prog ram.
392 • Cha pter 8 Tex t Files

lt;1:JII:JI Tasks and their procedures.


Pro ced ure
Tas k
frm Acc o unt_ Loa d
1. Set up first text file and form
lniti a li zeData
1.1 C reat e fir t text file
In itializeData
1.2 Read text files
SetupC hec k
1.3 Set up che ck
Res etln put
1.4 Reset inpu t fields
btnR cco rd_C li ck
2. Rec ord che ck or depo sit slip Dat a Va lid
2. 1 Validate in put
Resetln.put
2.2 Res et inpu t fields
s it slip btnM ode _C li ck
3. Toggle betw een che ck & depo
Setu pCh eck
3. 1 et up che ck
Setup Dep osit
3.2 Set up dep osit slip
Resetln.put
3.3 Res et inpu t fie lds
btn. Rep ort_C lick
4. Display tran sact ion repo rt btnQ uit_ Clic k
5. Qui t

ure :
Let's exa min e eac h eve nt pro ced
ess the tex t file. Thi s
oun t_L oad first call s the lnit ia lizeDat a Sub pro ced ure to proc
1. frm Acc ist, the pro ced ure
lnit iall nfo .txt ex ists. If it does ex
file
pro ced ure first looks to see if the rmi ne all info rma tion
h pos ibl y the la t entr y of Tra nsa ct ions. txt) to dete
uses it (alo ng wit ure pro mpt s the user for
txt does not ex ist, the S ub pro ced
nee ded to proceed. lf In itia llnfo. nce , and the num bers
e to app ear on the che cks and depos it lips, the star ting bala
t he nam file . The eve nt
ch eck and dep osit slip and the n writes thes e item s to the text
of the first saction type to Che ck
Sub pro ced ure nex t to set the tran
pro ced ure call s the Set upC hec k eve nt pro ced ure the n
bac kgr oun d colo r for a check. The
and sets the app ropriate text and a ub pro ced ure
etln put , whi ch init ializ es all the text boxe . The lnit ia lizeDat
call s Res lid user inpu t.
dlin g to pro tect the cod e from inva
emp loys stru ctur ed exc eption han ent ries. Thi s is
_Cl ick fir t con firm s tha t th e required fi elds con tain va lid
2. btn Rec ord retu rned is Tru e, the n
ncti o n Dat aVa lid . If the valu e
acc omp lish ed by call ing th e fu in app end mode, writes
ren t bala nce , ope n the text file
btn Rec ord _Cl ick upd ates the cur Valid retu rns False,
piec es of dat a to the fi le, and the n closes the file . Wh en Data
e ight is nee ded or
n itse lf pop s up a mes sage box to tell the user whe re info rma tion
th e fun ctio Record but ton again.
info rma tion and th n clic k on the
invalid. The use r must type in the ure tha t the user's inpu t
ctu red exc ep tio n h and ling to ens
The Dat a Val id fun ctio n uses stru a lidC astE xce ptio n is
ber field is not a num ber, the Inv
is va lid. If e ithe r the amo unt or num riat e message ask-
The Cat ch bloc k h and les this exc epti on by displaying an app rop
th row n.
t ion.
ing the use r to reen ter the info rma call s Set upC hec k,
Clic k togg les bac k and fort h from a che ck to a dep osit slip . lt
3. btn Mo de_
n calls Rese tlnp ut.
or its ana log Setu pDe pos it, and the
shown in Fig. 8. 15 .
lete hist ory of all tran sact ions , as
4. btn Rep ort_Click disp lays a co mp
5. btn Qui t_Click end s the program.
nts and var iab les
'cla ss lev el nam ed con sta
Con st INI T_ F I LE As Str ing
= "In itia lin fo. txt "
Con st TRANS_ FIL E As Str ing
= "Tr ans act ion s.tx t"
ent ry
'va ria ble s use d for eac h
Dim isC hec k As Boo lean
and dep osi t slip s
'nam e to app ear on che cks
Dim nam eOn Chk As Str ing
8.4 A Case Study: Record ing C hec
ks and Deposits
• 393
Dim las tCk Nu m As Int num ber of las t che ck
eg er wr itte n
Dim last Dp Nu m As Int num ber of las t dep osi
eg er
Dim cur Ba l As Do ubl e t sli p wr itte n
cu rre nt bal anc e in acc
oun t
Pri va te Sub frrn Ac cou
nt_ Loa d( ... ) Ha ndl es
My Bas e .Lo ad
the c ~o ~e el ar
ab
Ini tia liz eD ata ()
e the >am e nd bal anc
e lab els .
lbl Na me .Te xt = nam eOn
Chk
txt Ba lan ce. Te xt = Fo
rm atC urr enc y(c urB al)
S the dat e ~el to the
c rre nt dat e
txt Da te. Te xt = CS tr (To
day )
Set upC hec k ()
Re set inp ut ()
End Sub

Pri va te Sub Ini tia liz


eD ata ()
If IO. Fil e .Ex ist s(I NI
T_ FIL E) The n
Dim dat a() As Str ing
hol ds he dat a ~
Dim ini tFi leC on ten ts( a 1 ne
) As Str ing = IO. Fil
Spl~
e .Re a dA llL ine s(I NI T_
e s1 g e lin e o~ I IT FIL E)
FIL E us ng th QP ~it
da ta= ini tFi leC on ten e
ts. Fir st. Sp l it( "," c )
L> ad lhe e o app ear ch ec' s, c bal anc e, num ber of
las t ch= N • e~ and num ber of las t dep
nam eOn Chk osi t s~ip pro ces sed .
dat a(O )
cur Ba l = CD bl (da ta( l))
las tCk Nu m = Cin t (da ta(
2))
last Dp Nu m = Cin t (da ta(
3))
P ~ 1 up ia e er~c alu es by loo k1n g at
If IO. Fil e .Ex ists (TR AN las t rec ord of TRANS
S_ FIL E) The n FIL E
Dim tra nsF ile Co nte nts
() As Str ing = IO. Fil
dat a = tra nsF ile Co nte e .Re adA llL ine s(T RA NS
nts .La st. Sp lit( "," c ) _ FIL E)
cur Ba l = CD bl (da ta( 2))
las tCk Nu m Cin t (da ta( 3))
las tDp Nu m = Cin t (da ta(
4))
End If
Els e
o s no t ex ist , so ge
t ini tia l dat a fro m
Dim sw As IO. Str eam Wr use r
1te r
nam eOn Chk = Inp utB ox(
"Na me to app ear on che
Try cks and de po sit sli ps
:" )
cur Ba l = CD bl (In put Bo
x( "S tar tin g Ba lan ce:
ge t n unb t-rs of . " l " ))
che ck and dep os lip
las tCk Nu m Cin t (In put Bo x( "Nu mb er
of fir st che ck: " )) -
las tDp Nu m = Cin t (In put 1
Bo x( "Nu mb er of fir st
h s. dep osi t sli p:" ) ) - 1
e rec ord i, h tex t
fil e rec ord s the v~e
app ear >I che c s o
he 1n iti al ta for t "'
Dim out put Lin e As Str
ing = nam eOn Chk & ","
& cur Ba l & "," &
las tCk Nu m & "," & last
sw = IO. Fil e .Cr eat eT Dp Nu m
ext (IN IT_ FIL E)
sw .W rite Lin e(o utp utL
ine )
Ca tch
It a num ber can not
e co n·e rte d hen dis pl" l
Me ssa geB ox .Sh ow ( "In va .. sag e and q
lid num ber . Pro gra m
Me .Cl ose () ter mi nat ing ." , "E rro
r" )
Ch apt er 8 Tex t Files
394 •
Fin all y abo ve.
ma tte r wh at hap pen s
'Cl ose the wr ite r no
sw .Cl ose ()
End Try
End If
End Sub

btn Re cor d.C lic k


d_ Cl ick ( ... ) Ha ndl es
Pr iva te Sub btn Re cor fil e.
o the tra ns ac tio ns
'St ore the inp ut int
Dim am t As Do ubl e
ing
Dim tra nsT yp e As Str led and va lid
on ly if all req uir ed fie lds are fil
'st or e
If Da taV ali d() Th en
t.T ext )
am t = CD bl (tx tAm oun che ck or de po sit sli
p mo de
jus t bal anc e by am oun t dep end ing on
'ad
If isC hec k Th en
t
cur Ba l = cur Ba l - am
las tCk Nu m Ci nt (tx tNu m.T ext )
tra ns Typ e "Ch eck "
Els e
cur Ba l += am t
las tDp Nu m Ci nt (tx tNu m.T ext )
tra ns Typ e "D epo sit "
End If
rm atC urr enc y(c urB al)
txt Ba lan ce. Te xt = Fo be sto red
ins inf orm ati on to
'st rin g arr ay co nta txt To Fro m. Te xt,
Str ing = {tr ans Ty pe,
Dim tra nsO utp ut( ) As stD pN um ), CS tr (am t),
tr (cu rB al) , CS tr (la stC kN um ), CS tr (la
CS
te. Te xt}
txt Me mo .Te xt, txt Da pen dTe xt( TR AN S_ FIL E)
Wr ite r = IO. Fil e .Ap
Dim sw As IO. Str eam by the de lim ite r
d the inf o to the tex t fil e, sep ara ted
'ap pen
nsO utp ut, "," c ))
sw .W rit eL ine (Jo in( tra
sw. Clo se () en try
es to bla nk for ne xt
're se t inp ut tex t box
Re set inp ut ()
End If
End Sub

As Bo ole an
Fu nct ion Da taV ali d() dis pla y a me ssa ge if
no t
all da ta are va lid , or
're tur n Tru e if
Str ing =
Dim err orM ess age As orm ati on
two ess en tia l pie ces of inf
'If one of the orM ess age .
its nam e to err
'is mi ssi ng , ass ign
m = "" Th en
If txt To Fro m. Te xt. Tri
If isC hec k Th en
err orM es sag e "Pa y To"
Els e
e"
err orM ess age = "So urc
End If
txt To Fro m. Fo cus ()
xt. Tri m "" The n
El sei f txt Am ou nt. Te
err orM ess age = "Am oun
t"
txt Am oun t.F ocu s()
lds
End If the two nu me ric al fie
the n che ck syn tax of
'if no err ors ye t,
8.4 A Case Stud y: Recordin g C hecks and
Deposits • 395

If erro rMe ssag e = "" The n


'che ck syn tax of the amo unt
fiel d (Do uble )
Try
If CDb l (txt Arn oun t.Te xt) <=
0 The n
erro rMe ssag e = "Th e amo unt
mus t be gre ater than zero ."
txtA rnou nt.F ocu s()
End If
Cat ch exc As Inv alid Cas tEx
cep tion
erro rMe ssag e = "The amo unt
" & txtA rnou nt.T ext & " is
txtA rnou nt.F ocu s() inv alid ."
End Try
Els e
erro rMe ssag e "The '" & erro rMe ssag e & "'
fiel d mus t be fill ed. "
End If
'dis pla y erro r mes sage if
ava ilab le
If erro rMe ssag e = "" The n
'all req uire d data fiel ds
hav e bee n fill ed; reco rdin
Ret urn Tru e g can pro cee d
Els e
'adv ise use r of inv alid data
Mes sage Box .Sho w(e rror Mes sage
& " Ple ase try aga in." )
Ret urn Fal se
End If
End Fun ctio n

Priv ate Sub btnM ode Clic k(


... ) Han dles btnM ode .Cli ck
'tog gle mod e betw een Che ck
and Dep osit Slip
If isCh eck The n
Setu pDe pos i t ( )
Els e
Setu pCh eck ()
End If
'set fiel ds for nex t ent ry
Res etin put ()
End Sub

Sub Setu pCh eck ()


'pre par e form for the ent ry
of a che ck
isCh eck = Tru e
Me .Te xt = "Ch eck" 'set the titl e bar of the
lblT oFr om. Tex t = "Pay To" form
btnR eco rd.T ext = "&R ecor d
Thi s Che ck"
btnM ode .Tex t "&S witc h to Dep osit s"
Me .Bac kCo lor Col or .Lig htB lue
End Sub

Sub Setu pDe pos it()


'pre par e form for the ent ry
of a dep osit
isCh eck = Fal se
Me .Te xt = "De pos it Slip "
'set s the titl e bar of the
lblT oFr om. Tex t = "So urce " form
btnR eco rd.T ext = "&R ecor d
Thi s Dep osit "
btnM ode .Tex t "&S witc h to Che cks"
Me .Bac kCo lor Col or .Lig htY ello w
End Sub
396 • Cha pter 8 Text Files

Sub Re set inp ut ()


fie lds exc ept dat e
're set all tex t ent ry
txtT oFr om .Cl ear ()
txtA mo unt . Cle ar( )
txtM emo . Cle ar( )
If isC hec k The n
lec t nex t che ck num ber
mak e txtN um tex t box ref
Num + 1)
txtN um .Te xt = CS tr (las tCk
Els e p num ber
ref lec t nex t dep osi t sli
'ma ke txtN um tex t box
Num + 1)
txtN um .Te xt = CS tr (las tDp
End If ent ry
tex t box for the nex t
'se t foc us on To/ Fro m
txtT oFr om .Fo cus ()
End Sub
Re por t.C lick
Cli ck( ... ) Han dle s btn
Pri vat e Sub btn Rep ort _
S_ FIL E) The n
If IO. Fil e .Ex ists (TR AN e .Re adA llLi nes (TR AN S_ FIL
E)
Dim tra nsF ileC ont ent s() As Str ing = IO. Fil
In tra nsF ileC ont ent s
Dim que ry = Fro m tra ns
"," c )
Let dat a= tra ns. Sp lit(
(da ta( 7))
Let tran sD ate = CD ate
ber (da ta(O ), dat a(3 ), dat a(4 ))
Let num ber = For mN um
Let toF rom = dat a(l )
Let Memo = dat a(6 )
rre ncy (da ta(S ))
Let Am oun t= For ma tCu
tCu rre ncy (da ta(2 ))
Let Ba lan ce= For ma Bal anc e
ber , toF rom , Memo, Am oun t,
Sel ect tra nsD ate , num
ce = que ry. To Lis t
dgv Tra nsa ctio ns. Da taS our
ell = No thin g
dgv Tra nsa ctio ns . Cu rre ntC = "Tr ans act ion Dat e"
"tra nsD ate " ) .He ade rTe xt
dgv Tra nsa ctio ns. Co lum ns( "D esc rip tio n"
"nu mbe r" ) .He ade rTe xt
dgv Tra nsa ctio ns. Co lum ns( "Re cip ien t or Sou rce "
" t oFr om" ) .He ade rTe xt =
dgv Tra nsa ctio ns. Co lum ns(
Els e rep ort ." )
are no tra nsa cti ons to
Me ssag eBo x .Sh ow( "Th ere
End If
End Sub
che ckN umb er As Str ing ,
n For mN umb er( ByV al typ e As Str ing , ByV al
Fun ctio Str ing ) As Str ing
ByV al dep osit Nu mb er As
If typ e = "Ch eck " The n
ckN umb er
Ret urn "Ch eck #" & che
Els e
osit Nu mb er
Ret urn "De pos it #" & dep
End If
End Fun ctio n
it.C lick
ck( ... ) Han dle s btn Qu
Pri vat e Sub btn Qu it_ Cli
'ex it the pro gra m
Me . Clo se ()
End Sub

CHAPTER 8 SUMMARY
tho d c pie an array to a tex t file.
1. The IO.File .WriteA llLines me
ted by com mas , LIN Q
a are stor ed in tex t files wit h the field s of eac h reco rd separa
2. W hen dat the Split me tho d.
to sort , sea rch , and reo rgan ize the dat a wit h a littl e help from
can be used
Prog ram ming Projects
• 397
3. Arr ays and que ries can be com
bined with the set met hod s Con cat,
Exce pt. Union, Inte rsect, and

4. Wh en tex t fi les are ope ned , the


prog ram must spec ify whe ther they
StreamReade r or wr itten usin g a Stre wi ll be read using a
amWriter. Files used fo r inpu t are spec
IO.File. ReadTe xt met hod . O utpu t fi ified with the
les can be crea ted (IO.Fil e.C reat eTe
(IO .File .Appen dTe xt). A line of data x t) or just add ed to
is writ ten to a file with the Wri teLi
read from a fi le with the Rea dLi ne ne met hod and
met hod.
5. Structur ed exce ption handling can
redu ce the likel ihoo d that a prog
exc epti on occ urs whi le the cod e in ram will cras h. If an
the Try bloc k is exe cuti ng, execut ion
cod e in a Cat ch bloc k that aler ts bran ches to the
the user of an erro r and prov ides
Fina lly bloc k con tains cod e that exe a wor karo und. The
cutes rega rd less of whe ther an excepti
on occ urs.
6. 'XM L files are text files of a spec
ial form at that is popular for data tran
smi tted ove r the lnte m et.

CHAPTER 8 PROGRAMMING PROJECTS


1. The file A LE.txt con tains the info
rma tion sho wn in Tab le 8.5. Wri te
fil e to produce a text fil e con tain ing a prog ram to use the
the info rma tion in Tab le 8.6 in whi
teams are in descend ing orde r by the ch the base ball
percentage of games won .

I@:J!f:JW American League East games won and lost


in 2009 .
Tea m Won Los t
Ba ltimo re
64 98
Boston 95
New York 67
103 59
Tam pa Bay
84 78
Toro nto 75 87

lf!1:1!f:IM Final 2009 American League East standing


s.
Tea m W L Pet
New York 103 59 0.636
Boston 95 67 0.586
Tam pa Bay 84 78 0.5 19
Toro n to 75 87 0.463
Balt imo re 64 98 0.385

2. The file Sen ate l lO. txt con tain


s the members of the ll Oth U.S. Sen
ate prio r to th e 2008 elec tion . ate -th at is, the Sen -
Eac h reco rd of the file con sists of thre
and part y affili atio n. 2 Some reco rds e fields- name, state,
in the fi le are as follo ws:
Ric har d Selb y,A laba ma, R
Jos eph Lie ber man ,Co nne ctic
ut , I
Bar ack Oba ma, Ill ino is,D

2
We refer to anyo ne who is neit her
a Rep ublican nor a De moc rat as Inde
pend en t.
39 • Cha pte r 8 Text Files

.txt fo r sen ato rs


ired Sen .txt con ta ins the record s from the fil e Sen ate 110
Th e fi le Ret th, or res ign at ion.
ate afte r the 200 8 ele ctio n due to reti rement, def eat, dea
wh o left the Sen
follows:
Som e records in the file are as
,D
Bar ack Ob arn a,I llin ois
k, D
Hi lla ry Cli nto n,N ew Yor
Ca rol ina ,R
Eli zab eth Do le,N ort h
e newly ele cte d in 2008
rec ord s fo r the se nat ors wh o wer
Th e fi le Ne wS en. txt co nta ins 2008 e lectio n. Som e
e app oin ted to fill the sea ts of sen ato rs wh o left afte r the
or wh o wer
s:
records in the fi le are as fo llow
Mik e Joh ann s,N ebr ask a,R
Yo rk, D
Kir ste n Gil lib ran d,N ew
Ma rk Wa rne r,V irg ini a,D
the file Sen ate 111. txt tha t
gra m tha t uses the thr ee files abo ve to cre ate
(a) Wr ite a pro of the 111 th Sen ate .
s rec ord (ea ch con si ting of thr ee fie lds) for the me mb ers
con tain
and (d).
U e this fi le in pa rts (b), (c), ty affiliation .
gra m tha t det erm ine the num ber of sen ato rs of eac h par
(b) Wr ite a pro
whose two sen ato rs h ave the
gra m tha t det erm ine s the num ber of stat es
(c) Wr ite a pro
t: U e a pro ced ure wit
h the head ing Fun ctio n
same party affiliat ion . Hin
As Str ing ) As Bo ole an.
Sar neP arty (By Val sta te n disp lays the
m tha t asks the use r to se lect a stat e from a list box, and the
(d) Wr ite a progra
Fig. 8.1 7.
two sen ato rs from tha t stat e. See

State: Senators :

Lou isan na Benjamin Card in


Maine Barbara Mikulski
Ma and
Massachusetts
Michigan
Minnesot a
Miss issippi
Missouri

Project 2.
FIGURE 8.17 Possible outcome of Programming
t
rde r. Wr ite two programs tha
e file Nam es. txt con tain s a list of names in alp hab etic al o atio n . If it is
3. Th list in its pro pe r loc
and inse rt the nam e into the
request a nam e from the user
hould not be inserted.
a lready in t he list , the nam e t is, use only a Stream -
the firs t pro gra m wit hou t using any arrays or LIN Q; tha
(a) Wr ite
Rea der and a StreamWriter.
usin g arrays and LIN Q.
(b) Wr ite the second program
cre ate and ma inta in te le-
Ma inta in Tele pho ne Directories. W rite a program to
4. Cre ate and in a separa te tex t file. In
ries . Eac h tele pho ne dire cto ry sho uld be con ta ined
pho ne dire cto lep hon e dire cto r ies.
nam ed Dir ecto ries . txt sho u ld hold the nam es of t he te
add itio n, a file a li t box. Aft er
es of all the tele pho ne dire cto ries sho uld be disp layed in
At any t ime, nam directory. Th e fo llow ing but -
tele pho ne dire cto ry is sele cte d, it becomes the current phone
a
ton s sh ould be ava ilab le. ided by an inp ut d ia-
a new tele p hon e di rec to ry. (Th e file nam e sho uld be pro v
(a) Cre ate
log box.)
Prog rammin g Projects
• 399
(b) Add a listi ng (a give n in text
boxes) to the end of the curr ent pho
ne dire ctory.
(c) Delete a name (as give n in a text
box ) from the curr ent pho ne dire ctor
(d) Dis play the nam es and pho n e num y.
bers in the curr ent pho ne dire c to ry.
See Fig. 8.1 8

ainta in Tele pho ne Directories

Oick on one of the existing phon e direc


tories
below to mak e it the current phon e direc Create a New Phone Directory
tory.
Phone Directories
Friends .txt Current phon e directory:
Merc hants .txt Rest aura nts .txt
Restaurants txt
Theaters .txt Name:

Phone number:

Add a Usting to the Remove a Ustin g from the


Current Phone Directory Displ ay the Ustings in the
Current Phone Directory Curre nt Phone Directory

Name Phon e
Number
Addis ,Ababa 345- 1212
Great Sage 123.-4557
Mand alay 555-57&9
Woodlands 989-·5555

FIGURE 8.18 Sam ple outp ut of Prog ram min g Proj


ect 4.
5. Eac h item in a sup e rma rket is iden
tifie d by its Uni versa l Pro du ct Cod
co nsis ts of a seq uen ce of 12 digi ts e (UP C ), wh ich
app ea ring belo w a rec tang le of bars
bars h ave thes e digi ts enc ode d in . See Fig. 8. 19. The
the m o tha t the UP C ca n be read
ne r. Let 's refe r to the UPC as d -dz by an opti ca l scan - Video Note
1 d3 d4 ds d6-d7 ds d9 d 10 dw d z. The ingl
left, d 1, iden tifies the type of prod 1 e digi t o n the DNA
u ct (fo r inst anc e, 0 fo r ge nera l groc
a nd prod uce , 3 fo r dru g and hea e ries , 2 fo r mea t seq uence
lth produ cts, and 5 fo r co upo ns).
digi ts, d 2 d3 d4 d d6, id enti fies th The first se t of fiv e (dam
Homework)
5 e man ufac ture r, and the seco nd
d7 d8 d9 d 10 d 11 , iden t ifies the prod u ct. se t of fi ve digi ts,
The twe lfth d igit o n th e righ t, d
It is ch ose n so t h at 12 , is a ch ec k digi t.

3 · d 1 + d 2 + 3 · d3 + d4 + 3 · d + d
5 6 + 3 · d7 + d8
+ 3 · d9 + diO + 3 · dll + dl 2·
(*)
is a mul tipl e of 10. For inst anc e, for
the UPC in Figure 8. 19,
3 .0 + 7 + 3 .0 + 7 + 3 .3 + 4 +
3 . 0 + 0 + 3 . 9 + 0. 0 + 3 . 3 + 4
= 40.

FIGURE 8.19 A U niversa l Prod uct Cod e.


400 • Cha pter 8 Tex t Files

r has to ent e r the UP C


= 4 · 10, 40 is a mu ltip le of 10. In the eve nt tha t the cas hie
S inc e 40 to a mu ltip le of 10.
th e a bov e sum will no t add up
man ua lly and mis type s a dig it, e rma rke t. A mas te r file,
n aut om ated che ck- out a t a sup
W rite a pro gra m to sim ulat e a e rma rke t con sist ing of fields
C.t xt, sh o uld h ave a reco rd for eac h item in the sup
call ed UP inst anc e , the file mig ht
C, the n ame of the item , a nd the pric e of the ite m. Fo r
for the UP
con ta in the fo llow in g reco rds:
Bu tte r- 22 oz , 2 .2 9
037 0 0 00 043 0l, Jif Pea nut Tea , 2. 59
Se aso nin gs Sle epy tim e
070 734 0 000 34, Ce les tial
Roo t Bee r , . 55
099 482 403 64 5 , 365 Sod a
tim e and sh o uld plac e the
sh o uld a llow the cas h ier to ent er UP Cs o n e a t a
Th e pro gra m ( *) as soo n as it is
ara te tex t file. Eac h UP C sho uld be va lid ated wit h the sum
UP Cs in a sep 10. Aft er all ite ms h ave bee n
d if the sum is no t a mu lt iple of
ent ere d and sh o uld be reen tere (in a li t box ) a rece ipt sim i-
use the two tex t files to disp lay
pro ces ed, the pro gra m h o uld
lar to the one in Fig. 8.20 .
: $2. 29
22- o z Jif Pe a nut Bu tter
epy tim e Tea : $2. 5 9
Ce les t i al Se as oni ngs Sle
5
3 65 Sod a Roo t Bee r : $.5
Tot a l: $5. 4 3
Pro ject 5.
FIGURE 8.20 Sam ple out put of Pro gra mm ing
or leag ue play ers in the
eba ll .xm l con ta ins dat a a bo ut the pe rfo rma n ce of maj
6. The file Bas lud ed in the file .)
seas on . (On ly p laye rs wit h at leas t 350 at bat s a re inc
200 9 regular eba ll.x ml tha t
the beg inn ing of the fi le. Wr ite a pro gra m usin g the file Bas
Fig ure 8.21 sh ows from tha t tea m who se bat ting
a list a nd d isp lays the play ers
req ues ts a team as inp ut from es tha t a re liste d in the file.
abo ve the ave rage of his team mat es' bat ting ave rag
ave rage wa rages . Th e o utp ut
sho uld be sort ed in dec reas ing o rd er by the ir bat t ing ave
The p layers Fig. 8.2 2.
nam e and bat ting ave rage. See
sho uld disp lay eac h player's full

<? xml ver sio n= ' l.O ' ?> eba lL pla yer s. -->
<!- - ~
lata on ma jor lea gue bas
>
<ma jor_ lea gue _ bas eba ll
<pl aye r >
>
<na me >Aa ron Hil l </n ame
<te am >Bl ue Jay s </ team >
<at Ba ts >68 2 </ atB ats >
<hi ts >l 9 5 </h its >
</p lay er >
ject 6.
FIGURE 8.21 XM L file for Program min g Pro

ll Baseb3 ll
;.
Oick em a tearn . Batting
;.
Pla'J'er Average

V..e·.-in Youkilis .3 5

Vido r Martinez .3 J.
Reds .3 1
Rockies 1:: Jacob>/ BlsbUJy
I
RO'lals
Tigers
Dustin Pedroia .2%

g Pro ject 6.
FIGURE 8.22 Pos s ible out com e of Program min
Additional Controls
and Objects

9.1 List Boxes and Combo Boxes 402


• A Rev iew of List Box Fea tures • Som
e Add itio nal Fea tures of List Boxes
• The Com bo Box Con trol • A Hel
pfu l Fea ture of Combo Boxes
9.2 Eight Additional Controls and Objects
410
• The Tim er Con trol • The Random
C lass • T he Too lTip Con tro l
• The C lipboard • The Pict ure Box
Con tro l • T he Me nuS trip Con tro l
• The H orizont al and Vertica l Scro ll
Bar Con trols
9.3 Multiple-Form Programs 425
• Sta rtu p Form • Sco pe of Var iables,
Con stan ts, and Procedures • Mo dali
• C lose and ShowD ialog Me tho ds • ty
The Form C los ing Eve nt Procedure
• Imp orti ng an Ex ist ing For m • Del
etin g a Form fro m a Prog ram
9.4 Graphics 437
• G raph ics Objects • Lin es, Rec tang
les, C ircles, and Sec tors • Pie C harts
• Bar C h arts • A nim atio n • Prin ting
G raph ics
Summary 450

Programming Projects 451

401
Objects
402 • Cha pter 9 Additiona l Con trols and

9.1 list Boxes and Combo Boxes


king on a n item .
box a nd com bo box con trol s allo w the use r to make sele ctio ns by clic
The list
allo w for inpu t by ass isted typ ing.
Cer tain styl e of com bo box es also

A Review of list Box Features


l ecti on Edi tor. Ite ms are
d es ign t ime w ith the Stri ng Col
A list box can be pop ulat ed a t th er app li cati o n like
dire ctly into th e edit o r o r co pied (wi th Ctrl + C) from ano
type d or. A list box can be
ed (wi th Ctrl + V) in to the edit
Exc e l, Wo rd, o r N o tepa d a nd past D a taSo urce pro pert y to
ms. Add me thod o r by se ttin g its
pop ul ated at run tim e with the lte
o a list ).
a n a rray o r a que ry (co nve rted t is, the ite ms in a list
item s in a list box are inde xed with zero-based num be ring . Tha t
The . Tab le 9. 1 sum marizes the
s(O), lstB ox.l te ms( l ), a nd so on
box a re iden tifie d as lstB ox .ltem ie r cha pters.
list box es that were prese nted in earl
prop ertie s, met hod s, and eve nts for

and events.
ltr1:J!QM Previously discussed properties, methods,
box.
Method: Inse rt the va lue into th e list
lstBox. Ltems.Add(value) the list box.
Met hod: Remove all items from
lstB ox. Items. Clea r() g.
Property : The se lected item as a strin
lstBox.Text list box.
Property: The number of items in the
lstBox. ltems.Co unt disp laye d in asce nd ing
Property: If set to True, items will be
lstB ox.Sorted
ANS I orde r.
. If no item is selected,
Property: The index of the se lected item
lstBox.Selectecllndex
the va lu e is - 1.
. It must be conv erted to a
Prope rty: The curr entl y se lecte d item
lstBox.Se lectecl i tem or message box.
string before being disp layed in a text
must be conv erted to a
lstBox. ltems(n) Property: The item hav ing index n. lt
or mes age box.
stri ng before being disp layed in a text
ate the list box.
Property: Th e sour ce of data to pop ul
lstBox.Da taSo urce elec ted Index property
Eve nt: Occ urs when the valu e of the
lstBox.Se lected lndexChanged e.
changes. It is the defau lt even t procedur
the li st box.
Eve nt: Occ urs when the user clicks on
lstBox.C ii ck l icks on the list box .
Event: Occ ur whe n the user double-c
lstBox. Dou bleClick

ghte d) item by ch a ngin g the


Not e: You can prog ram mat ically
cha nge th e elec ted (tha t is hi ghli
espo nding item in the list box wi ll app ear high ligh ted.
Sele cted lnd ex va lue in cod e: the corr

st box
way to cop y the con te nts o f a li
Example 1 The fo llow ing prog ram sh ows two box pop ulat e a n a rray
a text file. Wh en the top but ton is clic ked , th e item s in the list
into clic ked , a St rea m Wri ter
fi le. Wh en the bot tom but ton is
tha t is the n used to c rea te a text file. Not ice tha t the
the list box dire ctly into a text
is used to cop y th e con te nts of to str in gs befo re cop ying
co nve rt the item s in th e list box
Stre am Wri ter doe s not hav e to
them into the fil e.
9.1 List Boxes and ombo Boxes • 403

OBJECT PROPERTY SETTING


g'i Greeting5
frmG reetin gs Text Greet ings
hello
lstBox Items (show n in screen capture)
Save Contents of btnA rray Text Save Cont ents of
hi
g'day Ust Box Using an
Array List Box Using an Array
hey btn W Text Save Conte nts of List Box
howdy
hi y'all Us ing a Strea mWriter
Save Contents of
howya doin
how-{jo~ou-{jo
Ust Box Using a
Stream Writer
good moming

Priv ate Sub btnA rray_ Click ( ... ) Hand


les btnA rray. Click
Dim ub As Integ er = lstBo x.Ite ms.C ount
- 1 'uppe r boun d of array
Dim a(ub) As Strin g
For i As Integ er = 0 To ub
a(i) = CStr (lstB ox.It ems( i))
Next
IO. File .Wri teAl lLine s( "Gre eting sl.tx
t" , a)
End Sub

Priv ate Sub btnSW_ Click ( . . . ) Hand les


btnSW .Clic k
Dim sw As IO. Strea mWr iter = IO . File
. Crea teTe xt( "Gre eting s2.tx t" )
For i As Integ er = 0 To lstBo x.Ite ms.C
ount - 1
sw.W riteL ine(l stBo x . Item s(i))
Next
sw. Clos e ()
End Sub

[Ru n, and click on each of the two butto ns. Then


end th e progr am, click o n the Refres h butto n
in the Solut i on Exp lorer windo w, click on th e
View A ll Files butto n, a nd look at the n ew text
files in the bin \Deb ug subfo lder. Each text file
will conta in the conte nts of the list box.]

Some Additional Features of List Boxes


Table 9.2 show s some add it iona l useful meth ods
fo r list boxes.

14':JIQW Some additional list box methods.


lstBox.Items.IndexOf( value ) Meth od: Index of the first item to have the va lue.
lstBox .ltem .RemoveAt( n)
Meth od: De lete item having index n.
lstBox.ltems.Remo ve(strValue) Meth od: Delete first occurre nce of the string va lue.
lstBox .ltems.lnser t(n, value ) Meth od: Insert th e va lue as the item of index n.

Example 2 The fo llow ing progr am re move s a ll dupli cates


fro m a list box. The progra m
looks at th e first item in th e list box and remo ves
eve ry ma tchin g ite m th a t fo llows it. The pro-
gram then repea ts th e proce ss with the next item
rema in ing in the list box, a nd so o n .
404 • Chap ter 9 Addi tiona l Cont rols and Obje cts

OBJECT PROPERTY SETTING

frmD OW Tex t DOW


btnR emove Text Remove Duplica tes
[ Remove Duplicates ] lstDOW Items (shown in scree n captu re)

MSFT~
IBM
MSFT
csco
INTC
I IN TC
J
l MSFT

. ) Han dles btnR emov e . Clic k


Priv ate Sub btnR emov e Clic k ( . .
ger = 0
Dim i As Inte ger = 0, j As Inte
.Ite ms . Coun t - 1)
Do Whi le i < ( l stDOW
j = i + 1
t
Do Whi le j < lstDO W . Item s . Coun
Item s(j ) ) = CStr (lstD OW . Item s(i)) Then
If CStr ( lstDO W .
lstD OW. Item s.Re mov eAt( j)
Else
j += 1
End If
Loop
i += 1
Loop
End Sub

[Run, and then click on the button.]

D DO IV l = I @) 1-·t-3 J

( Remove Duplicates )

MSFT
IBM
csco
INTC

'- - --- ~

The Combo Box Control


Co mbo
a text box with a list box attac hed to it.
A com bo box cont rol can be thought of as . T he
even ts that list boxes have , plus a few more
Video Note
List boxes and boxes have all the properties, meth ods, and ectio n
n in Fig. 9. 1. (Eac h combo box's String Coll
combo boxes th ree diffe rent styles of combo box are show inen ts. ) The style
with the names of the seve n cont
Ed itor wa used to populate the combo box impl e, Drop -
ng its OropOow nStyle prop erty to S
of a com bo box cont ro l is spec ified by setti the
combo box the list box is always visible. With
Down, or DropDow nList. In a Simp le style row
run time whe n the use r clicks on the down-ar
other two styles, the list box appears only at
the name of a combo box is cbo.
butto n. See Fig. 9.2. The sta ndard prefi x for
9.1 List Boxes and Combo Boxes
• 405

D_. The Thre e Style s of Combo Boxe s l = I @] lr"'·tJ J


Simp le Drop Down OropOownUst
.... [ .... ]
Nrica
Antarctica
Asia
Australia/Oceania
Europe
North America
South America

FIGURE 9.1 The th ree setti ngs for the D ropD own Style
prop erty.

Drop Down OropOownUst

Nrica
l::J Nrica
....
Antarctica Antarctica
Asia Asia
Australia/ Ocea nia Australia/Ocean ia
Europe Europe
North America North America
South America South America
(a) (b)
FIGURE 9.2 Com bo boxes at run time after their dow
n-arr ows are click ed.
Wit h a S imp le or Dro pDo wn combo box,
the use r ca n fi ll the tex t box eith er by
di rectl y into it or by selec ting an ite m from typi ng
the list. Wit h a Drop DownList style com
user can fill the tex t box only by selec ting bo box, the
an item from the list. (Oro pOo wn is the
ting of a combo box's Dro pOo wnS tyle prop defa ult se t-
erty. ) A list that has drop ped down disa ppea
the user clicks on an item or presses the rs whe n
Ente r key. Wit h any of the three styles,
the va lue of
c b o Box .Tex t
is the cont ent of the text box at the top of
the combo box. Just like list boxes, com bo
popu lated with their String Collectio n Edit boxes can be
or, the ltems.Add meth od, and the DataSour
ce property.

Example 3 The follo wing program uses a Simple com


bo box to obta in a perso n's title for the
first line of the address of a lette r.

OBJECT PROPERTY
D
~ Lette r Add ress GJ I @) I[][ ] frmA ddress Tex t
SETIING
Lette r Add ress
Trtle Name : lblTitle Tex t Title
cboTitle Item s (sho wn in
Mr. scree n capture)
Display Full Name DropDownStyle Simple
Ms.
Dr. lblN ame Tex t N ame :
The Honorable txtN ame
Her Exce llency btnD isplay Text Display
Fu ll Nam e
txt Display Read O nly True
cts
406 • C hapt er 9 Add ition a l Con tro ls and Obje

.. . ) Han dles btnD ispl ay.C lick


Priv ate Sub btnD ispl ay_ Clic k(
t & 11 11 & txtN ame .Tex t
txtD ispl ay .Tex t = cbo Titl e . Tex
End Sub

click on the
type a name into the Name text box, and
[Ru n , elec t an item fro m the com bo box,
butt on.]

a~ l e tte r Addr ess

Trtle Name : Quee n Elizabeth

Her Excellency
Mr. Display Full Name
Ms .
Dr.
The Hono rable Her Exce llency Queen Elizabeth
Her Excellen

in Fig. 9.3.
le com bo box prod uces the fo rm show n
T he sa me prog ram with a DropDow n sty .
a DropDow nList style com bo box is used
T he form wi ll look abou t the same whe n

a;} l e te r Address l = I @] ~~ •J

Title Name : Queen Elizabeth

Her Exce llency ....


Display Full Name

Her Excellency Queen Elizabeth

bo box.
FIGURE 9.3 Exam ple 3 with a Drop Dow n style com

the same fo rm des ign and settings


Example 4 T he fo llow ing varia t ion of Exa mple 3 uses
is not filled at des ign time.
as Example 3 exce pt that the co mbo box

. .. ) Han dles MyB ase .Loa d


Priv ate Sub frmA ddre ss _ Load (
." , "Ms ." , "Dr ." ,
Dim titl es( ) As Stri ng = { "Mr ncy " }
"The Hon orab le" , "Her Exc elle
from arra y
'Fil l comb o box with elem ents
cbo Titl e.D ataS ourc e = titl e s
End Sub
. .. ) Han dles btnD ispl ay.C lick
Priv ate Sub btnD ispl ay_ Clic k(
t & " " & txtN ame .Tex t
txtD ispl ay.T ext = cbo Titl e . Tex
End Sub
9.1 List Boxes and Combo Boxes
• 407

A Helpful Feature of Combo Boxes


The file Nat ions. txt con ta ins the nam es of
the 192 mem bers of the Un ited Nations. Supp
S impl e ty le com bo box has been filled with ose a
the natio ns in alph abet ical order. Figure 9.4(
shows the co mbo box whe n the prog ram a)
start s. Each t ime a lette r is type d into the
at the top of the com bo box the list scro ll tex t box
in a helpfu l way. For insta nce, after the lette
typed, the com bo box appea rs as show n in Fig. r N is
9.4(b ). The combo box has scro lled down so
the first natio n begi nning with the lette r N that
is at the top of the list. Sim ilarly, typ ing addi
lette rs causes the list to scro ll dow n so that tion al
the first nat ion begi nnin g with the typed lette
at the top of the list. See Figs. 9.4( c) and 9.4(d rs is
) . (Not es: Whe n the scro ll box reac hes the
tom of the scro ll bar, no furth er scro lli ng wi bot-
ll take place. A lso, if the typed lette rs do not
respo nd to any nat ion , the list wi ll retur n to cor-
the state in Fig. 9.4(a ). A nalogo us results appl
Orop Oow n sty le com bo boxes. ) y to

N Ne New
Afghanistan ;.. Namibia ... Nepa l ,;. Ne•N Zealand
AJban ia
Algeri a u Nauru
Nepal
Netherlands
Ne•N Zealand
Nicaragua
Niger
kidorra Netherlands Nicaragua Nigeria
Allgol a New Zealand Niger NorNa;'
Alltigua and Barbudc
Argentina
Nicaragua 0 Nigeria 0 Oman 0
Niger Norv.•a>J'
Armenia Pakistan
Nigeri a Oman
AJ..Jstra lia Palau
Norv.•ay Pakistan Panama
(a) (b) (c) (d)
FIGURE 9.4 Success ive comb o box displays .

Practice Problems 9.1

1. Will the fo llow ing two state men ts alwa


ys have the ame effect?
lstO xys. Item s.Re mov eAt( lstO xys.
Sele cted inde x)
lstO xys. Item s . Rem ove( lstO xys.
Text )

EXERCISES 9.1

In Exer cises 1 thro ugh 8, dete rmin e the


effec t of the code on the list box lstBo
below. (Ass ume that the Sort ed prop erty x show n
is set to True .)

Bach
Beethoven
Cho_Q in
1~1.¥1.
Tc haiko vsky

1. lstB ox.I tems .Rem ove( "Ch opin ")


2. lstB ox. Item s. Remo v eAt (0)
3. lstB ox.I tems .Rem oveA t(lst Box .Sel ecte
dind ex)
4. lstB ox.I tems .Rem oveA t(lst Box .Item
s.Co unt - 1)
5. lstB ox. Item s .Add ("Ha yden ")
cts
408 • Cha pter 9 Add iti onal Con trols and Obje

6. Dim tota l As Inte ger = 0


ox . Item s . Cou nt - 1
For i As Inte ger = 0 To lstB
ngt h= 6 The n
If CSt r(ls tBo x.It ems (i)) .Le
tota l += 1
End If
Nex t
txtO utp ut.T ext CSt r(to tal)

= lstB ox.I tem s . Cou nt - 1


7. Dim hig hes tind ex As Inte ger
As Stri ng
Dim com pos ers( hig hes tind ex)
hig hes tind ex
For i As Inte ger = 0 To
x.It ems (i))
com pos ers( i) = CSt r(ls tBo
Nex t
lstB ox. Item s.C lear ()
lstB ox. Sor ted = Fal se
ex To 0 Step -1
For i As Inte ger = hig hes tind
i))
lstB ox.I tem s.A dd(c omp oser s(
Nex t
lstB ox.I tem s.C oun t - 1
8. Dim hig hes tind ex As Inte ger =
As Stri ng
Dim com po sers (hig hes tind ex)
To hig hes tind ex
For i As Inte ger = 0
x . Item s(h igh esti nde x- i))
com pos ers( i) = CSt r(ls tBo
Nex t
lstB ox. Sor ted = Fal se
rs
lstB ox.D ataS our ce = com pose
to Sim ple, app ears
that cbo Box has Dro pDo wnS tyle set
In Exe rcis es 9 thro ugh 16, assu me stat eme nts that
erty set to Tru e. Giv e a stat eme or
nt
as show n below, and has its Sor ted prop if add ition al item s
e stat eme nts shou ld do th e job even
will carr y out the stat ed task . (Th
hav e been adde d to the list. )

mm l ]
Dan; ;--- ---1
Goethe
Moli ere
I
Shak espea re

9. Highligh t the name Dan te.


t.
10. H ighlight the third item of the li
11. De lete the name Sha kespea re.
12. De lete the name G oe the.
13. De lete the las t name in the list.
14. Display eve ry othe r item of the
list in ano ther list box .
the lette r M.
15. Dele te eve ry item begi nnin g with
16. Det erm ine if Cerva ntes is in the
list.
to newborn s in a
s the 20 mos t pop ular names give n
17. The file PopularN ames. txt con tain abetical orde r
a list box to so rt the names into alph
rece nt yea r. Wri te a prog ram that uses
into a new ord ered tex t file.
and then places the alph abe tized list
18. Rework the prog ram in Exa mple
2 using LIN Q.
9.1 List Boxes and Combo Boxes
• 409

19. Supp ose all the items in lstBo x are


num bers. Writ e a program to disp lay them
increasing num erica in lstBox in
l o rd er. Note : Setti ng lstB ox . Sort ed = T r u e wi ll not do the job.
20. Supp ose all the items in lstBox are
words. Writ e a prog ram to display them
in lstBox in
decr easin g alph abet ical ord er.
21. Writ e a prog ram that cont a ins a list box
(w ith Sort ed = False ), a labe l, and two butto
capt ione d Add an Item and Delete an Item. ns
Whe n the Add an Item butt on is clicked, the
gram should requ est an item with an inpu pro-
t dialog box and then inser t the item abov
curre ntly high light ed item . Whe n the Delet e the
e an Item butt on is click ed, the prog ram houl
remo ve the high light ed item from the list. d
At a ll times, the label shou ld display the num
of items in the list. ber
22. Con s ider the Leng th Con verte r in Fig.
9.5. Write a program to carry o ut the conv
(See the first prog ramm ing proje ct in C hapt ersio n.
er 7 for a table of eq uivalent lengths.)

a Converter

;::,
From

l'meter
Lmile
To
George Wash ington
John Adams
Thomas Jefferson
James Madison
James Monroe
John Q . Adams AI;Je at
Length to be Andrew Jackson inauguration :
converted : 5 Martin Van Buren
William Harrison
57
Convert John Tyler
James Polk
Converted Zachary Tay1or
Length : 15.00 Millard Fillmo re
:.___ ____J

FIGURE 9.5 Possible output for Exercise 22. FIGURE 9.6 Possible outp ut for Exercise 23.

23. The file Age sAtl naug uara l.txt gives the
ages at inaugura tion of the first 44 U.S. presi
The first four lines of the file cont ain the dents.
data 57, 61, 57, 57; th e ages of W as hing
Ada ms, Jeffe rson , and Mad iso n a t the ir to n,
inaugura tion . The file USP res.t xt cont ains
na mes of the first 44 Uni t d Sta tes pres iden the
ts in the o rd er they were inaugura ted . Writ
a prog ram that plac es the na mes of the pres e
iden ts into an un so rted list box and the ages
at inaugura tion into an array. Whe n the
user click s on the n ame of a pres iden t, his
inau gura tio n sho uld be displ ayed in a text age at
box. (Hin t: A pres iden t's inde x num be r in
list box will be the sa me a th e inde x num the
ber of his age at inaugura ti o n in the a rray.
See Fig. 9.6. )
24. Writ e a program to ask a pers on whic
h Mon opoly® spac e he or she has land ed on
display the result in a text box. The respo and then
nse shou ld be obta ined with a com bo box
the squares most com mon ly land ed on: Park li ring
Place, Illinois Aven ue, Go, B&O Ra ilroa
and Free Parking. (On e possible outco me d,
to be displayed in the text box is "Yo u
land ed o n Park Plac e.") have

25. Writ e a prog ram to ques tion a perso n abou


t his or her com pute r and then display a desc
tive se nten ce in a text box. The form sho rip-
uld cont ain com bo boxes for bran d, amo
memory, and scree n size. The lists should cont unt of
a in the most co mmo n respo nses for each cat-
egory. Som e co mmo n co mpu ters are Com
paq, De ll, H ewle tt Pack ard, Leno vo, and
The most co mmo n amo unts of memory App le.
are 1 GB, 2 GB, and 4 GB. The most com
mo n
410 • Chapter 9 Add itional Co ntro l and Obje cts

the text
(On e pos ible outc ome to be disp laye d in
screen sizes are 17, 19, 20, and 24 inches.
of memory and a 17 -inc h mon itor.")
box is "You have a Dell com pute r with 2GB

Solutions to Practice Problems 9.1


and th e secon d occ urren ce is
d istinc t. How eve r, if an item is repea ted
1. Yes, if a ll the items in the list box are d state ment will delet e the ea rli er
de lete that item, wher eas th e secon
se lected , then the first state ment will
occ urren ce of the item.

9.2 Eigh t Additional Controls and Objects

iiJ The Timer Control


on the form dur ing run t ime, raises an
even t afte r a
The time r cont ro l, whi ch is not visib le Windows
e time r cont rol is foun d only in the All
Video Note
Addit ional contro ls specified amo unt of t ime has passed. (Th lbox, it
le-cl ick on th e time r cont rol in the Too
Forms grou p of the Too lbox. Wh en yo u doub time, mea-
om of the Form Designer.) The leng th of
appears in the com pon en t tray, at the bott r from 1 to
e Inte rval property to be any inte ge
sured in milliseconds, is set with th i econ ds
t ra i ed each time Tim erl.I nterva l mill
2, 147,483,647 (abo ut 596 hours). The even on by setti ng
begin timing, a time r must first be turn ed
elapses is called Timerl.Tick. In orde r to prop erty to Fal e. The
turn ed off by se tting its Ena bled
its Enabled property to True. A time r is
rol is tmr .
stan dard prefix for the name of a time r cont

h that upda tes the time every tent h


..; Example 1
of seco nd .
a
The fo llow ing prog ram creates a stopwatc

PROPERTY SETIING
OBJECT
ll Stop watc h CEJI B I~ frmStopw atch Text Stop watc h
btnS tart Text Star t
Start lb l econ ds Text Seco nds:
txtSe concl s ReaciOnl y True
btnS top Text Stop
Seconds:
tmrWatch [nter va l 100

Stop

~ r:mrWa 'ch

. ) Han dles btn Sta rt . Clic k


Priv ate Sub btnS tart _ Clic k ( ..
tx t Sec onds . Tex t = "0" 'Res et watc h
tmrWa t c h . Ena bled = True
End Sub
. ) Han dles btnS top . Clic k
Priv ate Sub btnS top_ Clic k( ..
t mrWatc h .Ena bled = Fals e
End Sub
. ) Han dles tmrW atch . Tick
Priv ate Sub tmrW atch_ Tick ( ..
roun ded to one deci mal plac e
'N K line disp lays the time
(txt Sec ond s.Te xt) + 0.1) )
t xtS e c o n ds . Tex t = CSt r (( CDb l
End Sub
9.2 Eigh t Add ition al Con trols and Obj
ects • 411

[R un, cl ick on the Sta rt but ton ,


wai t 10.5 seco nds, and cli ck on the
Sto p but ton .]

a-j Stop wat ch l = I@J L s-z J

Start

Seconds : 10.5

Stop

The Random Class


Visual Basic has a usefu l obje ct call
ed a ran 1om num ber gen erat o r tha
men t of the form t is dec lare d wit h a stat e-

Dim rand omN um As New Ran


dom

If m and n are who le num ber s, wit


h m < n, the n the value of
rand omN um. Nex t(m , n)

is a rand oml y elec ted who le num


be r from m thro ugh n, incl udin g
met hod of th is bui lt-in obj ect a llow m but exc ludi ng n. The Nex t
s us to prod uce so me in tere st ing
app lica tion s.

Example 2 A lott ery num ber is obt a ined by


thre e sepa rate bow ls. Eac h ba ll sele cting a Ping- Pon g ba ll from
is num bered with an inte ger from eac h of
prog ram pro duc es a lo ttery num 1 thro ugh 9. The foll owing
ber. S uch a program is sa id to sim
Pon g ba lls. ulat e the se lection of Ping-

Pri vat e Sub btn Sel ect Cli


ck( .. . ) Han dles btn Sel ect
'Di spl ay the win nin g lot .Cl ick
ter y num ber
Dim rand omN um As New Ran
dom
Dim num l, num 2, num3 As
Int ege r
num l ran dom Num .Ne xt(l , 10)
num 2 = rand omN um . Nex t(1,
10)
num3 = rand omN um. Nex t(1,
10 )
txtN um ber s.T ext = num 1
& 11 11
& num2 & 11 11
& num3
End Sub

[Ru n, and the n clic k on the but ton


.]

a-;; l otte ry

Sele d Ill/inning Number

9 8 4
ls and Obj ect
412 • Cha pter 9 Add itio na l Co ntro

The TooiTip Control


in the Too l-
uses too lti ps to id ent ify but ton s on the Too lba r and ico n
The Visual Basic lDE rec tan gul ar box appea rs afte r
hov er the mo use ove r one of these items, a sma ll
box . Wh en we ws us to cre ate too ltip s
fo r 5 sec ond s. Th e Too lTip con trol allo
1
/zsec ond and rem ains visible
for the con tro ls in our programs.
A ToolTip Walkthrough
program.)
i no need to give a name to the
1. Sta rt a new program. (Th ere wi ll appear wit h the
ble -cli ck on the Too lTip con trol in the Too lbox. (Th e con trol
2. Dou Fo rm Des ign er.)
pon ent tray at the bot tom of the
defaul t name Too lTip l in the com (Th e sett ing for the
s on the form and ent er cod e as shown in Exa mp le 3.
3. Place con trol app ea r wh en the
Too lTip l" pro per ty of txtR ate holds the info rma t ion tha t wi ll
"ToolTip on
.)
mo use hovers ove r the tex t box

use r might
e the sales tax rate is 5%. Th e
Example 3 In the following progra m, suppos
comes to the re cue.
.05 into the tex t box. A too ltip
not kno w wh eth e r to ent er 5 or
PROPERTY SETTING
OBJECT
Sa les Tax
~~ ... Sales Tax GJ I @) IE§J frm Nam e Tex t
Tex t Sa les tax rate:
lblR ate
Too lTip o n Suc h as 5, 5.25, 5.5
Sale s tax rate : txtR ate
Too ltip l
Price : Tex t Price:
lblP rice
txt Price
Calculate Tota l Cost Tex t Ca lcul ate To tal Cos t
btnC alcu late
Tex t Tot a l cost :
lblT otal Cos t
Rea dOnl y True
Tota l cost : txtT ota lCo st

~ Too iTip l
Ca lcu late .Cl ick
_ Cl ic k( ... ) Han dle s btn
Pri vat e Sub btn Ca l cul ate
= CDb l ( txt Ra te . Tex t ) I
100
Dim tax Rat e As Dou ble t)
CDb l (tx tPr ice . Tex
Dim pri ce As Dou ble = ce
Dou ble = p ric e + tax Rat e * pri
Dim tot alC ost As talC ost )
ma tCu r r enc y (to
txt To talC ost .Te xt = For
End Sub
r the first tex t box.]
[Run, and hov er the mo use ove

a ... Sale s Tax l = I@) ~~-1


Sale s tax rate : I I
[ Such as 5, 5.25, 5 .5 ..
Price :

Calculate Tota l Cost

Tota l cost :
9.2 Eigh t Add ition al Con trols and Obj
ects • 413
Normally, a con trol placed on a form
does not have a "ToolTt p on Too lTip
property app ears in the Prop erties l " prop erty. Tha t
window only after a Too lTtp con trol
compon ent tray. has bee n add ed to the
In the exa mp le abo ve, we crea ted
a too ltip for on ly one of the text box
could have spec ified a toolt ip for the es. Howeve r, we
oth er con trols.
By default, a tool tip app ears 1/ seco
2 nd afte r the cursor hovers ove r a con
5 seco nds. These two dura tion s can trol and lasts for
be alte red with the Too ltip con trol
Aut oPo pDe lay properties. The num 's A utom atic Oelay and
eric sett ings for these two prop erti
Spe cifically, the Aut oma ticO elay sett es are in millisecond s.
ing dete rmines the leng th of time requ
app ear, and the Aut oPo pDe lay sett ired for a tooltip to
ing dete rm ines the leng th of time the
while the cursor is station ary inside too ltip rem ains visible
a control.

The Clipboard
The Clip boa rd object is used to cop
y or move info rma t ion from one loca
mai ntai ned by Win dows and therefor tion to ano ther. It is
e eve n can be used to tran sfer info rma
dows applica tion to ano ther. It is actu t ion from one Win -
ally a port ion of mem ory that hold s
no properties or eve nts. info rma tion and has
If str is a strin g, then the stat eme nt

Cli pbo ard . SetT ex t(s tr)

replaces any text curr entl y in the C


lipb oard with the valu e of str. The stat
eme nt
str = Clip boa rd.G etT ext

ass igns the tex t in the C lipb oa rd to


the strin g vari ab le str. The stat eme
nt
Clip boa rd . Set Tex t("" )

deletes the con tents of the C lipb oard


.
A por tion of the text in a text box
or combo box can be selected by drag
across it or by mov ing the cursor acro ging the mouse
ss it wh ile hold ing dow n the Shi ft
text , you can place it into the C lipb key. Aft er yo u select
oard by pressing Ctrl + C. Also, if
box and you press C trl + V, the con the cursor is in a text
tent s of the C lipb oard will be pasted
These tasks also can be carried out at the cursor position .
in code. T he Sele cted Tex t prop erty
elec ted strin g from the text box, and of a text box hold s the
a stat eme nt such as
Cli pbo ard . SetT ex t(tx tBo x
. Se lect edT ext )

cop ies this selected strin g into the


Clip boa rd. The stat eme nt
tx t Box . Sel ecte dTe xt = Clip boa rd.G etT ext

replaces the sele cted por tion of txtB


ox with the con tent s of the Clip boa
se lect ed, the stat eme nt inse rts the con rd. If not hin g has bee n
tents of the C lipb oard into txtB ox at
the curso r pos itio n.

The Picture Box Control


The pict ure box con tro l is designe
d to ho ld draw ings c reat ed with grap
tures stored in grap hics files such hics com man ds or pic-
as bmp fil es crea ted with W ind ows
tha t co me with Win d ows, or gif and Pain t, ico fi les of icon
jpeg images used on the Wo rld W
tion , names of pict ure box con trol ide Web. By con ve n-
s h ave the prefix pic.
and Obj ects
414 • Cha pter 9 Add itio na l Con tro ls

A stat eme nt of the form


y, w, h)
Rec tan gle (Pe ns . Blu e, x ,
picB ox .Cr eate Gra phi cs.D raw
e ight h pixels
are of type Inte ger, draw s a blu e rect ang le of wid th w pixe ls and h
whe re x, y, w, h pixels from the left side and
cor ner of th e rect ang le will be x
in the pict ure box. The upper-left fee l for how big a pixel is,
ls from the top side of the pict ure box. (Se e Fig. 9.7.) To get a
y pixe ls by 300 pixe ls.
you crea te a new pro ject is 300 pixe
the init ial size of the form whe n

w
w

FIGURE 9.8 Elli pse argu men ts.


FIGURE 9.7 Rec tangle argu men ts.

aced with DrawEllipse,


oth er colo rs. IfD raw Rec tang le is repl
The colo r Blue can be replaced by angle just described.
nt abo ve will draw th e ellip se that wou ld be insc ribed in the rect
the stat eme d iam eter of
if wa nd h hav e the sam e va lue, the ellip se wi ll be a c ircl e wit h a
See Fig. 9.8 . A lso, ls, a whi te bac kgr oun d, and
box has a size of 140 by 140 pixe
tha t va lue. In Fig. 9.9, the pict ure
le is draw n with the stat eme nt
a Fix edS ingl e bo rder styl e. The circ
35, 70, 70)
wE llip se( Pen s.R ed, 35,
picB ox .Cr eat eGr aph ics. Dra

11:1 Grap hics in a Pictu re Box

[ Draw Orcle

0
FIGURE 9.9 Pict ure box con tai ning red circ le.

property. If you dou ble-


ure box con trol wit h the Image
A pict ure can be placed in a pict app ea rs and assists you in
des ign tim e, an Ope n dia log box
clic k on th Ima ge pro pert y dur ing y, you sho u ld set the
an app rop riat e file. H owe ve r, prio r to sett ing th e Image pro pert
se lect ing ure box con tro l will
pro pert y. If the S izeM ode pro pert y is set to Aut oS ize, the pict
S izeM ode Stretc hlm age, the pic ture
the S izeM ode pro per ty is set to
be resized to fit the p icture. If Stre tch image sett ing , pic-
resi zed to fit the pict ure box co ntro l. The refo re, wit h the
will be o r enlarged (by plac-
be red uce d (by p lac ing the m in to a sma ll pict ure box con trol)
ture s can re 9. 10 shows a pict ure
trol bigge r tha n the pict ure) . Figu
ing the m into a pict ure box con .
Stre tch image to fit the pict ure box
crea ted with Paint and redu ced by
9.2 Eigh t Add iti ona l ontrols and Objects
• 415

a';} Gra phic s in a ·ct ure Box

0
FIGURE 9.10 Pict u re box with dese rt scen e.

A pict ure also can be ass igned to a


pict ure box con tro l at run time. H owe
such as ver, a stat eme nt

picB ox.I mag e = fi lesp ec

will not do the job. Inst ead , we mus


t crea te an Image obje ct with a stat
eme nt such as
picB ox .Im age = Ima ge . From F i le( fi lesp ec)

The S izeM ode prope rty can be alte


red at run time with a stat eme nt such
as
picB ox.S izeM od e = Pic ture Box Siz e Mo de.A utoS
ize

The MenuStrip Control


Vi ual Bas ic form s can have menu bars
simi lar to tho e in mos t W indo ws app
shows a typ ical menu bar, with the Ord lica tion s. Figu re 9. 11
er men u revealed. Here, the menu bar
items (Order and Color), refe rred to con tain s two men u
as top~level men u items. Wh en the
cl icked, a drop -dow n li t con tain ing Order men u item is
two seco nd- level men u items (Ascend
appears. A ltho ugh not visible here ing and Descending)
, the dro p-do wn li t und er Color con
leve l menu items Foreground and Bac tain s the two seco nd -
kground. Eac h menu item is trea ted
that respond s to a C lick eve nt. The as a d ist inct con tro l
C lick eve n t is rai ed not only by the
ton , but also for to p ~ leve l items by clic k of the mouse but-
pres ing A lt + access Key and for seco
pressing the access key. The eve nt nd- leve l items by just
proc dure for the Asce nding or Des
can be raised by pressing the sho rtcu cend ing menu item also
t key comb inat ion C trl + A or C trl
+ D.

@J i~ l·
aj Dem o s'l ate f'l> en s l=
Qrder I £;;olor
I ll,s.c ending Ctri+ A
I
Qe5.cend ing Ctri+D

FIGURE 9.11 A simple men u.


Objects
41 6 • Cha pter 9 Add ition al Con tro ls and

the Menus & Too lbars


are crea ted wit h the Me nuS trip con tro l- the thir d con trol in
Me nus ) and a N ame
Too lbox . Eac h men u item has a Tex t prop erty (wh at th e user sees
group of the gh c rea tes the menu bar
in cod e. ) The foll owing wal kth rou
proper ty (use d to refe r to the item
in Fig. 9.11 :

1. Sta rt a new program . l app ears in the co m-


con tro l in the Too lbox . The co ntro
2. Double-clic k on the Me nuS trip in the Form Des igne r.
ent tray , and a men u des igne r appears just belo w the title bar
pon
See Fig. 9.12 .

Forml.vb [Design] * X

a .... __F()rml
..C:2Jl 8 I
... ...........................................

'\ }
0

:: - - . - ·····- -- -- -
menu designer

o................... .................,

'... ~.. ~.t:n.~~~ripl···,


a form.
FIGURE 9.12 The Men uStr ip con trol added to

and press the Ent er key.


on the rect ang le tha t ays "Type Here", type in "&O rde r",
3. C lick ere" rect angles
ersa nd spec ifies 0 as an acc ess key for the menu item.) "Type H
(Th e amp w the O rder menu
Order menu item. The rect ang le belo
app ear belo w and to the righ t of the rec tang le on the righ t is
el item for the Order menu. The
item is used to crea te a seco nd -lev
u item .
used to crea te a new first -level men
and pre s the Ent er key.
e "&A scen din g" into the rect ang le below the Order rect angle,
4. Typ the Property window,
to display its Pro perty window. In
5. C lick on the Ascending men u item ool Stri pM enu ltem to
the Nam e prop e rty of the menu item from Ascend ingT
cha nge tKeys Set tings
sc. Als o, clic k on the dow n- arrow at the righ t of the Sho rtcu
mnu Ord erA n-ar row but ton of the
und er Mo difiers, clic k on the dow
box , clic k on the C trl ch eck box er key. ("C trl + A " will
dro p-d own list, and press the Ent
Key combo box , clic k on A in the
ending.)
app ea r to the righ t of the word Asc
ang le, set the N ame prop-
rect ang le belo w the A scending rect
6. Type "&D esce ndi ng" into the rtcu tKe ys Pro perty to
of the Des cend ing men u item to mnu Ord erD esc, and se t the Sho
erty
C trl + D.
the tex t "&C olo r".
on the rect ang le to the righ t of the Order rect ang le and ent er
7. C lick set its N ame prop-
"&F oreg rou nd" into the rect ang le belo w the Color rect ang le, and
8. Type
erty to mnu olo rFo re.
ang le, and se t its N ame
rectang le belo w the Foreground rect
9. Type "&B ackgro und " into the
pro per ty to mnu ColorB ack.
9.2 Eigh t Additional Controls and Objects
• 417
10. C lick on the Foreground recta ngle,
and type "&R ed" into the recta ngle on
have just crea ted a third - leve l men u item its righ t. (We
. ) Set its Name prop erty to mnu Co lorF oreR
11. Type "&B lue" into the recta ngle ed.
below the Red recta ngle, and set its Na
mnu Co lorF oreB lue. me prop erty to
12. C lick on the Background recta ngle,
type "&Yel low" into the recta ngle on its
its Nam e property to mnu Co lorB ackYe llow right , and set
.
13. Typ e"& Wh ite" into the recta ngle belo
w the Yellow recta ngle, and set its Name
mnu Co lorB ackW h ite. The n set its C heck property to
ed property to True. A chec k mar k will
the left of the word "Wh ite". appear to
14. Run the program; cl ick on Order
to see its menu items; click on Color and
word Foreground to see its men u items. The hove r ove r the
menu items are usefu l only after we writ
for thei r C lick even t procedures. e code

Example 4 The fo llow ing prog ram uses the men u


just crea ted to alter the colo r of the
text in a list box and the orde r of its item
. The form has the text "De mon strat e Men
title bar. us" in its

Priv ate Sub frmD emo_ Load ( ...


) Han dles MyB ase .Loa d
lstO utpu t.Ite ms. Add ( "ma kes" )
lstO utpu t. Item s. Add ( "has te" )
lstO utpu t. Item s .Add ( "wa ste" )
End Sub

Priv ate Sub mnu Orde rAsc _ Clic


k( ... ) Han dles mnu Ord erA sc.C
lstO utpu t.So rted = True lick
End Sub

Priv ate Sub mnu Orde rDes c Clic


k( ... ) Han dles mnu Ord erD esc.
'Tvi o code se t e act that Clic k
if a list is in asce ndin g ord
then diap layi ng it back ward s er,
give s a desc end ing list
Dim temp (2) As Stri ng 'Hol d asce ndin g arra y of item
lstO utpu t.So rted = True s
'Sor t the item s alph abe tica lly
For i As Inte ger = 0 To 2 Plac
e sort ed item s into the arra
temp (i ) = CSt r (lst Out put. Item y
s(i ) )
Nex t
lstO utpu t . Sor ted = Fals e 'Tur n off the Sor ted pro pert
lstO utpu t.Ite ms. Cle ar( ) y
For i As Inte ger = 2 To 0 Step
-1
lstO utpu t . Item s.Ad d(te mp( i))
Nex t
End Sub

Priv ate Sub mnu Colo rFor eRed_


Clic k( ... ) Han dles mnu Colo rFor
lstO utpu t.Fo reC olor = Co l or . eRe d .Cli c k
Red
End Sub

Priv ate Sub mnu Colo rFor eBlu e


Clic k( ... ) Han dles mnu Colo rFor
lstO utpu t.Fo reC olor = Col or.B eBl u e.C li ck
lue
End Sub

Priv ate Sub mnu Colo rBac kYe llow


_ Clic k( ... ) Han dles
mnu Colo rBac kYel low . Clic k
'Mak e Yell ow the back grou nd
colo r of the list box, gua rant
ee that a
ects
41 8 • Chapter 9 Add itiona l Con trols and Obj

and not in fro nt


nt of the men u item Yel low
'che ck mar k app ears in fro
'of the Wh ite men u item
lstO utp u t.B ac kCo lor = Col
or.Y e llow
mnu Col orB ackY ello w.C hec ked = Tru e
mnu Col orB ack Wh ite . Che cke d
= Fal se
End Sub

Col orB ack Wh ite.C lick


hite _ Clic k( ... ) Han dles mnu
Pri vat e Sub mnu Col orB ackW
lstO utp u t . Bac kCo lor = Col
or.W hite
ed = Fal se
mnu Colo r Bac kYe llow .Ch eck
mnu Co l o r Bac kW hite . Che cke d
= Tru e
End Sub
ove r Foreground,
k on Asce nding in the Order men u, clic k on the Color menu , hover
[Run, clic
and click on Red.]

§] L .l
a:} Demonst rate l
enu s L!:==.J~::J~~~
SL

Orde r Co lor

[5:~:~:~:::::::::::::::::::::::::::::::::::
makes
waste

Bar Controls
• The Horizontal and Vertical Scroll
one of the a rrow but-
scroll bars . W hen the user clicks on
Figure 9.13 show the two types of the user clicks betw een
dist anc e toward that arrow. Wh en
tons, the scro ll box moves a sma ll e dist ance toward that
buttons, the scro ll box moves a larg
the croll box and one of the arro w

'" .__ Top arrow

Scroll box _ _ _ _ _ _.,... ~

t t
Right arrow
[ ~ .._ Bottom arrow
Left arrow
.
FIGURE 9.13 H orizonta l and vert ical scro ll bars
9.2 Eight Add itiona l Controls and Objects
• 419

arrow. The user can also move the scroll box by dragg ing it. The ma in propertie of a scroll bar
control are Minimum, Maximum, Value, S mallC hange, and LargeChange, which are set to
integers. The stand ard prefix for the name of a scro ll bar is hsb or vsb. At any time, hsbBar.Value
is a number between hsbBar.Minimu m and hsbBa r.Max imum determined by the pos ition of the
left side of the scroll box. If the left side of the sc roll box is ha lfway between the two arrows,
then hsbBar.Va lu e is a number ha lfway between hsbBar. Minimum and hsb Bar.Max imum. If
the scroll box is near the left arrow button, then h bBar.Va lu e is an approp riate ly proportion ed
va lue near hsbBar.Minimu m. W h en the user clicks on an arrow button, hsbBar.Value changes
by hsbBar.S ma llC hange and the scroll box moves acco rdingly. When the bar between the
scroll box and one of the arrows is cl icked, h sbBar.Value ch anges by hsbBar.LargeC hange and
the scroll box moves accordingly. When the scroll box is dragged, hsbBar. Va lu e change
acco rdingly. The default va lues of M inimum , Maximum, Va lue, S ma llC h ange, and
LargeCh ange are 0, 100, 0, 1, and 10, respectively. H oweve r, these values are usua lly changed
at design time. The width of the croll box is equal to the va lue of LargeCh ange. S ince
h sbBar.Va lu e is determined by the left sid e of the scro ll box, the greatest va lu e it can assume
is (hsbBar.Max imum - h sbBar.LargeC hange + 1) . Vertica l sc ro ll bars beh ave similarly.

Note : The etting for the Minimum property mu t be less than th e setting fo r the Max imum
prope rty. The Min imum property determines the va lu e for the left and top arrows. The
Maximum property determines the va lues fo r t he right and botto m arrows.

The two controls are refe rred to as HScro llBar and VScrollBar in the Toolbox. The ir
default event, Scroll, is raised whe neve r the user clicks on any part of the cro ll bar.

Example 5 The fo llow ing prog ram uses sc ro ll ba rs to move a miling face aro und
the form. The face is a large Wingd ings c ha rac ter ] insid e a labe l. The va lu es lblFace. Left
and lblFace.Top are the dista nces in pixe ls of the labe l from the left side and top of the
form.

"w Sm ili ng Face

~
~
420 • Chapt er 9 Add itional Controls and Objects

OBJECT PROPERTY SETTING

frmFace Text Smiling Face


hsbX Pos Min imum 0
Max imum 300
Small C hange 10
LargeC hange 50
Value 0
vsbYPos Min imum 30
Max imum 300
Small Chang e 10
LargeC hange 50
Value 30
lblFace Text J
Fon t Wingd ings, 24pt

os.Sc roll
Priva te Sub hsbXp os Scrol l( ... ) Handl es hsbXp
lblFa ce.Le ft = hsbXp os.Va lue
End Sub
os.Sc roll
Priva te Sub vsbYp os Scrol l( ... ) Handl es vsbYp
lblFac e.Top = vsbYp os.Va lue
End Sub

[Run, and move the scroll boxes on the scroll bars.]

a S iling ace

Practice Problems 9.2

1. What is the effect of the following event procedure?


btnDi splay .Click
Priva te Sub btnDi splay_ Cl ick( ... ) Handl es
Dim random Num As New Random
, "Lind a",
Dim conte stant () As Str ing= {"Mar y", "Pat"
"Bar bara" , "Mari a"}
9.2 Eight Add itional Contro ls and Object s
• 421

Dim numbe r As Integ er, temp As Strin g


For i As Integ er = 0 To 3
numbe r = random Num.N ext(i, 5)
temp = conte stant (i)
conte stant (i) = conte stant( numb er)
conte stant( numb er) = temp
Next
1st0u tput.I tems. C1ea r()
For i As Integ er = 0 To 4
1st0u tput.I tems. Add( conte stant( i))
Next
End Sub

EXERCISES 9.2

In Exerc ises 1 throug h 6, determ ine the effect of setting


the prope rty to the value shown .
1. Timer l.Inte rval = 5000
2. Timer l.Enabled = False
3. T oolTip l.Auto maticDelay = 1000
4. ToolTipl.Au toPop De lay = 4000
5. mnuO rderA sc.Ch ecked True
6. mnuO rd erAsc.Chec ked False
In Exerc ises 7 throug h 25, descri be the effect of execu ting
the statem ent(s) .
7. Time r1.Int erva1 = Cint( intVa r * 1000)
8. Dim random Num As New Random
txtBo x.Tex t = CStr(r andom Num.N ext(1, 101))

9. Dim random Num As New Random


Dim numbe r As Integ er
'Assum e the array pres( ) conta ins the names
of the 44 u.s. presi dents
numbe r = random Num.N ext(O, 44)
txtBo x.Tex t = pres(n umbe r)

10. Dim random Num As New Random


'95 chara cters can be produ ced by the compu
ter keybo ard
txtBo x.Tex t = Chr(ra ndomN um.Ne xt(32, 127))

11 . Dim random Num As New Random


Dim numbe r As Integ er, temp As Strin g
'Supp ose the array state s() conta ins the
names of the 50 state s
numbe r = random Num.N ext(O, 50)
1stBo x.Item s.Add (state s(num ber))
temp= states (num ber)
states (num ber) = states (49)
states (49) = temp
1stBo x.Item s.Add (state s(rand omNu m.Nex t(O,
49)))
422 • Chap ter 9 Addit ional Contr o ls and Object

12. Dim rando mNum As New Rando m


"Clu bs", "Diam onds" , "Spa des"}
Dim suit( ) As Strin g= {"He arts" ,
, "3", "4", "5", "6",
Dim deno mina tion( ) As Strin g= {"2"
"10 11 "Jack ", "Que en", "Kin g 11 , "Ace "}
11
7 11 , "8", "9", ,

m.Ne xt(O, 13)) & "of " &


txtBo x.Te xt = deno mina tion( rando mNu
suit(r ando mNu m.Ne xt(O, 4))

13. Clipb oard . SetT ext (" " )


14. Clip boar d.Se tTex t("H ello" )
15. Clipb oard . Set Text (txt Box. Selec tedT ext)
Text ()
16. txtBo x. Selec tedT ext = Clipb oard . Get
17. txt Box . Text = Clipb oard . Get Text
18. Dim strV ar As Strin g = "Happ y"
Clip boar d.Se tTex t(strV ar)
19. Dim strV ar As Strin g
strV ar = Clipb oard .GetT ext
e.Str etchi mage
20. Pictu reBo xl.Si zeMo de = Pictu reBo xSize Mod
e(Pe ns.B lue, 20, 30, 100, 100)
21. Pictu reBo xl.Cr eateG raph ics.D rawE llips
gle(P ens.G reen, 25, 50, 200, 100)
22. Pictu reBo xl.Cr eateG raph ics.D rawR ectan
23. Pictu reBo xl.Im age Imag e . From File ("Air plane .bmp" )
r2 . Minim um) I 2)
24. HScr ollBa r2.V alue Cint( (HSc rol l Bar2. Maxi mum + HScr ollBa
r2.La rgeC hang e
25. VScr ollBa r2.Sm allCh ange = VScr ollBa
of code to carry out the task.
In Exer cises 26 throu gh 44, write one or more lines
econd .
26. Spec ify that Time rl raise an even t eve ry half
t.
27. Spec ify that Time rl cease to raise the Tick even
28. The array nam es conta in twen ty names. Displ
ay a rando mly selec ted name in txtBox.
from 1 to 12.
29. Display in txtBox a rando mly selec ted numb er
30. Display in txtBox a letter rando mly selec ted
fro m the alpha bet.
ty-fi ve cities. Display a rando mly selec ted
31. The file Town s. txt conta ins the names of twen
city in txtBox.
ing a pair of dice.
32. Display in txtBox the sum of the faces after toss
rivers. Rand omly selec t two different rivers
33. Suppose the array rivers co nta ins the names of
from the array and display them in lstBox.
nts of the C lipbo ard .
34.Rep lace the selec ted portio n of txtBox with the conte
35. C lear the conte nts of the C lipboard .
36. Place the word "Rose bud" into the C lipbo
a rd.
ard.
37. Copy the selec ted tex t in txtBox into the C lipbo
38. Delet e the selec ted portio n of txtBox.
39. Ass ign the conte nt of the C lipbo ard to the
integer varia ble am ount.

40. Draw a ye llow circle of diameter 100 pixel


s in PictureBox l.
item named mnuO rd erDesc.
41. Remove the check mark in fro n t of the menu
rder".
42. C hange the tex t for mnuO rderDesc to "Dec reas ing O
43. Move the scroll box of V crollBar2 as high
as possible.
the way fro m the left arrow to the right arrow.
44. Move the scroll box of HScrollBa r2 one-third of
9.2 Ei ght Addition al Controls and Objects • 423

Exercise s 45 and 46 refer to Example 4.


45. Make a conj ecture on the effect of the following statemen t and test your conj ecture
.
rnnuOrd erAsc.En abled = Fal s e
46. Make a conj ecture on the effect of the followin g statemen t and test your conj ecture.
rnnuOrd erAsc.V isi b le = Fa l se

47 . Write a program to create a decorat ive digital clock. The clock in the Digita l C
lock form
in Fig. 9. 14 is inse rted in a picture box con tro l co ntaining the Trees.bm p picture.
The
va lue fo r hour, minu te, and seco nd ca n be ob tained as H our( Now), Minute( Now ),
and
Second( N ow).

oA Coin Toss

Outcome : Heads

Number of Heads : 308 Number of Tails: 299

Total Number of Tosses: 607

Percent Heads: 50_74%

Toss the Coin

FIGURE 9. 14 Sample run of Exercise 4 7. FIGURE 9.15 Sample run of Exercise 48.

48. W rite a program using the form in Fig. 9. 15 . Each time the button is pressed, a
Random
object is used to si mul ate a coin toss and the va lues are updated . The figure shows the
sta-
tu s after the button has been pressed 607 time . Note: You can prod uce tosses quickly
by
just holding down the Enter key. Although th e perce ntage of heads initially will flu ctuate
cons iderab ly, it should stay close to 50% after many (say, 1000) tosses.
49. The file Members. txt contains the names of the members of a large club. Write
a program
to random ly se lect people to se rve as Pres ident, Treasure r, and Secretary. Note: A person
cannot hold more than one office.
50. Place the names of the 52 play ing cards in to the array deckOfCards . Then disp lay the
names
of five randomly chosen cards in lstPokerH and.
51. W rite a program that repeated ly rolls a pair of dice and tallies the number of ro lls
and the
number of those ro lls that tota l seven. The program should stop when 1000 sevens
have
been ro lled, and then report the app roximate odds of rolling a seven. (The approxim ate
odds
will be "1 in " followed by the result of div id ing the number of rolls by the number of
ro lls
that came up seven.)
52. Write a program to randoml y select 40 different people from a group of 100 people
whose
names are contained in the text file N ames.txt.
53. The Birthday Problem . G iven a random group of 23 people, how likely is it that two
people
have the same birthday? To answer this question, write a program that creates an array
of
23 elements, randoml y ass ign to each ub cripted variable one of the integer from 1 through
365, and checks to see if any of the subscript ed variables have the same value. (Make the
sim-
plify ing assumpti on that no birthdays occur on February 29.) Now expand the program
to
repeat the process 1000 times and determin e the percentage of th time that there is a match
.
424 • Chapte r 9 Additio na l Contro ls and Objects

54. Consid er a carniva l ga me in which two ca rds are drawn


at random from a deck of 52 cards.
If neithe r card is a dia-
If eithe r one or both of the ca rds is a diamond, yo u win one dollar.
times and determ ine how much
VideoNo te mond, yo u lose one dollar. S imulate playing the game 1000
Bl ac kj ack money yo u win or lose.
( Ho mework) txtZ ipCode . The tooltip
55. Write a program contain ing text boxes named txtN ame and
appea r when the mouse
"Enter your full name." or "Enter your 9-d igit zip code." should
hovers over the corresponding text box .
on an item to delete it
56. Write a program contain ing a list box. The too ltip "Doub le-click
from the list." should appea r when the mouse hove rs ove r the list box.
on the hard drive) in a pic-
57. Write a program to display a picture (conta ined in a .bmp fil e
contro l.
ture box . The .bmp fi le should be selected with an OpenF ileOialog
single top- level item Edit
58. Write a program with a single text box and a menu hav ing the
place a copy of the
and the three second-level items Copy, Paste, and Cut. Copy should
duplica te the conten ts of
elected portion of the text box into the C lipboard, Paste should
d portion of the text
the C lipboard at the cursor positio n, and Cut should delete a selecte
box and place it in the C lipboard.
59. The C h09 \ Pictures folder contain s files named Moon1.bmp,
Moon2.bmp, ... , MoonS.bmp,
picture box contro l and
which show eight phases of the moon. Create a form consist ing of a
Image property of the picture
a time r contro l. Every two second s ass ign anothe r file to the
. One phase is shown
box contro l to see the moon cycle through its phases every 16 econds
in Fig. 9.16.

32. ...

212 Celsius

Fahrenheit

Sample run of Exercis e 59. FIGURE 9.17 Sample run of Exercis e 60.
FIGURE 9.16

in the Tempe ratures form in


60. Write a program to synchronize the two thermo mete rs shown
the other thermo meter
Fig. 9. 17 . When the scroll box of either thermo meter is moved,
atures displayed above
should move to the corresponding temperature, and the two temper
the thermo meters should be updated. Note : F = (9/S)C + 32.

61. Simulation of the Times Square Ball. C reate a form with a


vertica l scroll bar and a timer con-
the scroll bar. Each sec-
trol. When the program is run , the scroll box should be at the top of
When the scroll box reaches
ond the scroll box should descend one-te nth of the way down.
YEAR should appear.
the bottom after 10 second s, a message box displaying HAPPY NEW

Solution to Practice Problem 9.2


box in a random o rd er.
1. The even t procedu re pl aces rhe names of rhe contesta nts in a list
9.3 Mu ltip le-Form Progra ms
• 425

9.3 Multiple-Form Programs


A Visua l Basic program can conta in more than one form.
Additional forms are add ed fro m the
menu bar's Projec t menu by clicki ng on Add Windows Form,
wh ich brings up an Add N ew Item
d ialog box with "Win dows Form " highli ghted . To add
the new form, optio nally type in a name Video N ote
and press the Add butto n. The new fo rm has a defau lt name
such as Form1 or Form2 . The name Multipl e-
of each fo rm in the progra m appea rs in the Solu tion Explo form
rer windo w. See Fig. 9.1 8. When you
doub le-clic k on the name of a form, its Form Designer program s
appea rs in the Docu ment windo w. In
practi ce, forms are given de cript ive names. H oweve r,
we will initia lly use the defau lt names.

Solutio n Explorer
~ _-_ , ~
a ~
-:::-
..=..J=:..J
];] WincdowsAppl ica~tion l
~ My Project
.:::J
Fo rml.v b
~ Forml .v b

FIGURE 9.18 Solution Explo rer windo w after a secon d for m is added
.

T he most comm on use of an additional form is as a custo


mized input dialog box (Fig. 9.1 9 )
or a custo mized message dialog box (Fig. 9.20). The
form in Fig. 9. 19 cou ld appea r to limit
access to the rest of the progra m only to a user who enters
a regist ered user name and passwo rd .
In Fig. 9.20 the outpu t of the Weekl y Pay roll case stud
y fro m C hapte r 5 is d isp layed in a second
fo rm instea d of in a li t box .

Name : AJ Oark

Gross pa)' this period : 1.729.


Year-to-date eamings :
D Lo gi n Fo rm ~~ 8 ~~ .;:a .329.

FICA taxes this period : S132.27


User name :
Income tax withhe ld: 1&3.
Password :
Net pa)' (check amount): 1.433.2 9
Continue
[ Print ] [ Retum to Data-Entry Form

FIGURE 9.19 Custo mized input dialog box. FIGURE 9.20 C ustom ized message dialog box.

Startup Form
W hen a progra m starts runn ing, only one fo rm (calle
d the startu p for m ) will be loaded. By
defaul t, the first fo rm create d is the sta rtu p form. The
follow ing steps change the startup form.
1. Right -click on the na me of the progra m at the top
of the Solu t ion Exp lorer window and
cl ick on Properties in the drop-down contex t menu .
The progra m's Projec t De igner will
appea r.
2. C lick the App lica tion tab.
426 • Chap ter 9 Additiona l Cont rols and Objects

n list.
3. Selec t a form fro m the Startup form drop -dow
X sy mbo l on its tab.
4. C lose the Proje ct Designer by click ing the

Scope of Variables, Constants, and Procedures


(or local-leve l) , and class-level (or modu le-
We have cons idered block-leve l, proced ure- level can
in ide a block (such as a Do loop or If block )
level ) scope. A variable or cons tant decla red a va riabl e or
s out of the block. If yo u decla re
no longe r be refer red to when execu tion passe
with in that proce dure, you can think of the
cons tant inside a proce dure but ou tside any block re a
the block is the entire proce dure. You decla
variab le as havin g block -leve l scope, wher e t outs ide of any
plac ing its Dim or Co nst state men
class- level var iab le o r consta nt for a form by ' code .
be referr ed to anyw here in the form
proce dure. C lass- leve l variables or cons ta nts can
ca n exten d the scope of a class- level vari-
If a program h as more than one form, th en you
keyword Publ ic in place of the keyword Dim in
able to all the forms in the program by using the
said to h ave name space -leve l scope. Let's refer
its decla ratio n state ment . The variab le is then is
a its declaration form. Whe n such a varia b le
to the form in whic h the variab le is decla red
ratio n fo rm's name (followed by a perio d) must
referred to in the code of anot her form , the decla
the variab le total decla red as a class- level vari-
prece de the name of the variable. Fo r insta nce,
able in Form l with the state ment

Pu blic tota l as Doub l e

in Form2 .
must be referred to as Form I. total when used
The scope of a class- level cons tant is conv erted to namespace- level by prece ding the key-
era l proce dure and a S truct ure decla ratio n have
word Cons t with the keyword Publ ic. A gen
their h eade r with the keyword Priva te will limit
name space- level scope by default. Prece ding with
ls always h ave name space -leve l scope. Just as
the ir access to the ir decla ratio n form. Cont ro , and cont rol must be
tants , gene ral proce dures
variables, the name s of namespace- leve l cons refer red to in anot her
wed by a perio d) when
prece ded by t heir decla ratio n form's name (follo
fo rm's code.

Modality
d
or mode less form. A moda l fo rm must be close
A fo rm can invok e anot her form as a moda l (Ord inary inpu t and mes-
rest of the program.
before the user can co ntinu e work ing with the
l form s.) With a mode less (or nonm odal) form, the user
sage dialog boxes are examp les of moda l
her form with out havin g to fir t close the initia
can shift the foc us betw een the form and anot
ple of a mode less fo rm.) In this book, new forms
form. (Vi ual Basic's Find dialog box is an exam
will always be invoked as moda l forms.

Close and ShowDialog Methods


e code cont a ins it. The C lose meth od actua lly
The state ment Me. Cl o s e () closes the form whos
The state ment
can be used to close any fo rm in the program.

frmO ther. Clos e ()


cont aining the state ment , closes frmO ther.
wh ere frmOther is a form othe r than the form
The state ment

frmO th e r.Sh owDi alog ( )

it the focus. (The tatem ent frmO the r. Show ()


displays the othe r form as a moda l form and gives
displays the othe r form as a mode less form .)
9.3 Multi ple-Fo rm Programs
• 427

The FormCiosing Event Procedure


The Load even t proce dure occur s before a form
is d isplayed fo r the first time o r before it is dis-
played afte r havin g been closed. Analogous to the
Load even t is the Form Clo ing even t that
occur s before the form is closed. (A fo rm is close
d by th e execu tion of a C lose meth od, by the
user's click ing on the form's C lose butto n in the
title ba r, or by the user's pressing A lt + F4.)

Importing an Existing Form


You can add a form crea ted in anoth er program to
the curre nt program with t he follow ing reps:
1. C lick o n Add Existing Item in the menu bar's Projec
t menu.
2. Navi gate to the progr am conta ining the form.
The progr am will conta in a fi le named
fonnN ame.v b.
3. Doub le-click on fonnName.vb. That file will be
copied into your program's Solu tion Explorer
and you will have added its form to your program.
Note : lf the added form refers to a text fi le,
the text file will have to be cop ied separately into
your program's bin \Debug folder.

Deleting a Form from a Program


To remo ve a form from a program, right- click on
its name in the Solu tion Exp lo rer, and click on
Delete in the drop- down conte xt menu . (An input dialo
g box wi ll ask you to confi rm the dele-
tion.) lf the delet ed form was the startu p form, you
will have to se lect a n ew startu p form.

Example 1 The follow ing progr am uses a second fo rm a a dia


log box to obta in and tota l
the d iffere nt sources f income. Initia lly, only frmln
co me i visib le. The use r types in his o r her
name and then can e ither type in the tota l inco me
or click on the butto n fo r as istanc e in tota l-
ing the differ ent so urces of incom e. C lickin g on
the butto n from frml ncom e causes frmS o urce
to appea r and be activ e. The use r fi lls in the three
tex t boxes and then clicks o n the butto n to
have the amo unts totale d and disp layed in the "To
tal incom e" tex t box of frmln co me.

OBJECT PROPERTY
~I ~ I~
D_. Incom e SETTING
frmln come Text Incom e
Name : lblNa me Text Name :
txtN ame
Total income : lblTo tlnco me Text Total incom e:
txtTo t!nco me
Determine Total Income btnDe termi ne Text Deter mine
Tota l Incom e

OBJECT PROPERTY SETTING


a..J Sourc es of Incom e
GJ~ []!J frmSources Text Sources of Income
Name : lblN ame Text Name :
txtNa me ReadO nly Tru e
W ages : lblWages Text Wages:
Interest income :
txt Wages
lbllnt lncome Tex t Intere st income:
Dividend income : txtlnt lncom e
lblDiv lncome Text Divid end income:
Compute Total Income txtDi vlnco me
btnCo mpute Tex t Comp ute Tota llnco me
428 • Chap ter 9 Addi tiona l Cont ro ls and Objects

'frm inco me's code (sta rt up form )


) Hand les btnD eterm ine.C lick
Priv ate Sub btnD eterm ine_ Clic k( ...
Text
frmS ourc es.tx tNar ne.T ext = txtN arne. clos es.
log () 'Show the seco nd form and wait unti l it
frmS ourc es .Sho wDia in this proc edur e.
Then exec ute the rest of the code
y( frmS ourc es .sum )
txtT otinc ome .Tex t = Form atCu rrenc
End Sub

'frm Sour ces• s code


valu es
Publ ic sum As Doub le 'hold s the sum of the text boxe s'

Hand les MyB ase .Loa d


Priv ate Sub frmS ourc es _ Load ( ... )
txtW ages .Cle ar()
txtin tinco me.C lear( )
txtD ivinc ome .Cle ar()
End Sub

) Hand les btnC ompu te .Cl ick


Priv ate Sub btnC ompu te_ Clic k( ...
ce-le vel vari able sum.
Stor e the tota l into the narn espa
(txti ntin com e.Te xt) +
sum= CDbl (txtW ages .Tex t) + CDbl
CDbl (txtD ivinc ome .Tex t)
ed any more
Me .Clo se() 'Clo se the form sinc e it is not need
End Sub
fill in the sourc es of incom e.] Note : Afte r the
[Run, enter a name, click on the butto n, and
s wi ll di appea r and the sum of the three
ComjJute Total Income butto n is pressed, frmSource
text box of frmln come.
numbers wi ll be disp layed in the Tota l Inco me

= @]
D I nco e

Name : John Doe


-
~

,l l = I@] 1~.-J
D~ So rces of In come

Total income : Name : John Doe

[ Detennine Total In Wages : 34567 .89

Interest incom e: 123.45

Dividend income: 2345.7Bj

[ Compute Total Income l

up form, frmOrder, proces es


Example 2 The fo llowing program u es two form s. The start
password with frmLog in. Even though frmOrder
an order after first requesting a u er name and
form seen by the user. It is invoked by frmOrder's
is the startup form, frmL ogin is actua lly the first
Load even t proced ure.
e. txt to chec k for a registe red user name and
The form frmLog in uses the text file MasterFil
a user name conc atena ted with an und ersco re
pa sword. Each line of the text file con ists of
of the file cont ain the data dcoo k_id ol08,
characte r and a password. The first three lines
9.3 Multi ple- Form Programs
• 429

JQPu blic_vbguy21, and sh awnj _dan ce09. After check


ing that the tex t boxes have been filled in,
the program u es a query to determine if the user name
and password comb inat ion is in th text
file. The user gets three chan ces to enter an accep
table respo nse. Code in a Form y losing even t
procedure preve nts the user from clo ing the login
form witho ut first giving a satisfactory user
name and password.

OBJECT PROPERTY SETTING


II _. Login Form G] l 8 ![};[] frmLo gin Tex t Login Form
User name : lblUse rN ame Text User n ame:
txtUse rNam e
Password : lblPassword Tex t Password:
txtPassword
Continue btnCo ntinu e Tex t Conti nue

OBJECT PROPERTY SETTING


D -' Order Form GJI 0 ICID frmO rder Text O rder Form
User name : lblUserN ame Text Use r name :
txtUserN ame ReadO n ly True
Numbe r of items ordered : lb lNum ltems Text N umbe r of
items ordered:
Proces s Order txtN umlte ms
btnProcess Tex t Process O rder
Total cost : lblTot alCos t Tex t Total cost:
tx tTota lCost Read O nly True
log Out btnLo gOut Tex t Log O ut

'frmO rder' s code (star tup form)


Priv ate Sub frmO rder_ Load ( ... ) Hand
les MyBa se .Load
frmL ogin .Show Dialo g()
txtUs erNa me . Text = frmL ogin .user Name
End Sub

Priv ate Sub btnP roce ss_ Click ( ... )


Hand les btnP roce ss . Click
Dim numi tems As Integ er
Dim total Cost As Doub le
numi tems = Cint (txtN umit ems. Text )
'cos t per item : $20; shipp ing cost :
$8
total Cost = (num items * 20) + 8
txtT otalC ost . Text = Form atCu rrenc y(tot
alCo st)
End Sub

Priv ate Sub btnLo gOut _ Click ( . .. ) Hand


les btnL ogOu t.Cli ck
Me . Clos e()
End Sub

'frmL ogin 's code


Publ ic userN ame As Strin g
Dim numT ries As Integ er = 0
Dim idVe rifie d As Bool ean False
430 • Chapter 9 Add ition al Cont ro ls and Objects

... ) Han dles btnC onti nue . Clic k


Priv ate Sub btnC onti nue_ Clic k(
(txtP assw ord. Tex t = "" ) Then
If (txtU serN ame .Tex t = '"' ) Or d." )
r both a user name and a pass wor
Mess ageB ox .Sho w( "You mus t ente
Else
assw ord. Tex t) Then
If Con firm (txtU serN ame .Tex t, txtP
idV erif ied = True
userN ame = txtU serN ame .Tex t
Me . Clos e ()
Else
name or pass wor d." )
Mess ageB ox . Show ( "Imp rope r user
txtU serN ame .Cle ar ( )
tx tPas swo rd.C lear ()
End If
End If
num Trie s += 1
erifi ed) Then
If (num Trie s = 3) And (Not idV
is bein g term inat ed." )
Mess ageB ox .Sho w( "Thi s prog ram
frmO rder . Clos e()
Me .C lose ()
End If
End Sub

As Stri ng ,
Fun ctio n Con firm ( ByV al userN ame
ByV al pass word As Stri ng ) As Boo lean
)
.Rea dAll Line s( "Ma ster File .txt"
Dim que ry= From line In IO. File
& pass word
Whe re line = userN ame &
Sele ct line
If quer y.Co unt = 1 Then
Retu rn True
Else
Retu rn Fals e
End If
End Fun ctio n

... ) Han dles Me .For mCl osin g


Priv ate Sub frmL ogin _ Form Clos ing(
If Not idV erif ied Then
is bein g term inat ed." )
Mess ageB ox .Sho w( "Thi s prog ram
frmO rder .Clo se()
End If
End Sub

the form .]
[Run , ente r a user na me and password into

II,. og in Form l =J@) ~ _j


Usern ame : JQPublic

Password : vbgll'l 1

:~~.0.~~~~~:
1!:.':... :.. .::.:.
..:!1
9.3 Mult ip le-Form Prog rams
• 43 1

[C lick on the butto n in the Login form. Then enter


a quan tity into the text box of the Orde r
fo rm below and click on the Process Order butto n.]

a~ Order Fonn l = I @) ~~ -d
User name : JQ Public

Number of items ordered : 2

Process Order

Total cost : S48.

Log Out

Example 3 We can easily modi fy the Weekly Payro ll case stud


y from C hapte r 5 so that
instead of the outpu t being displayed in a list box,
it is displayed in the form shown in Fig. 9.20.
The teps are as follows:

1. tart a new program with the name 9-3-3.


2. Delet e Form l. vb fro m the Solution Explo re r.
3. Add the existing form frmP ayroll from the progr
am 5-5 (Wee kly Payro ll ) to the new program.
4. C hange the startup form to frmP ayroll.
5. A dd a new form to the program and name it frmR
eceipt.
6. Design the form for frmR eceipt a shown in Fig.
9.20 on page 425 with the settin gs in Fig. 9.21.

OBJECT PROPERTY SETTING


fnnReceipt Text Payroll Receipt
lblGrossPay Text G ross pay this peri od:
txtG rossPay
lbiTot alPay Text Year-to-date-ea rnings:
txtTo talPay
lblFicaTax Text FlC A tax thi s pe riod:
tx tFicaTax
lblFed Tax Text Inco me tax withh eld:
txtFed Tax
lblC heck Text N et pay (chec k amou nt):
txtC heck
btn Pri nt Text Print
btnRe turn Text Retur n to Da ta- Entry Form
FIGURE 9.21 Contr ols and settin gs for frmR eceip t.

7. Doub le-cli ck on the Print Form contr ol in the Visua


l Basic PowerPacks group of the Toolbox.
The co ntrol will appea r with the defau lt name Print
Form l in the co mpon ent tray.
432 • Chap ter 9 Additi onal Cont ro ls and Objects

t even t
eceipt. Note : The code ins ide the btn Prin
8. Add the code show n in Fig. 9.22 to frmR
the prin ter.
proc edure prin ts the cont ents of the form on
,
As Stri ng , ByV al pay As Dou ble
Sub SetP ayro lli nfo( ByV al empName
fica Tax As Dou ble ,
ByV al tota lPay As Dou ble , ByV al
chec k As Dou ble )
ByV al fedT ax As Dou ble , ByV al
txtN ame. Text = empName
cy(p ay)
t x tGro ssPa y.Te xt = Form atCu rren
cy(t otal Pay)
t x tTot alPa y.Te xt = Form atCu rren
cy(f icaT ax)
txtF ic aTax .Tex t = Form atCu rren
fedT ax)
txtF edTa x . Text = Forr natC urre ncy(
chec k)
txt Che ck.T ext = Forr natC urre ncy(
End Sub

) Han dles btnP rint .Cli ck


Priv ate Sub btnP rint Clic k( ...
. Prin tAct ion .Pri ntTo Prin ter
Prin tFor ml . Prin tAct ion = Prin ting
Prin tFor rnl.P rint ( )
End Sub

) Han dles btnR etur n . Clic k


Priv ate Sub btnR etur n_ Clic k( ...
Me . Clos e ()
End Sub
FIGURE 9.22 Code for frmR eceip t.

ayro ll, replace the line


9. In the btnOispla y_C lick procedu re of frmP
fedT ax, chec k) Task 6
lPay , fica Tax ,
Show Payr oll(e mpN ame, pay, tota

with
e, pay, tota lPay , fica Tax ,
frmR ecei pt .S etPa yrol linfo (emp Nam
fedT ax, chec k) 'Tas k 6

frmR ecei pt .S how Dial og()

~·~~
Practice Problems 9_..~JL~~~
ame.
out using the namespace- leve l varia ble userN
1. Rewrite th e prog ram in Examp le 2 with

EXERCISES 9.3
ed.
outp ut disp layed whe n the butt on is click
In Exer cises 1 thro ugh 4, dete rmin e th e
1. 'For rnl' s code (sta rtup form )
) Han dles btnD ispl ay. Clic k
Pr iva te Sub btnD ispl ay _ Clic k( ...
Forrn 2.Sh owD ialo g()
Form 2.to talC ost)
txtO utpu t.Te xt = Forr natC urre ncy(
End Sub

e As Dou ble) As Dou ble


Fun cti on GetT otalC os t(ByVal pric
RATE *pr ice)
Retu rn pric e + (Form 2.SA LES_ TAX_
End Fun ctio n
9.3 Multiple- Fo rm Programs
• 433

1
Form2 1 s code
Public Const SALES TAX RATE As Double 0.06
Public totalCo st As Double

Private Sub Form2 Load( ... ) Handles Me.Load


Dim price InputBo x("What is the price?" )
total Cost Forml.G etTotalC ost(CDb l(price) )
Me.Clos e()
End Sub

(Assume that there ponse is 100. )


2. Form1 1 s code
1
(startup form)
Private Sub Forml Load( ... ) Handles MyBase. Load
Form2.S howDial og()
Dim name As String= Form2.t xtName. Text
Dim dob As Date = CDate(F orm2.tx tDateOf Birth.Te xt)
Dim parsedN ame() As String = name.S plit(" "c)
Dim firstNam e = parsedN ame.Fir st
Dim message As String
If dob.Add Years(21 ) <=Toda y Then
messag e= •, you are at least 21 years old."
Else
message you are not yet 21 years old."
End If
txtOutp ut.Text firstNam e & message
End Sub

1
Form2 1 s code
Private Sub Form2 _ Load( ... ) Handles MyBase. Load
txtName .Text = "John Doe"
txtDate OfBirth . Text = "2/3/198 9"
End Sub

Private Sub btnReco rd_ Click( ... ) Handles btnReco rd.Click


Me. Close()
End Sub

3. Forml 1 s code
1
(startup form)
Private Sub Form1_ Load( ... ) Handles MyBase. Load
Form2.S howDial og()
Dim name As String= Form2.fu l1Name
Dim l astName As String= Form2.G etLastNa me( name)
txtOutp ut.Text = "Your last name begins with " &
lastNam e.Substr ing(O, 1) & " "
End Sub

1
Form2 1 s code
Public fullNam e As String

Private Sub btnDete rmine_ Click( ... ) Handles btnDete rmine.C


lick
fullNam e = "John Fitzger ald Kennedy "
434 • Chapte r 9 Additio nal Controls and O bj ects

Me. Close( )
End Sub

Functi on GetLas tName (ByVa l nom As String ) As String


Dim parsed Name( ) As String nom . Split( " "c)
Return parsed Name . Last
End Functi on

4. 'Forml ' s code (startu p form)


Public averag e As Double

Privat e Sub Forml Load( ... ) Handle s MyBas e.Load


Form2 .ShowD ialog()
End Sub

s btnCom puteAv erage. Click


Priva te Sub btnCom puteAv erage_ Click( ... ) Handle
Dim num As Double = 0
Dim count As Intege r = 0
Dim sum As Double = 0
num = CDbl (InputB ox ("Ente r a numbe r"))
Do While num <> -1
count += 1
sum += num
num CDbl( InputB ox("En ter a numbe r"))
Loop
averag e = sum I count
Form3 .ShowD ialog()
Me. Close ()
End Sub

'Form2 's code


Privat e Sub Form2_ Load( .. . ) Handle s MyBas e.Load
m is to" &
Dim messag e As String = "The purpos e of this progra
numbe rs" &
" calcu late the averag e of a set of nonne gative
time" &
" input by the user. Enter the numbe rs one at a
"
" and enter -1 to signal the end of data entry.
Messag eBox.S how(m essage , "Instr uction s")
Me .Close ()
End Sub

'Form3 's code


Privat e Sub Form3 _ Load( . .. ) Handle s MyBas e.Load
ge &
txtAve rage.T ext = "The averag e is " & Forml .avera
End Sub

(Assum e the respon ses are 80, 100, and - 1.)


a econd form appea rs
5. Consid er Examp le 2 of Sectio n 6.1. Alter the program so that
. The second form should allow the
(instead of a messag e box ) when th e button is pressed
with the caption s Movie
use r to make a se lection by clickin g on one of three radio button s
1, Movie 2, and Movie 3.
9.3 Multi ple- Fo rm Programs
• 435

6. Con ider the program in Exa mple 9 from Section 7.1 that determines a pe rson 's first and
last names. A lter the program so that the person's full name is typed into the startup form
and a econd fo rm is used to el i play their first and last names.
7. Consider Exa mple 4 of Section 6.1. A lter the program so that a second form showing the
balance after each year appea rs when th e button is clicked on. See Fig. 9.23.

aj Successive Balances
a.J 6% Interes l= §] ~

Year Amount
Amount Deposited: 1 0 0 S100. 0.00
S106. 0.00
[ Calculate Years to Become a Millionaire J 2 S112.360.
In 40 years you will have a million dollars . 3 511 9.101 60

FIGURE 9.23 Possible outcome of Exercise 7.

8. Conside r the A nalyze-a-Loa n case stud y from C hapter 7. A lter the program so that the
amortization tab le and the interes t-rate-ch ange table are each displayed in a separate fo rm
when requested. The program sh ould have three forms, and the startup form sho uld not
conta in a DataG ridView control.
9. Consider the Recording C hecks and Depos its case study from C hapter 8. A lter the program
so th at the li t of transactions is di splayed in a second fo rm when requ es ted.
10. Write a program that allows stud ent grades on three exams to be entered one tudent at a time
in frmStudent and then displays each student's average and the class average in frmG rades. Ini-
tially, frmG rades (the startup form) should look like Fig. 9.24 with the text box and DataG rid-
View controls empty. The form frmStudent should initially look like Fig. 9.25 with the four
text boxes empty. The Load event procedure of frmG rades should invoke frmStudent.
Each time a student 's name and grades are reco rd ed, the number in the title bar of frm -
Student sho uld increase by 1. The Terminate button should be clicked o n after a ll students
have been recorded. The da ta for the students sho uld be stored in an array of st ructures
with the structure hav ing four members.

a.. Grades a-} Student #1 l= I§] 1~-~J


Display Grades Name: AJ Adams

Exam 1: 75
Oass average : 85.8
Exam 2: 88
Name Average
Exam 3: 89
AJ Adams 84
1: ................ ............. .................... ........TI
Brittany Brooks 80 1: Record Student 1
Carol Cole 92
Donald Davis 87 [ Terminate Ent ering Grades

FIGURE 9.24 frmGrades FIGURE 9.25 frmSt udent


436 • Chapter 9 Addit ional Contro ls and Objects

rma t ion. Th e
11. Write a progra m con sisting of three fo rms tha t ga th ers custome r billi ng info
first fo rm (the sta rtup fo rm) sho uld initia ll y look like Fig. 9.26, but with th e tex t box and
list box blank and no radio butto n se lec ted. (The seco nd a nd third fo rms sh o uld initia lly
a n ame,
look like Figs. 9. 27 and 9.29 with a ll tex t boxes blank .) After th e use r prov ides
th e butto n in fr mC ustome r, e ith e r frmCustl nfo o r
selects a billing me thod, a nd clicks o n
frmCard info sh o uld appea r to o bta in the necessa ry info rmat io n.

Custo er c stall e In o l = I @] l-t:i J


Name: John Public Name : John Public

Billing Method Address : 123 Main Street


Bill Customer Bill Credit Card
Oty: San Francisco

Get Billing Information State : [california ~]

IMail bill to : lip code: 9 1 2


John Public
123 Main Street
Record Data
ISan Francisco. California -=9....:....:.
4 1 ==--

FIGURE 9.26 frmC ustomer FIGURE 9.27 fr mCustln fo

n is
Le t's first consid er frmC ustlnfo, that appears wh en th e Bill Customer rad io butto
lled a utomatic a lly with the n a me that
se lected . The N ame read -only tex t box sh o uld be fi
se lects
was ente red in frmC ustome r. T h e user e nte rs info rma tio n in to the o the r tex t boxes,
d isplay the
a state fro m the sorted dro p-down -list co mbo box , and cl icks o n th e button to
na mes of
ma iling address in the list box of frmC usto me r as sh o wn in Fig. 9.26. Note: The
th e states can be o bta ined from the fi le S tates. tx t.
in frm -
T h e fo rm frmCard l nfo, which appear wh en th e Bill Credit Card radio butto n
(fo type of
r
C usto mer h as bee n se lected , co nta ins two tex t boxes, o n e simp le combo box
it ia lly auto-
cred it card) and two D ropDown List style com bo boxes. The N ame text box is in
in frmC ustomer. H o wever, th e name can be
ma tica lly filled with the na me that was entered

c sto er l = I @] I""'··~ .J
Name on card : John Q. Public
Name: John Public

Billing Method Type of credit card : American Express


Bill Customer 0 Bill Credit Card Amencan ress
MasterCard
VISA.

I Get Billing Information ] Card number: 1111


Bill American Express Good until:
Name on card : John Q. Public
Card number: 111122223.1334444
Expiration date : Apr/2014 Record Data

FIGURE 9.28 frmC ustomer FIGURE 9.29 frmCardl nfo


9.4 Grap hics • 437

altered , if necessary, to look exac tly like the name


printed on the credi t card . The list for th e
Year comb o box should be filled by the Load even
t proce dure and should cont ain the curre nt
year followed by the next five yea rs. (Not e: The
curre nt yea r i give n by Today. Yea r.) Afte r
the user prov ides the reques ted data, the infor
mati on is displ ayed in the list box of frm -
C ustom er as shown in Fig. 9.28.
12. Writ e a program cont aining the two form
s shown in Fig. 9.30. Initia lly, the Num ber to
form appe ars. Whe n the Show Push Buttons butto Dial
n is clicked, the Push Butto ns form appears.
The u er ente rs a numb er by click ing on ucces
sive push butto ns and then click ing on Enter
to have the numb er transferred to the read-only
text box at the botto m of the first form.

umbe r to Dial = a.. Push Bu ons l= l @) l~· l

Show Push Buttons


OJ [I ] [I ]
000
000
~~0 Ent er

FIGURE 9.30 Samp le run of Exerc ise 12.

Soluti ons to Practice Problems 9.3

1. In frmLogin's code, de lete the two lines


Publ ic userN ame As Strin g
anJ
userN ame = txtU serN ame. Text
In frmO rder's code, cha nge the line
txtU serN ame. Text frmL ogin .user Nam e
to

txtU serN ame. Text frmL ogin .txtU serN ame. Text

9.4 Graphics
In this secti on, we draw bar charts and pie ch arts
in a pictu re box, and illustrate one meth od for
crea ting anim ation on a form .
Caut ion: S ince the prog rams in this secti on
mi x text and graph ics, what you see on the
moni tor will vary with the moni tor's DPI settin
g. To guara ntee the intend ed outco mes, you
should chec k that your moni to r is set to displ ay
96 DPI (Dot s Per Inch ). For deta ils, see the first
ite m unde r "Configur ing the Wind ows En viron
ment " in Appe ndix B.

Graphics Objects
Yid eoN ote
A tatem en t of the form
Graph ics
Dim gr As Grap hics = picB ox.C reate Grap hics
decla res gr to be a G raphi cs obj ect for the pictu
re box picBox.
cts
438 • Cha pter 9 Addi tiona l Con trols and Obje

big a
met hods is the pixel. To ge t a feel fo r how
The un it of meas urem ent used in grap hics ls thic k. The
ls high , and the bo rder of a fo rm is four pixe
pixe l is, the title bar of a form is 30 pixe . The two
box is two num bers eparated by a co mma
setti ng fo r the S ize property of a pictu re e num be rs to
pictu re box in pixe ls. You can a lter thes
num bers give the widt h and he ight of the rdin ates
ctur e box is identifi ed by a pa ir of coo
spec ify a prec ise size. Each poi nt of a pi
(x, y)
of the pict ure
is its dista nce in pi xe ls from the left side
whe re x (bet wee n 0 and picBox. Wid th) pictu re box.
is its dista nce in pixe ls from the top of the
box, andy (bet ween 0 and picBox. Heig ht)
men t of the fo rm
Tex t is placed in a pictu re box with a state
Bru shes .Co lor, x, y)
gr.D raw Stri ng( stri ng, Me.F ont,
font be u ed to
literal, Me. Font spec ifies that the Fo rm's
whe re string is eith er a strin g varia ble or dina tes (x, y ).
er of the fir t char acte r of the text has coor
el i play the tex t, and the uppe r-left corn abou t 140 poss ible
The colo r of the tex t i dete rmined by Colo
r. Inte lliSe nse will prov ide a list of
example, the state men ts
colo rs after "Bru shes ." is type d. As an
reat eGr aph ics
Dim gr As Gra phic s = picB ox.C
Dim strV ar As Stri ng = "He llo"
t, Bru shes .Blu e, 4, 30)
gr.D raw Stri ng(s trVa r, Me .Fon
t, Bru shes .Red , 35, 50)
gr.D raw Stri ng( "Wo rld" , Me .Fon

prod uce the outp ut sh own in Fig. 9.3 1.

Hello
World

FIGURE 9.31 Draw Strin g meth od.

Lines, Rectangles, Circles, and Sectors


The n the state men t
Let gr be a G raph ics obj ect for picBox .
yl, x2, y2)
gr.D raw Line (Pen s.Co lor, xl ,
with coat·d i-
t with coor dina tes (xl, yl) to the po int
draws a straight line s gme nt from the poin an ex ten -
rmin ed by Color. lnte lliSe nse will provide
nates (x2, y2 ). The colo r of the line is dete t
i type d. Fo r in rane e, the state men
sive list of poss ible colo rs after "Pen s."
120, 75)
gr . Dra wLi ne(P ens. Blue , 50, 20,
coo rd inate s
coo rdin ates (50, 20 ) to the poin t with the
draws a blu e line from the poin t with the
(1 20, 75 ). See Fig. 9.32.

(50 ~
(120, 75)

FIGURE 9.32 Draw Line meth od.

The state men t


, x, y, w, h)
gr.F illR ecta ngle (Br ush es.C olor
9.4 G raphics • 439

draws a solid rectan gle of width wand height h in the color


specifi ed and h av ing the point with
coord inates (x, y) as its upper-l eft vertex. The left side of the
rectan gle will be x pixe ls from the
left side of the pictur e box and the top side of the rectangle
will b y pixe ls from the top of the
pictur e box. For instan ce, the statement
gr.Fil lRect angle (Brus hes.B lue, 50, 20, 70,
55)
draws the rectan gle shown in Fig. 9.33.

70
[50. 20]

55

FIGURE 9.33 Fii!Re ctangle method .

The FillEllipse metho d draws a solid ellipse of a specifi ed color,


give n the specification s of a
circum scribe d rectan gle. The rectan gle is specifi ed by the coordi
nates of its upper-left point, its
width , and its height . This metho d produc es a circle when the
width and height of the rectan -
gle are th e sa me. In partic ular, the statement
gr.Fi llElli pse(B rushe s.Col or, a - r, b - r, 2 * r, 2 * r)
draws a solid circle of the specifi ed color with center (a, b) and
rad iu T. For instan ce, the tatcme n.t
gr.Fi llElli pse(B rushe s.Blu e, 80 - 40, 50 - 40, 2 * 40, 2 * 40)
draws a solid blue circle with center (80, 50) and radius 40.
Note: If a rectan gle were circum -
scribed about the circle, the rectan gle would be a square with
its upper- left vertex at ( 40, 10)
and each side of length 80.
The FillP ie meth od draws a solid ec tor of an ellipse in a co
lor. The ellipse is specified by
giving the coord inates, width , and heigh t fo r the circum sc
ribing rec tangle, as in the FillEl-
lipse metho d. The ecto r is determ ined by a radiu s line and
the angle swe pt out by the radiu s
line. We are intere ted solely in the case where the ellipse
is a circle . The shaded region in
Fig. 9.34 is a typ ical sector (or pie-sh aped region ) of a circle.
The sector is determ ined by the
two angles 81 and 82. The start angle, 8 , is the angle throug
1 h which the horizo ntal radius
line must be rotated clockwise to reach the startin g radiu s
line of the secto r. Angle 82 is the
n umbe r of degrees through which the startin g radius line
must sweep (clockwise ) to reach
th e endin g radiu s line of the sec tor. The angles 8 and 8
1 2 are referre d to as the start angle
and the sweep angle, respec ti ve ly. Figure 9.35 on the nex
t page shows the start and sweep
angles fo r three secto rs of a c ircle.

;...<---,------1 ...__ Horizonta I


rad ius line

FIGURE 9.34 A typical sector of a circle.


440 • Chap ter 9 Additional Contr ols and Objec ts

start angle =45 start angle =0


start angle = 135
sweep angle = 180 sweep angle =31 5
sweep angle =90

FIGURE 9.35 Fii!Pie method.

In ge neral, a state ment of the form


- r, 2 * r , 2 * r ,
g r. Fill Pie (Bru shes. Colo r , a - r, b
s tartA ngle , swee pAng le)

cente r (a, b) , radius r , and the given start


draws a secto r of a circle of the spec ified color with
of Fig. 9.3 5 can be d rawn with a state ment
and sweep angles. For instan ce, the midd le image
such as
80 - 40, 2 * 40, 2 * 40, 45, 180)
g r . Fi ll P i e(Br ushe s.Blu e, 80 - 40,
draw ing state ments so far are litera ls of
The Brush es, Pens, and Fo nts appea ring in the
values . For instan ce, the state ment gr.Fill-
obj ects. Variab les also ca n be used to provide these
ced by the pair of statem ents
Recta ngle (Bru h es.Blu e, 50, 20, 70, 55) can be repla
Dim b rAs Bru sh = Brus hes.B lu e
gr . Fil lRe ctan gle(b r , 50, 20 , 7 0, 55)
ble of type Brush and ass igns it the va lue
The first state ment decla res br to be a varia
Brush es. Blue.
ents discussed in th is sectio n must be of
Nu meric va riables used in the Draw and Fill statem
ilar to the Doub le data type but has a sma ller
type Intege r or S ingle . T he Single data type is sim
ers, fract ions, o r mixe d numb ers between
range . A varia ble of type S ingle can hold whole numb
38 ion conv erts other data types to the S ingle
abou t -3 .4 · 10 and 3.4 · 10 . T he C Sng funct
38

data type.

Pie Charts
chart can be used to graph ically display the
Cons ider the three pieces of data in Table 9.3. A pie
ing a pie ch art is to convert the numbe rs to
re lat ive size of these nu mbers. The first step in creat
bill ion , the federal outla y is 33/41 9 ~ .08 or
pe rcents. Since the total expend itu res are $419
49% and 43%. ee Table 9.4. O ur goa l is to
8%. S imila rly, the state and local expen ditures are
pie ch art of Fig. 9.36 .
write a program to d isplay the inform ation in the

IM:J!fiM Financing for public schools (in billions).


Federa l $33
State $206
Local $180

lt4=J!fJM Financing for public schools.


Federal .08 or 8%
State .49 or 49%
Local .43 or 43%
9.4 G rap h ics • 441

a" ina ncing for Pub lic Sch ools (K - 12)

•• Feaeral

State

Loca l

Display Pie Chart

FIGURE 9.36 P ie chart fo r Exam ple 1.

The blue sector in Fig. 9.36 ha start angle 0 degrees and


sweep angle .08 * 360 degrees . The
red sector ha start angle .08 * 360 and sweep ang le .49
* 360. The tan sector has ta rt angle
.08 * 360 + .49 * 360 [or ( .08 + .49) * 360 degrees]
and sweep angle .43 * 360° degrees.
Notic e that each start angle is ( urn of prev ious perce
ntages) * 360. T he sweep angle for each
sector is the corres pondi ng percentage times 360.

Example 1 The follow ing progra m creates the pie chart (see Fig. 9.36)
for the financ ing
of public schoo ls. The program is writte n so that it can
be eas ily con verted to hand le a pie chart
with up to six sectors. A ll that is requ ired is to chang
e the first two Dim statements and the
Me .Tex t statem ent. T he "Dim br() As Brush " line, which
creates an array of brush es, has six
brush es in order to acco mmod ate add itiona l secto rs.

Priva te Sub btnD ispla y _ Cl ick( . .. ) Hand


les btnD ispla y . Click
Dim legen d() As Strin g = { "Fede ral" , "Stat
e" , "Loca l" }
Dim quan tity( ) As Singl e = { 3 3, 206, 180}
Dim perce nt(qu antity .Coun t - 1) As Singl
e
Dim sumO fQuan t i ti e s As Singl e = 0
Dim sumO fSwee pAngl es As Singl e = 0
Dim br () As Brush = {Brus hes .Blue , Brush
es .Red, Brush es .Tan,
Brush es .Gree n , Brush es . Orang e, Brush es
. Gray}
Dim gr As Grap hics = picO utput . Creat eGra
phics
'The pictu re box has w~dth 312 and heigh
t 215
Dim r As I ntege r = 100 'Radi us of circl e
Dim c As Integ er = 105 'Cent er of circl e has coord inate s (c,
c)
Me . Text = "Fina ncing for Publi c Scho ols
(K- 12)"
•sum the numb ers for the quan tities
For i As Integ er = 0 To quan tity. Coun
t - 1
sumO fQua ntitie s += quan tity(i )
Next
442 • Chap ter 9 Additional Cont ro ls and Objects

Con ert the quan titie s to perc ents


- 1
For i As Integ er = 0 To quan tity.C ount
) = quan tity( i) I sumO fQua ntitie s
pe rcen t( i
Next
ds
'Disp lay the pie char t and the legen
= 0 To quan tity.C ount - 1
For i As Integ er
i), c - r, c - r, 2 * r , 2 * r,
gr .Fi llPie (br(
sumO fSwe epAn gles, perc ent(i ) * 360)
sumO f Swee pAng les += perc ent(i ) * 360
d
'Disp lay smal l colo red squa re and legen
gr .Fi llRe ctan gle(b r(i) , 2 20, 20 + 30 * i, 20, 20)
Me .Fon t, Brus hes .Blac k, 250, 22 + 30 * i)
g r. Dr awS tring (lege nd(i) ,
Next
End Sub

Bar Charts
7. The picture box for the chart has a width
O ur goal here is to prod uce the bar chart of Fig. 9.3
rStyle prope rty is set to Fixed S ingle for
of 210 and heigh t of 150 pixe ls. (Here, the Borde
look bette r with the Borde rStyle prope rty of
instru ction al reaso ns. In general, the bar chart will
the pictu re box left at its defau lt sett ing: N one. )

a:) Financing for Public Schools (K - 12)

100

Federa l State Local


(Expenditures i billions)

Display Bar Chart

FIGURE 9.37 Bar chart for Exam ple 2.

and 180. If we let a pixe l corre spon d to


The three magn itude s for the graph are 33 , 206,
ls high -a bit too large. With a pixe l cor-
one unit, then the largest recta ngle wi ll be 206 pixe
be 206/2 or 103 pixel s high -a reaso nable
respo nd ing to 2 un its, the larges t recta ngle will
of the pictu re box, the larges t recta ngle is
size . By se tting the x-axi s 110 pixe ls from the top
larges t rec tangle is 110 - 103 [that is,
acco mmo dated co mfort ably. The top of the
In ge neral, a recta ngle co rresp ond ing
11 0 - (206/ 2 )] pixels from the top of the pictu re box.
the top of the pictu re box , and the heigh t
to the quan tity q wi ll be 110 - (q/2 ) pixels from
will be q /2 pixe ls.
9.4 Graphi cs • 443

Example 2 The fo llow ing program prod uces the bar ch art of Fig. 9.3 7. Each rectan gle is
20 p ixels w id e, and th e re are 20 pixels be twee n recta ngles.

Private Sub btnDisplay_ Click( ... ) Handles btnDisplay.C lick


Dim quantity() As Single = {33, 206, 180}
Dim gr As Graphics = picOutput.Cr eateGraphics
The p' ture box hati w h 210 and heigh 150
gr.DrawLine( Pens . Black, 40, 110, 210, 110) x axis
gr.DrawLine( Pens .Black, 40, 110, 40, 0) 'y-axis
gr.DrawLine( Pens .Black, 35, 60, 4 5, 60) ' i ~ I:' ·~ 60 110 - (10012)
gr.DrawStrin g( "$100" , Me .Font, Brushes .Black, 5, 55)
Me . Text = "Financing for Public Schools (K- 12)"
For i As Integer = 0 To quantity.Cou nt - 1
gr . FillRectangl e( Brushes .Blue, 60 + i * 40,
(110- quantity(i) I 2), 20, quantity(i) I 2)
Next
gr.DrawStrin g( "Federal State Local" , Me .Font,
Brushes .Black, 50, 115)
gr.DrawStrin g( "(Expenditur es in billions)" , Me .Font,
Brushes .Black, 50, 130)
End Sub

• Animation
One way to produce animation on a form is to place an image in to a p ictu re box and then move
the p icture by steadi ly ch a ng ing t h e location of the picture box. Figure 9.38 sh ows a ba ll placed
inside a sma ll p icture box .

Example 3 In the fo llowing program , the ba ll in Fig. 9.38 will initia lly move diagon a ll y
in a sou thea t direction and the n bo unce off a n y side of the fo rm it h its. The client area of a for m
is th e gray area within the ti tle bar and borders of th e form. The va lues of M e .C lie ntS ize. H igh t
and Me. lient ize. Wi dth are t he he ight and width of the white area. The v lues of p icB x. Top
and picBox.Left are the distances of the pic ture box from the top and left sid es of the clie nt a rea .

OBJECT PROPERTY SETTING


- Bouncing Ball
a
~I G I[];B fr mBa ll Text Bounc ing
Ba ll
Back o lor White
pic Ba ll Image Moon5.bmp
Timerl Interva l 10

FIGURE 9.38 T h e fo rm for Example 3.


444 • Chapter 9 Additiona l Con trols and Objects

The speed at which the ba ll move is determined by the setting for the Interva l property of
Timerl . At each t ick, the ball will move x pixe ls hori zontally, where x = 1 o r - 1. When x = 1
the ball moves to the righ t, and wh en x = - 1 the ball moves to the left . The va lue of x reve r es
when the ball strikes the right o r left side of the form. The value of y determines the verti cal
motion of the ball in a similar manner,
Dim x As Integer 1
Dim y As Integer 1

Private Sub frmBall _ Load(o o o) Handles MyBase oLoad


TimerloE nabled = True
End Sub

Private Sub Timerl_ Tick( o o o) Handles TimerloT ick


If picBallo Left <= 0 Or
picBallo Left >= (Me oClientS iz eoWidth - picBalloW idth) Then
x = -x
End If
picBallo Left += x
If picBalloT op <= 0 Or
picBalloT op >= (Me oCli entSizeoH eight - picBalloH eight) Then
y = -y
End If
picBalloT op += y
End Sub

Printing Graphics
Graphics can be printed with a PrintDocument control in the sa me way that tex t was printed
in Section 3 .3.

Example 4 The follow ing program produces the same o utput as Exa mple 2. H oweve r,
the output is printed instead of being displayed in a picture box. The changes from Example 2
are as fo llows:

10 The code was moved fro m the btnDisplay _C lick event procedure to the procedure Print-
Docume ntl_PrintP age.
20 The source of the graphics object gr was changed fro m picOutput . C rea teGraphics to
e. G raphics.
30 The Me.Tex t statement wa replaced with a DrawS tring statement .
40 The values of the x-coo rd inates were increased by 300 to approx imate ly center the graph
horizontally, and the va lues of the y-coordina tes were increased by 200 to lower the graph
from the top edge of the page.
9.4 G raphic • 445

OBJECT PROPERTY SETTING


~:~ :; Bar Chart ~[}[] ~ frmBarC hart Text Bar C h art
btnPrint Text Print Bar hart
Print Bar 01art ] brnPrev iew Tex t Prev iew Bar C hart
PrintOocum entl
Preview Bar Chart
PrintPrev iewOialog l
]

L6J Prin Doc umen:l


Private Sub btnPrint Click( ... ) Handles btnPrint .Click
PrintDoc ument1.P rint()
End Sub

Private Sub PrintDocu ment1_ PrintPag e( ... ) Handles PrintDoc umentl.P rintPage
Dim quantity () As Single = {33, 207, 180}
Dim gr As Graphics = e.Graphi cs
gr . DrawLine ( Pens .Black, 340, 310, 510, 310 ) 'x-axis
gr . DrawLine ( Pens .Black, 340, 310, 340, 200) 'y-axis
gr . DrawLine ( Pens .Black, 335, 260, 345, 260) tick marie
gr . DrawStri ng( "$100" , Me .Font, Brushes .B1ack, 305, 255)
gr.DrawS tring( "Financin g for Public Schools ( K - 12)" , Me .Font,
Brushes . B1ack, 300, 175)
For i As Integer = 0 To quantity. Count - 1
gr.Fi11R ectang1e ( Brushes .B1ue, 360 + i * 40,
(310 - quantity (i) I 2), 20, quantity (i) I 2)
Next
gr . DrawStri ng( "Federal State Local" , Me .Font,
Brushes .B1ack, 350, 315)
gr.DrawS tring( "(Expend itures in billions )" , Me .Font,
Brushes . B1ack, 350, 330)
End Sub

Private Sub btnPrevie w_ C1ick( ... ) Handles btnPrevie w.Click


PrintPrev iewDialo gl.Docum ent = PrintDocu ment1
PrintPrev iewDia1o g1.ShowD ialog()
End Sub

Comments
1. A statement of the form
Dim pn As Pen = Pens.Col or

declares pn to be a variab le of type Pen and ass igns it the value Pens. Color.
2. A statement of the form
Dim fnt As Font = New Font(font Narne, size)

declares fnt to be a variable of type Font and ass igns it th specified font and size. For
instance, the statements
446 • Chapter 9 Add itional Controls and Objects

Dim gr As Graph ics = picBo x.Crea teGrap hics


Dim fnt As Font = New Font ( "Cour ier New" , 10)
gr.Dra wStrin g( "Hello " , fnt, Brushe s .Blue, 4, 30)

display the word Hello in 10-po int Courie r N ew font.


3. The statement
picBox .Re fresh( )

clears all graphics and tex t from the picture box.

Practice Problems 9.4


use colored Brushes.
1. (True or False) The Draw and Fill method s discussed in this section
of the form. Note: The
2. Write lines of code that place a smi ling face in the upper left co rner
letter] corresponds to a smiling face in the Wingd ings font.

EXERCISES 9.4

in a picture box.
In Exerci ses 1 throug h 4, write a progra m to draw the given figures
1. Draw a circle whose center is loca ted at the center of a picture box.
2. Draw a circle whose leftm ost point is at the center of a picture box.
20.
3. Use the FillEllipse method to crea te an unfilled red circle of radius
4. Draw a triangle with two sides of the same length.
In Exerci ses 5 throug h 18 display the graphic s in a picture box.
design ated countr y. Refer
In Exerci ses 5 throug h 8, write a progra m to create the flag of the
flags, the width is 1.5 times
to Fig. 9.39. Note: The Swiss flag is square . For the other three
the height.

Italy Switzerland Niger Greenland

FIGURE 9.39 Flags of four countri es.

5. italy 6. Switze rland 7. Niger 8. Greenl and


the user specify the max-
9. Write a program to draw disp lays such as the one in Fig. 9.40. Let
imum numbe r (in this display, 8).

0 2 3 4 5 6 7 8

FIGURE 9.40 Drawin g for Exercis e 9.


9.4 Graph ics
• 447

10. Write a program to draw d isplays such as


the one in Fig. 9.41. Let the user specify the num-
ber of lines (in th is display, 3 ).

- - - - - Line1
- - - - - Line2
- - - - - Line3

FIGURE 9.41 Draw ing for Exerc ise 10.

11. U se the data in Table 9.5 to creat e a pie chart


.

lfi':UJiJW United States recreational beverage consumption.


Soft Drinks 52.9%
Beer 14.7%
Bottled Wate r 11.1 %
O ther 21.3%

12. Use the data in Table 9.6 to creat e a bar chart.

lt!1:JIQW United States minimum wage.


1959 1.00
1968 1.15
1978 2.65
1988 3.35
1998 5.15
2009 7.25

13. Write a program to creat e the line chart in


Fig. 9.42. Use the data in Table 9.7.

1 .

2008
Percentage of College Fres men \~lho Smoke
Source: Higher Eaucatio Researc Institute

FIGURE 9.42 Line chart for Exerc ise 13.

lf!1:JIJjiM Percentage of College Freshmen Who Smoke.


1996 1998 2000 2002 2004 2006 2008
Perce nt 11.6 12.7 10.0 7.4 6.4 5.3 4.4
Source: Highe r Educati on Research Institute.
ects
448 • Chap ter 9 Add itio nal Con trols and Obj

t in Fig. 9.43 . Use the data in Tab le 9.8


14. Wri te a program to crea te the line char

females
3358

1960 1970 1980 1990 2000


Tvio- Year College Errollrre ts
(i trous ar ds)

FIGURE 9.43 Line char t for Exer cise 14.

s).
IM:Jip:M Two-year college enrollments {in thousand
1980 1990 2000
1960 1970
2047 2233 2398
Male 283 1375
2479 3007 3358
Female 170 945

t in Fig. 9.44.
15. Wri te a program to crea te the bar char

5. <.•

Biology Psychology Precfent Bus . Arlrr in.


Nursing
Prerr.eo (general)
(ge era I)
Prevet
ir Fall 2008.
Most Popular Majors for College Fres rr.e

FIGURE 9.44 Bar char t for Exer c ise 15.

t in Fig. 9.45. Use the data in Tab le 9.9.


16. Wri te a prog ram to crea te th e bar char

Fres n a
(% of stu ents con n ·tteu to goal)

• Be very well off fi a ~i - lly


• Deve lop a rr ea i ful ph.ilosoph :o,• of Iif a

FIGURE 9.45 Bar char t for Exer cise 16.


9.4 G raphic • 449

lf!1:J!IIJI Freshman Life Goals (% of students committed to goal).


1978 1988 1998 2008
Be very well off financially 59 74 73 77
D evelop a meaningful philosophy of life 60 43 44 51
Source : Higher Education Research Institute.

17. W rite a program to create the bar chart in Figure 9.46. U se the data in Table 9. 10. Note:
Mand arin and Wu are spoken primarily in C hina.

882

Principal La11guages of tt->e Worl d


(in millions of first Ia guage speakers)

FIGURE 9.46 Bar chart for Exercise 17.

lf!1:J!Qiel Principal languages of the world.


Be nga li 173
Engli h 3 11
German 96
Hindi 182
Japa nese 128
Ma ndarin 882
Portuguese 179
Russ ian 146
Spa nish 326
Wu 78

18. Write a program that allows th e use r to display a budget as a pie chart. See Fig. 9.47 on the
next page. After the u er enters numbers into the four tex t boxes and click on the button ,
the pie chart should be displayed.
19. Wri te a program in which an airplane fli es horizo ntally to the right across a form. After it
flies off the form, the airplane should reappear on the left and fly horizontally across the
screen aga in. Note: Use the image Airplane.bmp found in the folder C h09 \Picture .
20. Rewrite the program in Exa mple 1 so that the pie chart is prin ted instead of being di played
in a picture box . Note: You will mos t likely want to replace the variabl e with the pair of
vari ables ex and ey. Then the center of the circle will have coord inates (ex, ey ).
21. Refer to Exe rcise 5. Write a program to print the flag of Italy.

22 . Refer to Exe rcise 7. Write a program to print the fl ag of N iger.


450 • Chap ter 9 Addit ional Control and Objec ts

D~ Bud get

Housing : 9100 Food : 37 Display


Chart
Transportation : 5 Other: 55

• H us ing

• TraBSportati o

. Food
Other

FIGURE 9.47 Form for Exerc ise 18.

Solutions to Practice Problems 9.4


d uses
metho d use colored Brushes . The DrawLine metho
1. False. On ly the Fi ll methods and the DrawS tring
co lored Pens.
2. Dim gr As Grap hics = Me.C reate Grap hics
gs", 20)
Dim fnt As Font = New Font ("Wi ngdin
fnt, Brus hes.R ed, 0, 0)
gr.D rawS tring ("J",

CHAPTER 9 SUMMARY
() holds the items stored in the list box.
1. List boxes provide ea y access to lists of data. Items
lists can be automatically sorted (Sorted
Each item is identified by an index numbe r. The
ltems.RemoveA t, and ltems.Remove
property = True ) and altered (Items.Add ltem,
(Text property), and the numb er of
meth ods), the curre ntly highl ighted item iden tified
items deter mine d (Item s.Cou nt property).
nced text boxes. They allow the user to
2. Simp le and Drop Oown style combo boxes are enha
by typing the item directly into the text
fi ll the text box by se lecting an item from a list or
the comb o box's Text prope rty. A Orop-
box. The conte nts of the text box are ass igned to
that drops dow n instead of being penn a-
DownList style co mbo box is essen tially a list box
nentl y displayed.
a specified time interv al.
3. The timer contro l ra ises an even t repea tedly after
mly selec ted integ e r from a pecified range.
4. An objec t of type Rando m can ge nerat e a rando
guida nce when the mou e hovers over a
5. The ToolTip control allows the program to d isplay
contr ol.
or by pressi ng C trl + C, and its conte nt
6. The Clipboard i filled with the SetText meth od
C trl + V.
are cop ied with the GetTex t meth od or by pressing
Progr ammi ng Projec ts
• 451

7. The picture box contro l, whic h disp lay pictu res or


geom etric shapes, can expand to accom-
moda te the size of a pictu re or have a pictu re alter it size
to fit the contr ol.
8. Menu s, simil ar to t he menu s of the Visua l
Bas ic IDE itse lf, ca n be crea ted with the
MenuStrip contr ol.
9. Horizontal and vertical scroll bar controls perm
it the user to selec t from amon g a range of inte-
ger by click ing or dragg ing with the mouse. The range
is deter mined by the Mini mum and
Maxi mum prope rties. The cro ll even t is ra ised by
click ing on the scroll bar.
10. Addi tion al forms ca n be added to a program
to erve as custo mized dia log boxes . They ar
revea led with the ShowDialog meth od and remo ved
with the C lose meth od .
11. After a graph ics obj ct is produ ced with a
Crea teGra phics meth od , the DrawString, Draw -
Line, FillRectangle, FillElli/Jse, and FillPi e meth o l
can be used to display strings, lines, solid
rectan gles, solid elli pses, and solid secto rs with color
s supplied by Pen and Brush obj ects.
12. Animation can be produ ced by stead ily mov
ing a pictu re box conta ining an image .

CHAPTER 9 PROGRAMMING PROJECTS


1. Membership List. Write a menu -driv en progr
am to manage a mem bersh ip list. See Fig. 9.48.
Assu me that t he name s and phon e numb er of all mem
bers are sto red in alpha betic al ord er
(by last n ame, then by first name ) in the text file
MemberPh ones. txt. Each reco rd consists
of two fie lds-a name fie ld and a phon e numb er
fie ld . The names should appea r in a list
box when the form is loade d . Whe n a name is highl
ighte d , bo th the name and phon e num-
ber of the perso n should appea r in the tex t boxes
at the bo ttom of the fo rm. To delet e a per-
son, high light his o r h er name and click on the
Delete menu item. To chan ge e ither a
perso n 's name o r phon e numb er, make the co rrecti
ons in the text boxes and click on the
menu item Modify. To add a new mem ber, type his
or her name and phon e numb er into the
text boxes and click on the menu item Add. Whe
n the Exit menu item is click ed, the new
mem bersh ip list sho uld be writte n to the fil e and
the progr am should termi nate.

II:;' 1em bers ip ·st l = I @] 1.-tJ ·l


Up date I Exit
~ 1odify Fl
Add F2
Delete F3
-
Alice Ree
Carlos Sanchez
John Smith

Name: Judj• L.angle'l

Phone: Jl1-1 111

FIGURE 9.48 Form for Progr ammi ng Proje ct 1.

2. Inventory Control. Write a menu -driv en multi form


inven tory program for a bookstore with
data aved in a text file. Each record of the text
file should consist of fi ve fie lds- title,
author, category, wholesale price, and number in stock.
(The two catego ries are fiction and
452 • Chap ter 9 Add ition al Contro ls and Objects

list
displ ay the titles of the books in stoc k in a
nonfiction .) A t any time, the prog ram should or just those in one of
layin g eithe r all t itles
box. T he user should have the op tion of disp or alter any
to add a new book , dele te a book,
the two categories. The use r should be able ,
ng and editi ng processes use the econ d form
of the fields of a book in stoc k. The addi lue
user should be able to calculate the to tal va
frmDeta ils. See Fig. 9.49. At any time, the u item File cont ains
in eithe r catego ry. The men
of all books, or the total va lue of the boo ks
the two seco nd -leve l menu items Save and
Exit. The menu items Display and Valu es each
the
s All, Ficti on, and Nonfiction. (Hin t: tore
cont ain the three seco nd -leve l menu item
.)
data abou t the books in an array of struc tures

ll Book Inventory l=l@) ~ J D::J De ails

f il e ~ook J Qi!>play Yalues,


-- Trtle: Into the Wild
~dd Ctri +A
Ctrl + D Author: Krakauer
I• Qelet e

p !J.pd at e Ctri +U Price: S11 .25


Stock :
l he oae1
The Audacity of Hope Category
Nudge
Into the l/1,/ild Rction o Nonfiction
Hany Potter and the Deathly Hallows
Outliers : The Story of Success
The Time Traveler's Wife
Record Details
Olive ~ eridg e

2.
FIGURE 9.49 The two forms for Prog ramm ing Proje ct

use in
bring a co mpu ter to their annu al mee ting to
3. Voting Mac hine. The members of a club prog ram
program to hand le the elect ion . The
the elect ion of a new president . Writ e a on
he or he is nom inated. Afte r the nom inati
shou ld add each candid ate to a li t box a
able to approach the co mpu ter one at a t ime
process is complete, club members should be on ,
choice. Whe n a Tally Vo tes butt on is clicked
and doub le-click on the ca ndid ate of their shou ld appe ar
s rece ived by each candid ate,
a seco nd list box, ha wing the num ber of vote t num ber
of the candidate (s) with the high e
alongs ide the first list box . A lso, the name(s)
of votes should be disp layed in a list box.
seats
15 rows (num bered 1 thro ugh 15), with six
4. Airplane Seating Chart. An airplane has that keep s track of
Write a mult iform prog ram
(labe led A, B, C, D, E, and F) in each row. nger . The
type of mea l requ ested by each passe
the seats that have been reserved and the
with a line for each row. See Fig. 9.50 (a) .
eating char t should be displ ayed in a list box
row in the list box, the row num ber and the
Whe n the ticke t agen t clicks on the desired
ayed in seve n read -onl y text boxes at the bot-
status of the seats in the row should be displ
one of the text boxes, a seco nd form con ta ining
tom of the form . Whe n the agen t clicks on r.
lar, Low Calorie, and Vege tarian should appea
fou r optio n butto ns labeled Unoccupied, Regu both
n should close the seco nd form and upda te
See Fig. 9.50 (b) . C licki ng on a radio butto ied seats are deno ted with a
list box. Unoccup
the text box and the row for that seat in the . At an y time ,
the first lette r of their mea l type
period , and occupied eat are deno ted with
ber of seats fi lled, the num ber of window seats
the agen t should be able to requ est the num
l ord ered .
vaca nt, and the num bers of each type of mea
Progra mmin g Projec ts
• 453

"~ Airplane Seating Chart

ABC DE F
R. V R.:.JL
R. R .- .
-'
R. L • : : .,R
C D1splcrj Statistics
RR:Z.,
RV.
VRR
RRR
RRL :Z., .R
Seac a : illed : 62
Kindow s avail : 6 RRR . RR
o . Assign seat SA l = I @) l;....iJ ~~
Regula r ~e al s: 43 •• R •• R
Lo-w·Cal me als: 14 It Unoccupied
' egie me als: S ::::.,R . L . R Regular

R •• • • R
Low Calorie Vegetari an
RRR ::::.,RR
. ::::.,R RRR
RRL .v . (b)
•• R
. LR VRR
A B c D E F
8 R R

(a)

FIGURE 9.50 Forms for Progra mmin g Projec t 4.

5. The Underdog and the World Series. What is the proba


bility that the und erdog will win the
Wo rld Series of Baseball ? What is the average numb er of games
fo r a World Series? Write an
anima ted progra m to answe r these questi o ns. Fo r instan
ce, suppose that the und erd og is
expec ted to win 40% of the time. We say that the proba
bility of the underdog's winni ng a
game is 40%. (In ord er fo r a team to be the underd og,
the proba bi lity that the tea m wins a
game must be less than 50%. ) Figure 9.51 shows that
the proba bility of a 40% und erdog's
winni ng the Wo rld Series is about 29%, and that such
a series wo uld last an ave rage of abo ut
5.6 7 games . The progra m should simul ate the play ing
of 10,00 0 W orld Series where the
underdog has the proba bility of winni ng that was entere
d into the first text box. The va lu es
of the h orizon ta l scroll bars sho uld exten d from 0 to
10,000 and should be calcu lated after
each series o that the scro ll boxes steadily move across
the bars. Note: In ord er to spare
Visua l Bas ic from be ing ove rwhelmed with chang ing
the values in the twe lve text boxes to
the right of the scroll bar too often , just change the va
lues after eve ry ten series. A lso, every
time the va lues are changed, execu te a Refres h metho
d for each of these tex t boxes.
6. SjJread of an Epidemic. A comm unity of 10,00 0 indivi
duals is ex posed to a flu epide mic in
which infect ed indiv idua l are sick for two days and
then are immu n fro m the illne s.
When we first start to obse rve the epide mic (that is, on
day 0) , 200 peopl e have had the ill-
ness fo r one day, and 100 peop le have had th e illness
for two days. At any tim e, the rate at
which the ep id emic is pread ing i propo rtio na l to the
produ ct of the numb er curren tly ill
and the numb er suscep tible. Specifically, each day

[#of indi vidu a ls in the first day of the illness]


C lnt (0.00 01735 * [#s ick the prev ious day] * [# suscep
tible the prev ious day])
454 • Chap ter 9 A ddit ional Cont ro ls and Objects

l = I@J I. ~.
a~ e U derde>g and he Worl d Series

Probab 1lity of underdog


•Ninning a game :
.,
'• I Simulate Outcomes of 10.000 World Series
J

WIN NER
2900 29.00~~
Underdog : (

7100 71.00%
Favorite :

DUR AT.ION OF WOR LD SER IES


1591 15.91%
Four games :
27 27.60%
Rve games : ~

2963 29.63%
Six. games : ~

26&6 26.86"4
Seven games:

Avera ge duration of 'Nond series: 5.67 games

FIGURE 9.51 A sample run of Prog ramm ing Proje ct 5.

grap hs illust ratin g the prog ress of the epi -


Writ e a prog ram that d isplays succ ess ive bar ibu-
ed on, the bar grap h should show the distr
demic. Whe n the Show Day 0 butto n is click ed o n, a ba r
A dvan ce One Day butto n is click
tion fo r day 0. Se Fig. 9.5 2. Each time the bar
t day should appear. Figure 9.53 shows the
grap h show ing the distr ibuti on for the nex
three times.
grap h after this butto n has been clicked on

ll ... Sprea d of a n Epide mic.

Day O

Sick 1 Day Sick 2 Days lrrrr u e


Susceptible

Show Day O Advance One Day

FIGURE 9.52 Initia l distr ibuti on of epide mic.


Progra mmin g Projec ts
• 45 5

a~ Sprea d of a n Epidem ic

Day 3

Susceptible

Show DayO Advance One Day

FIGURE 9.53 D istribu tion o n day 3 of epide mic.


Da tab ase s

10.1 An Introduction to Databases 458


• Accessing a Data ba e Table • Bind ing to Add itiona
l Tables • Browsing a Conn ected
Database • Querying a Table with LINQ • Primary and
Foreign Keys • The Join of
Two Table s
10.2 Editing and Designing Databases 479
• A Program to Edit the Citie s Table • Designing the
Form for the Table-Ed iting
Program • Writi ng the Table-Editing Program • Princ
iples of Database Design
Summary 486

Programming Projects 487

457
458 • Cha pter 10 Databases

10.1 An Introduction to Databases


rs today. A irlines
man agem ent of data base s is one of the mos t imp orta nt uses of com pute
VideoNote The 0 hosp itals in
passenger rese rvat ions per year. The 7,50
lntro Jucti on to use databases to han d le nea rly 1.5 bi llion pati ents pe r year.
doc ume nt the care of ove r 30 mi llion
J atabases the Uni ted Stat es utili ze databases to it ca rds. A ltho ugh
databases to mon itor 1.6 billion cred
Banks in the U nite d Stat es employ the fund ame ntal
complex ity, mos t of them adh ere to
databases vary cons iderab ly in size and ecti on of inter-
ter. Tha t is, they are co mposed of a coll
principles of design discussed in this chap
related tab les. ut la rge cities.
. Tab le 10.1 prov ides info rma t ion abo
A tabl e is a rect ang ular array of data 0 pop ulation in mil-
. (Th e third colu mn gives the 201
Eac h colu mn of the tab le is called a field The nam es of the
ected 2015 popu latio n in millions.)
lions and the four th colu mn the proj ntai ns the same
pop2015. Each row, call ed a reco rd, co
fields are name, country, fJop2010, and row are rela ted
of info rma tio n as eve ry othe r row. A lso, the piece of info rma t ion in each
type and ten records.
Tab le 10.2, Cou ntries, has thre e fie ld
because they all app ly to a spec ific city.

I'U:J!II•II Cities.
pop2 010 pop2 015
nam e coun try
20.1 22.0
Bombay Indi a
13 .1 13.4
Buenos A ires Arge ntin a
15.6 17.0
Calc utta India
17.0 18.7
Delh i Ind ia
14.8 17.0
Dha ka Bangladesh
19.5 20.2
Mex ico C ity Mexico
19.4 20.0
New York USA
19.6 20.1
Sao Pa ulo Braz il
15.8 17. 2
Shan gha i Chin a
36. 1 36.4
Tokyo Japa n
us densely popu lated
an agglome ratio ns" -tha t is, cont iguo
Note : The popu latio n figures are for "urb
urba n areas.

lfi':J!II•IJ Countries.
mon etar y Uni t
nam e pop2 010
41.9 peso
Arge ntin a
152.6 raka
Bangladesh rea l
195 .2
Brazil yuan
Chin a 1379.7
1196.8 rupee
Indi a rupi ah
Indo nesi a
258.5
129.0 yen
Japa n peso
Mex ico 117.4
184.2 rupee
Paki stan dolla r
USA
3 10.1

tab les that


ecti on of one or mor e (usually rela ted)
A rela tion al data base con ta ins a coll one of the best
eme n t softw are. Mic roso ft Access is
has been crea ted with data base -ma nag cle, SQL Server,
. Som e othe r prom inen t one s are Ora
kno wn data base -ma nag eme nt products
10.1 A n Introdu ction to Databases
• 459

and MySQL. VB 20 10 can in te ract with a database that has been


created with an y of these
produ cts.
The databases needed for the exercises in this tex tboo k are contai
ned in the materi als
downloaded from the compa nion website. They are in the folder
Progra ms \ C hlO \ Databases.
The database files we re created wi th Microsoft A ccess 2007 and have
the ex tension accdb (an
abbrev iation for ACCes s DataBase ). For instance, Megac ities.ac
cdb is the database file co n-
taining the two tab les prese nted above. When the tables were created
, each field was given a
name and a data type. In the C ities table, the fields jJOjJ20 10 and pop20
15 were given data type
Double and the other fields a data type compa tible with the Str ing
data type.

Accessing a Database Table


Before a progra m can access a table fro m a database, a connec tion
must be establi shed. The fol-
low ing steps prov ide one way to connec t to the Megac ities databa
se and bind to the C ities
table.

1. S tart a new progra m.


2. Add a BindingSource contro l to the Form Design er. (The Bindin
gSource co ntrol can be
found in the A ll Windows Forms or Data groups of the Toolbox. ) After
you double-click on
the co ntro l in the Toolbox, a contro l named Bindin gSource l appear
s in the compo nent
tray at the bottom of the Form Design er.
3. Go to the Properties window for Bindin gSource l and click
on the down-a rrow at the right
side of the DataSo urce property's Settings box. The panel in Fig. 10.1
appea rs.

Non e

click here

I
Add Project Data Source ...
Click the 'Add Project Data Source.. .' li nk t o
conn ect to data .

FIGURE 10.1 Panel produce d by Step 3.

4. C lick on Add Project Data Source. The Data Source Config


urat ion W iza rd in Fig. 10. 2 on
the nex t page appea rs and asks you to "C hoose a Data Source Type".
5. Select the Database ico n in the Data Source Configuration Wiza
rd and click on the N ext
button . The Wizard now asks yo u to "Choose a Database Model".
6. Se lect the Datase t icon and click on the N ext button . The Wizard
now as ks you to "Choose
Your Data Conne ction".
7. C lick on the New Connec tion button. An Add Conne ction
window similar to the one in
Fig. 10.3 appea rs.
Data So urce Config uratio n Wiza rd

Choo se a Data Sourc e Ty pe

-- ,
lDotobm
Servi ce
~
Obj ect

se objects for your appl ication .


Lets you connec t to a databa se and choose t he databa

Ne:t > Cancel

FIGURE 10.2 Wind ow produ ced by Step 4.

Add Conne ctio n


l Tt ll!le"-~ _.,j

sourc e or click
E.nter inform ation to conne ct to the select ed data
ent data sourc e and/ or prov ider.
"Chan ge" to choos e a differ

Data sourc e:
Micro soft Acces. s. Datab ase File (OLE. DB) Chang e ...

Databas.e file name:


Brow s.e...

Log on to the datab ase

Us.er name: Admi n

Passw ord:
j Save my pas.s.w ord

dv anced ...

OK Cance l
T es.t Conne ction

FIGURE 10.3 Wind ow produ ced by Step 7.

460
10.1 An Introd ucti on to Databases
• 461
8. If the "Da ta source:" tex t
box doe s not say "M icro soft Acc
clic k on the C hange but ton . A ess Database File (OL E DB) ",
C han ge Dat a Source window will app
Access Database File from the win ear. Sel ect Microsoft
dow's list box and click on the
retu rne d to the Ad d Co nne ctio OK but ton . You will be
n wind ow shown in Fig. 10.3.
9. C lick on the Browse but ton
, nav iga te to and ope n the Dat
Pro gra ms\ C hlO ) , dou ble -cli ck aba ses fo lde r (a sub fo lder of
on Me gac ities .acc db , and clic k
Dat a Source Co nfig ura t ion Wiz on the OK but ton . Th e
ard tha t app ear ed in Step 6 reap
now co nta inin g Megac ities.accdb pea rs wit h the tex t box
.
10. C lick on the Next but ton
. The window in Fig. 10.4 appear
to place a copy of the file Megac s, ask ing wh eth er you wou ld li ke
ities.accdb into the program.

~icros.oft Visu a l Basic 20 0 Exp ress


l j

Th e con n ecti on you s.ele cted uses


a loc al data fil e that is. not in th
curr ent proj ect. !Vou ld you like e
to cop y th e fil e to you r proj ect
mod ify th e con n ecti on ? and

If you cop y th e data fil e to you


r proj ect, it will be cop ied to th
out put dire ctor y ea ch tim e you e proj ect' s.
run th e appli cati on. Press. Fl for
info rma tion on con trol ling this
behavior.

~--Ye_s.__~J ~~ ___N_o __~j [~__H_e_lp__~


FIGURE 10.4 Win dow pro duc ed by Step 10.

11. C lick on the Yes but ton


. Th e Data Source Co nfig ura
wh eth er you would like to Sav e t ion Wizard wi ll appear and ask
the Co nne ctio n Str ing to the Ap p lica
File. See Fig. 10.5 on the nex t pag tion Co nfig ura tion
e.
12. Ma ke sure tha t the Yes che
ck box is checked and the n clic
Source Co nfigura t ion Wizard in k on the Next but ton . The Dat a
Fig. 10.6 will appear.
13. C hec k the Tables che ck box
and the n clic k on the Finish but
of BindingSource1 is now set ton. Th e Dat aSo urc e prope rty
to Megac itie sDa taS et, and a Me
appeared in the com pon ent tray gac itie sDa taS et icon has
.
14. In the BindingSource1 Proper
ties window, click on the down-a
Dat aM emb er property's Set tings rrow at the righ t ide of the
box. A drop-down list con taining
database will appear. the tab les in the Megac ities
15. C lick on C ities in the dro
p-d own list. A C itiesTab leA dap
nen t tray. A lso, a Load eve nt pro ter icon will appea r in the co mp
ced ure con tain ing one line of exe o-
in the Cod e Editor. See Fig. 10. c utab le cod e is ge nerated
7 on page 463 .
Th e Cit ies table can now be acc
essed by the program. You ca n eas
for bot h of the tab les in the Me ily view a list of th e fie lds
gacities database. Jus t bring up
and dou ble -cli ck on the fi le Me the Solu t ion Exp lore r window
gac iti esD ataS et.xsd to d isp lay the
close the page, click on the X sym page in Fig. 10.8. (Note: To
bol on its tab.)
Wiz ard
Data Sou rce Con figu ratio n

atio n File
to the Ap plic atio n Co nfi gur
Sav e the Co nne ctio n Str ing

dep loym ent. To save the


file ease s mai nten anc e and
con nec tion strin gs in you r app licat ion configuratio n th e box and then click Next.
Storing r a nam e in
lica tion con figu ration file, ente
con nec tion string in the app fil'e ?
tion con figu rati on
nec tion strin g to the app lica
Do you wan t to sav e the con

i
,/J Yes, save the con nec tion as:

Meg •<it ;5C ooo od;o oStr iog

check this box

Cancel
<Pr evio us ]I.___N_ext
__>_ __.

p 11.
FIGURE 10.5 W ind ow pro duc ed by Ste

Wizard
Data Sou rce Con figu ratio n

jec ts
Ch oos e Yo ur Da tab ase Ob

----------
you wan t in you r data set ?
-1fl]
Wh ich data base obje cts do

[
~ Tables
@V iews
-- - -

check this box

I
..J

DataSet nam e:
MegacitiesDataSet

.____F_in_i_sh__.......J c_a_n_ce_l__~
L[_ _ _
<.P revi ous

p 12.
FIGURE 10.6 Wi ndo w pro duc ed by Ste

462
10.1 A n Intro duct ion to Data bases
• 463

Priv ate Sub Forrn l Load ( ... )


Han dles MyB ase .Loa d
'TODO: This lin~ of code load
s data into the 'Me gac itie sDa
•tab le. You can mov e, or remo taSe t.Ci ties '
ve it, as need ed.
Me .Cit iesT able Ada pter .Fil l(Me
.Me gac ities Dat aSe t.Ci ties )
End Sub
FIGURE 10.7 Cod e gene rated by Step 15.

Meg acities.Data5et.xsd* X Forml .vb [Design]*

FIGURE 10.8 Tabl es and fi elds in the Megacities data


base .
Binding to Additional Tables
A prog ram can access man y tables thro ugh
one data base conn ectio n. T he follo wing
th e Cou ntries table to the prog ram crea steps bind
ted in the walk thro ugh above.
1. Add ano ther Bind ingSource cont
ro l to the Form Designer.
2. et its Data Source property to Meg
acit ies Data et. (Aft er yo u click on the
click on the right - poin ting trian gle (or plus down-arrow,
box) to the left of Oth er Data Sources, click
the righ t-po intin g trian gle (or plus box ) on
to the left of Proj ect Data Sou rces
on MegacitiesDa taSe t.) , and then cl ick
3. Set the Data Member property of the
new Bind ingSource co ntro l to Cou ntrie
esTa bleA d apte r icon wi ll appear in the s. A Cou ntri-
compon ent tray, and anot her line of code
added to the Load even t procedur e. wi ll be

Browsing a Connected Database


Afte r a database has been conn ected to a
program , any table from the data base can
played. The follo wing steps d isp lay a table eas ily be d is-
fro m the Megaciti es database.
1. Righ t-dick on the name of the data base
(Megacit ie .accdb) in the Solution Explorer
Open in the context menu. W ith Visual Basic and click on
Express the Data base Explorer window in Fig.
10.9

Data bas e Explore r

Data Conn ectio ns


" Meg a citi es. ac cd b
Ta bl es
[> Views
•, Store d Proc edur es
'> Func tions

FIGURE 10.9 D ataba se Expl orer wind ow.


464 • Cha pter 10 Data bases

the Server Exp lore r


appe ar in the loca tion occu pied by the Too lbox. (With Visual Studio,
will
wind ow will appear.)
fold er. The fo ld er
(or plus box ) to th e left of the Tab les
2. C lick on the righ t-po int ing tria ngle
the two tables.
will ope n and reve al the nam es of
s) or Prev iew Data (wit h
3. Rig h t-cl ick on C it ies, and clic
k on Retrieve Data (w ith VB Ex pre
e wi ll be disp layed in
al Stu dio) in the con tex t men u . The con ten ts of the C ities tabl
Visu
0.
the tabb ed page sho wn in Fig. 10.1
4. C lick on th e X ymb ol on the
page 's tab to clos e the page.

X Forml.vb [Design]* ....


Citie.!>: Que. ry(C:\ U...1\ Me.g aciti es.ac cdb)

-
pop2010 pop.2.015
nam e coun t ry
20.1 22
~
India
13.1 13.4
I Bu enos Aire!; Arg entina
15.6 17
Ca lcutta Indi a
17 18.7
Delhi Indi a
14.8 17
Dhaka Bangladesh
19.5 20.2
~vl ex ico Ci y Mex ico
19.4 20
New York USA
19.6 20.1
Sao Pau lo Braz il
15.8 17.2
Shanghai China
36 .1 36.4
Toky o Japan
NULL NULL
NULL NULL
* m
I

1 of10
• •I • ..,

FIGURE 10.10 Con tents of the C ities table.

Querying a Table with LINQ


e. LIN Q can be
are usua lly quit e larg e and so we rare ly wan t to d isplay an ent ire tabl
Dat aba ses to extr act info rma tion
data tab le usin g similar syn tax as used
used to extract info rma tion from a
Vide o Note
Q uerying tahles t file, or an XML fi le.
from an arra y of reco rds, a CSV tex con ta in ing seve ral
a equ ence of row s with each row
A data base table can be tho ugh t of ied by the na mes
line is a row of a data table, then the elements of the row are inde ntif
fields. If
me2 , and so on. For in ran ee,
if city is the first row of th e
l, li n e . fiel dNa
lin e. fiel dN ame
ci t y . nam e is Bo mbay, the valu
e of cit y . cou ntry i Ind ia,
C ities tabl e above , then the va lue of .0.
and the value of c i ty . pop 2 015 is 22
the value of ci ty . pop 201 0 is 20. 1,

and
ities table of th e Megacit ies data base
Example 1 The follo win g prog ram uses the C ed by th e ir 201 0
the nam es of the citie s that are loca ted in Ind ia. The cities are sort
disp lays ulat ion of those cit ies in
prog ram also d isplays the tota l pop
populat ion in dec reas ing orde r. The Q q uery. Not e: In the
erve a the data sour ce for the LIN
a text box. Megacit iesO ataS et.C ities
10.1 An In trod uction to Dat aba es
• 465
O rd er By clause of que ryl , the re
was no need to use the C Dbl fun
was give n to the pop 20 10 field whe ctio n . The data type Doub le
n the dat abase wa crea ted, and the
cit y . pop 201 0 has type Dou refo re LIN Q kno ws tha t
ble.

a~ Meg acit ies ~Q¥IJ~


OBJECT PROPERTY SETTING
frmC ities Tex t Meg ac ities
btnD isp lay Tex t D isplay Ci ties in Ind ia
Display Cities in India ] lstO utpu t
lblT otalPop Tex t Tota l pop ulat ion :
tx tTot alPo p Rea d O n ly True

Total population :

~ Meg ac i ies.DacaSe
~ Ci iesTableAda p er

Pri vat e Sub frm Cit ies _ Loa


d( ... ) Han dle s MyB ase .Lo
'cod e gen era ted aut om atic ad
ally whe n Dat aMe mbe r was
Me . Cit ies Tab leA dap ter. Fil set to Cit ies
l( Me .Me gac itie sDa taS et.C
End Sub itie s)

Pri vat e Sub btn Dis pla y_


Cli ck( ... ) Han dle s btn Dis
Dim que ryl = Fro m cit y pla y.C lick
In Me gac itie sDa taS et.C itie
s
Wh ere city .co unt ry = "In
dia "
Ord er By city .po p20 10 Des
cen din g
Sel ect city .na me
lstO utp ut . Dat aSo urc e =
que ryl .To Lis t
lstO utp ut . Sel ect edi tem
= Not hin g
Dim que ry2 = Fro m cit y
In Me gac itie sDa taS et.C itie
s
Wh ere cit y .co unt ry = "In
dia "
Sel ect city .po p20 10
txtT ota lPo p . Tex t = CSt r
(qu ery2 .Su m)
End Sub

[Run, and cl ick on the but ton .]

a~ 1ega ci1ie s

Display Cities in India

Bombay
Delhi
Calcutta

Tota l popu lation : 52.7


466 • Cha pter 10 Databas es

requ sted by
the Co unt ries tab le for a cou ntry
Example 2 The fo llow ing progra m searches "mo netary Un it" in
tha t the Dat aSo urce met hod d isplays "na me", "pop20 10", and
the user. No tice ", and "co unt ry.m one tary Un it".
u ntry. name", "co unt ry.pop2010
the headers of the tab le, not "co loop ing variab le in a For Each
vari able cou ntry plays a sup porting ro le sim ilar to tha t of a
The
loop.
ase .Lo ad
s_ Loa d ( ... ) Han dle s MyB
Pri vat e Sub f r mC oun trie aMe mbe r was set to Cit ies
ally whe n Dat
'co de gen era ted aut om atic taS et .Co unt rie s)
er.F ill( Me . Me gac itie sDa
Me .Co unt rie sTa ble Ad apt
End Sub
Dis pla y.C l ick
Cli ck( . .. ) Han dle s btn
Pri vat e Sub btn Dis pla y_ sD ata Set .Co unt ries
itie
Dim que ry Fro m cou ntr y In Me gac
e.T ext
Wh ere cou ntry .na me = txtN
am
net ary Un it
ntr y.p op2 010 , cou ntry .mo
Sel ect cou ntr y.n am e, cou
If que ry.C oun t = 1 The
n
dgv Ou tpu t.D ata Sou rce = que ry. ToL ist
dgv Ou tpu t.C urr ent Cel l
= No thin g
Els e " , "No t Fou nd" )
ry is not in the tab le.
Me ssag eBo x . Sho w ( "Co unt
End If
End Sub
t box, and clic k on the but ton.]
[Run, ent er a coun try into the tex

a-;} M ega ci ies


l = I @) ~~ ,j

Cou ntry : India

l Display the Country's Record


J
pop 2010 mon et ary Unit
name
_p_e~
'ru
--h
India [ 11 96.8

and
tabl e of the Me gac ities dat aba se
Example 3 Th e foll owi ng progra m uses the C ities 1 mi llio n peo ple
-./ by mo re tha n
lays the c ities who se pop ulat ion s are pre dic ted to incr ease bot h the
disp lati o n inc rease, and
ord ered by the ir pro ject ed popu
from 2010 to 20 15 . The citi es are
ea es (in mil lion s) are d isplayed.
city nam e and pop ulation incr
ase .Lo ad
Loa d ( ... ) Han dle s MyB
Pri vat e Sub frm Cit ies _ esD ata Set . Cit ies )
i ll (Me .M ega citi
Me .Ci tie sTa ble Ad apt er.F
End Sub
Dis pla y . Cli ck
Cli ck( ... ) Han dle s btn
Pri vat e Sub btn Dis pla y_
sD ata Set .Ci ties
Dim que ry Fro m cit y In Me gac itie
op 2 015 - city .po p20 10
Let pop inc rea se = cit y.p
1)
mat Num ber (po pin cre ase ,
Let for ma tted inc r = For
Wh ere pop inc rea se > 1
cen din g
Ord er By pop inc rea se Des
tted inc r
Sel ect city .na me , for ma
10.1 An Introduc ti on to Databases • 467

dgvOut put.Dat aSourc e = query . ToList


dgvOu tput.Cu rrentCe ll = Nothin g
dgvOut put.Col umns( "name" ) . Header Text = "City"
dgvOut put .Colum ns( "forma ttedinc r" ) .Header Text "Popul ation Increas e"
End Sub

[Run, and cl ick on the button. ]

Display Oties

Population
Oty
Increase
Dhaka 2.2
Bombay 1. 9
Delhi 1.7
Calcutta 1.
Shanghai 1..

Example 4 The following program displays the cities fro m the Cities table in a list box
sorted by their population in 2010. When the user clicks on one of the cities,
its coun try, popu la-
tion in 2010, and populat ion in 2015 are displaye d in text boxes. In the second
event procedur , a
query is used to earch for the desired record of the table. In this ca e, the query
returns a sequence
of one value. Since a sequenc e cannot be assigned to a text box, the First method
is used to obtain
the desired value. Note: Notice that the stateme nt lstCiti es . Dataso urce
= query.T oList in
the Load event procedure is not followed by the stateme nt lstCi ties . Selecte
ditem = Nothing .
Had the Selecte dltem stateme nt been added, the ini tial display wou ld show
the data about Tokyo
without revealing the city that the data referred to.

Private Sub frmCit ies _ Load( ) Handle s MyBase .Load


Me .C itiesTa bleAd apter.F ill( Me . Megac itiesDa taSet.C it ie
s)
Dim query = From city In Megac itiesDa taSet.C ities
Order By city.po p2010 Descen ding
Select city.na me
lstCiti es.Dat aSourc e = query . ToList
End Sub

Privat e Sub lstCiti es Selecte dindex Change d( ... ) Handle


s
lstCiti es . Selecte dindex Change d
Dim query From city In Megac itiesDa taSet.C ities
Where city.na me = lstCiti es.Tex t
Select city.co untry, city.po p2010, city.po p2015
txtCou ntry.Te xt query . First.c ountry
txtPop2 010 . Text Format Numbe r(query .First.p op2010 , 1)
txtPop2 015.Te xt Format Numbe r(query . First.p op2015 , 1)
End Sub
468 • Chapte r 10 Databases

[Run, and click on one of the cities in the li t box.]

c~ egacities

Tokyo Country: USA


Bombay
Sao Paulo
Mexico CJt!1
Population in 2 10: 19.
Delhi
Shangha i
Calcutta
Dhaka
Population in 2015: 2 .
Buenos Aires

Primary and Foreign Keys


be used to unique ly id entify
A we ll-desig ned tab le should ha ve a field (or set of fi elds) that can
y key. Fo r instance, in the C ities and
each record. S uch a field (o r set of fields) is called a primar
en t enro llment s in a co llege
Countr ies tab les, each name fie ld is a primary key. Databases of stud
names would not be a good
usually use a field of tudent ID numbe rs as the primary key. S tud ent
n ame.
choice , because there could eas ily be two stud ents h av ing the same
primar y key. If so, Visual Basic will
When a tab le is created , a field ca n be pec ified as a
sa me entry does not appear
insist that eve ry reco rd has an entry in the primary key and that the
data in the primar y key, the
in two differe nt reco rds. If the use r tries to add a record with no
will be ge nerated. If the user
error message "Ind ex or prima ry key cannot contai n a Null Value."
reco rd, an error message will be
tr ies to add a record with the same primary key data as ano ther
ful because they wo uld cre-
disp layed: "The changes you requ ested to the table were not success
hange the data in the field or
ate duplica te va lues in the index, primary key, o r relation ship. C
t he index to permit duplica te
fie lds that contai n duplica te data, remove the index, or redefin e
entri es and try aga in."
related. Fo r instance, th e
When a databa se conta in two or more tab les, they are usua lly
h o ld name of countries. Let'
two tables C ities and Countr ies are related by the ir fie lds that
N o tice that every entry in
refer to these two fie lds as C ities .countr y and Countries .name.
that Countr ies .name is a primary key of
Cities.country appea rs unique ly in Countries.nam e and
key of Countries. name.
the Count ries table. W e ay that C ities .country can se rve as a foreign
If so, Vi sua l Basic wi ll enforce
Foreign keys are usually specifie d when a databa se is first crea ted.
fore ign key must a lso appea r
the Rule of R eferent ial Integri ty-na mely, that each va lue in the
as a va lu e in the primary-key field of the other table.
been specifi ed as primar y
In the Megac ities database, Cities. name and Countr ies. name have
specifi ed as a fo re ign key of
keys for their respect ive tables, and C ities .countr y ha been
Countries. name. If the use r tries to add to the C ities table a c ity
whose co untry does not appear
add or ch ange a record
in the Co untries tab le, an error message wi ll be displayed: "You cannot
The messag e wi ll also be ge nerated if
becaus e a related reco rd is req uired in table 'Count ries'."
field that appear s in the
the user tries to de lete a country from the Countries. name
C ities.country field.

The Join of Two Tables


a relatio na l database in a
A foreign key allows Visual Ba ic to link (or join) two tables from
ies from the Megac ities
meanin gful way. For instanc e, when the two tables C ities and Countr
is Table 10.3. The record
databa se are joined based on the fore ign key C ities.country, the result
10.1 An Introduction to Databases
• 469

fo r each city is expan d ed to h o w its count ry's 201 0 popula t io n an d its mo n etary uni t. T his
jo ined table i very h and y if, say, we wa n t to d isplay a c ity's cu rre ncy.

lbNIII•II Ajoin of two tables.


Cities. Cities. Cities. Count ries. Count ries. Count ries.
Cities. name countr y pop20 10 pop20 15 name pop20 10 monet ary Unit
Bombay India 20.1 22 .0 India 11 96.8 rupee
Buenos A ires Arge ntina 13. 1 13.4 Argent in a 41.9 peso
alcutta India 15.6 17.0 India 11 96.8 rupee
De lhi India 17.0 18.7 India 11 96.8 rupee
Dhaka Bangladesh 14.8 17.0 Bangladesh 152.6 rupee
Mex ico C ity Mex ico 19.5 20.2 Mex ico 11 7.4 peso
New York USA 19.4 20.0 USA 310.1 dollar
Sao Pa ulo Braz il 19.6 20.1 Braz il 195.2 rea l
hangha i C hin a 15.8 17.2 C hina 1379.7 yuan
Tokyo Japan 36. 1 36.4 Japan 129 .0 ye n

The q ue ry th a t creates the jo in above beg ins as follows:

Dim query = From city In Mega cities DataS et.Cit ies


Join count ry In Mega cities DataS et.Co untrie
s
On city.c ountr y Equal s count ry . name

The From clause is standa rd. The Jo in clause says th at the


Count ries table sh o uld be jo ined with
th e C ities ta ble. The O n clause inden tifies th e two fie lds
wh ose va lues are match ed in o rde r to
jo in th e ta bles. The variab les city and countr y in th e first
two clauses are loopin g variab les a nd
can h ave an y n a mes we choose . Fo r instan ce, t he q ue ry above
could have bee n writte n
Dim qu e ry = From town In Mega cities DataS et.Cit ies
Join natio n In Mega cities DataS et . Coun tries
On town. count ry Equal s nation .name

~ Example 5 T h e fo llowin g progra m d ispla ys Ta ble 10.3, th e jo in of


th e two ta bles from
th e M egac ities database.

Priva te Sub frmC ities Load( . .. ) Handl es MyBas


e .Load
Me .Coun triesT ableA dapte r . Fill( Me .Mega cities
DataS et.Co untrie s)
Me . Cit iesTa bleAd apter . Fill( Me .Meg acitie sData
Set.C ities)
End Sub

Priva te Sub btnDi splay_ Click ( ... ) Handl es


btnDi splay . Click
Dim query From city In Mega cities DataS et.Cit ies
Join count ry In Mega cities DataS et.Co untrie
s
On city .coun try Equal s count ry.nam e
Let cityNa me = city.n ame
Let cityPo p2010 Forma tNum ber(ci ty.pop 2010, 1)
Let cityPo p2015 = Forma tNum ber(ci ty.pop 2015,
1)
Let countr yNam e = count ry.nam e
Let countr yPop2 010 = Forma tNumb er(cou ntry.p
op201 0, 1)
Selec t city Name, city.c ountr y, cityPo p2010
, cityPo p2015 ,
countr yNam e, count ryPop 2010, count ry.mo netary
Unit
470 • Chap ter 10 Databases

dgvO u t p u t . Data Sour ce = query . ToLi st


dgvO utpu t.Cu rren tCel l = Noth i ng
End Sub

[Run, and click on the butto n.]

l= l · @l i~J
• Megacit ies

Display the Join of the Two Tabies

countryN ame countryPop201 0 monetai)'Unit


country cityPop 2010 crtyPop2015
cityName
India 1.1968 rupee
India 20.1 22 0
Bombay
Argentina .!1 9 peso
13.1 13.<~
Buenos .Aires Argentin a
India 1.1968 rupee
India 15.6 170
Calcutta
India 1,196.& rupee
India 17.0 1&.7
Delhi
Banglad esh 152.6 raka
Bangladesh 14.& 17.0
Dhaka
Mex~co 11 7..! peso
City Mex~co 19.5 20.2
Mex~co
USA 310.1 dollar
USA 19..! 20.0
New York
Brazil 195 2 real
Brazil 19.6 20.1
Sao Paulo
China 1.379.7 yuan
China 15.& 17.2
Shangh ai
Japan 129 0 ;•en
36.4
Tokyo Japan 36.1 I

in the Megacit ies data-


Example 6 T he following program u e the jo in of the two ta bles
box is fi lled with the mone tary units from
base. W hen the fo rm is loaded, the C urren cies list
use r selec ts a curre ncy, the cities that use
the Coun tr ies table in alpha betical order. W hen the
alpha betica l ord er. Note: The C itie list box
that curre ncy are d isplayed in the C ities list box in
ource meth od, so that the word NON E
was filled with the Add meth od rathe r than the DataS
curre ncy.
could be displayed when no cities u e the selec ted
OBJECT PROPERTY SETTING

D':J Me:gac itie:s GJ I a I[ID fr mCitie Text Megacitie


Cu rrencies
lbl urrenc ies Tex t
Currencies Cities
lstC urrencies
lstCurrencies 1stCities lblC iti es Text C ities
lstC iti es

·-

les MyBa se . Load


Priv ate Sub f rmCi ties_ Load ( ... ) Hand
dapte r.F i ll( Me .Meg aciti esDa taSet . Coun t ries)
Me .Cou ntri esTa bleA
ities Data Set . Ci t ies )
Me .Citi e sTab leAd apte r.Fil l (Me . Mega c
esDa taSet . Coun t rie s
Dim query = From coun try In Meg aciti
Orde r By coun t ry .mon etary Unit Asce nding
Sele ct coun t ry . mone taryU nit
Dist inct
lstC urr e nc i e s . Data Sour ce = query . ToLi
st

End Sub
10.1 A n Introdu ction to Databa es • 471

Privat e sub lstCur rencie s Select edinde xChan ged(


... ) Handle s _
lstCur rencie s.Sele ctedin dexCh anged
Dim query From city In Megac itiesD ataSet . Cities
Join countr y In Megac itiesD ataSet .Coun tries
On city.c ountr y Equals countr y.nam e
Where countr y.mon etaryU nit = lstCur rencie s.Tex
t
Order By city.na me Ascend ing
Selec t city.na me
lstCit ies.Ite ms.Cl ear()
If query. Count > 0 Then
For Each city As String In query
lstCit ies . Items. Add(c ity)
Next
Else
lstCit ies . Items .Add ( "NONE" )
End If
End Sub

[Run, and click on a curren cy in the C urrenc ies list box.]

Currencies Oties
r-------,
Buenos Aires
Mexico Cit;•

Comments
1. A database resides on a disk, and a DataSe t resides in memory.
A table adapte r serves a a
condui t to allow bid irection al data transfe r betwee n the two. A
bindin g source is used to
simplify attachi ng form con tro ls to data sources .
2. The require ment th at no record may have a n ull entry in a primar
y key an d th at entr ie for
primary keys be un iqu e is called the Rule of Entity Integri ty.
3. The Jo in of two ta bles is a virtu al constru ct. It exists on ly in memor
y.

Practice Problems 10.1

1. Consid er the qu ery in the Load event proced ure of Exa mple 6. W
hat would happen if the
LINQ operato r Distinc t were omitted ?
2. Consid er the qu ery in Exa mp le 5. W hy ca n 't th e Select clause be
wri tten as follows?
Select city .name, city . countr y, cityPo p2010 , cityPo
p2015 ,
c o untry . name, countr yPop2 010, countr y.mon etaryU
nit
472 • Chapte r 10 Database

EXERCISES 10.1

ures in Exercises 1 th rough 6.


Figure 10.11 conta ins the output s prod uced by the event proced

city Name country name country


cityName monetary Unit
China Calcutta India
Dhaka raka Shangha i
India Dhaka Bangladesh
Buenos Aires peso Calcutta

(b) (c)
(a)

country name monetaryUnit


name monetary Unit name
Bangladesh Japan yen
Indonesia rupiah Dhaka
Brazil China yuan
USA dollar Sao Paulo

(e) (f)
(d)

FIGURE 10.11 Outpu ts for Exercises 1 throug h 6.

10.11 that is the outpu t of the


In Exercises 1 throug h 6, identify the DataG ridVie w in Fig.
event proced ure as Example 5.
event proced ure. Assum e that each program has the same Load
splay . Click
1. Priv ate Sub btnDi splay_ Click ( ... ) Handl es btnDi
Dim query From city In Mega cities DataS et . Citie s
Where city . count ry. Starts With ( "B")
Selec t city.n ame, city.c ountr y
dgvOu tput.D ataSo urce = query .To Li st
dgvO utput. Curre ntCel l = Nothi ng
End Sub
.Click
2. Priv ate Sub btnDi splay_ Click ( ... ) Handl es btnDi splay
Dim query From city In Mega cities DataS et.Cit ies
Where city.p op201 5 = 17.0
Selec t city.n ame, city.c ountr y
dgv Outpu t.Data Sourc e = query .ToLi st
dgvO utput. Curre ntCel l = Nothi ng
End Sub
btnDi splay .Click
3. Priva te Sub btnDi splay_ Click ( ... ) Handl es
s
Dim query From count ry In Mega cities DataS et.Co untrie
try.po p2010 < 300)
Where (coun try.po p2010 > 250) And (coun
Selec t count ry.nam e, count ry.mo netary Unit
dgv Outpu t.Data Sourc e = query .ToLi st
dgvO utput. Curre ntCel l = Nothi ng
Sub
splay .Click
4. Priva te Sub btnDi splay_ Click ( ... ) Handl es btnDi
s
Dim query From count ry In Mega cities DataS et.Co untrie
Where count ry .mone taryU nit . EndsW i th ( "n")
Order By count ry.pop 2010 Ascen ding
Selec t count ry.nam e, count ry.mo netary Unit
dgvOu tput.D ataSo urce = query .ToLi st
dgvO utput. Curre ntCel l = Nothi ng
End Sub
10.1 An Intro d uctio n to Data base s
• 473

5. Priv ate Sub btnD ispl ay_ Clic k(


.. . ) Han dles btnD ispl ay.C lick
Dim que ry From city In Meg acit iesD ataS
et.C ities
Join cou ntry In Meg acit iesD
ataS et.C oun trie s
On city . cou ntry Equ als coun try.n
ame
Let cityN ame = city .nam e
Whe re cou ntry .pop 2010 > (75
* city . pop2 010)
Ord er By city .cou ntry Asc endi
ng
Sele ct city Nam e, city .cou ntry
dgvO utpu t . Da t aSo urce = que ry.T
oLi st
dgv Out put. Cur rent Cell = Not hing
End Sub
6. Priv ate Sub btnD ispl ay_ Clic k( . .
. ) Han dles btnD ispl ay.C lick
Dim que ry From city In Meg acit iesD ataS
et.C ities
Join c oun try In Meg acit iesD ataS
et . Cou ntri es
On city .cou ntry Equ als coun try.n
ame
Let cityN ame = city .nam e
Whe re coun try . nam e.Le ngth >
8
Orde r By city .pop 201 0 Des cend
ing
Sele ct cityN ame , cou ntry . mon
etar yUn it
dgv Out put. Dat aSo urce = que ry.T
oLi st
dgv Out put. Curr entC ell = Not hing
End Sub

Exe rcise s 7 thro ugh 16 requ ire th e M


egac ities data base .
7. Writ e a prog ram that displays (in a Data
G ridV iew cont rol) the names of all the
cou ntries, and the projected percentage grow cities, their
th of their popu latio ns from 2010 to 2015
houl d be sorted in descend ing order by the . Reco rds
ir projected populatio n grow th. See Fig. 10.1
2.

ll M egaci ies l = I @) 1- tJ · I
( Displa}' Data
I
Projected
City Country Population
Gro•Nth
Dhaka Bang ladesh
11 . 8b-~
Delhi India 10. %
Bombay India
- -
9 .45~~
Calcutta India 8 . 97~~
Shanghai
- -
China 8.86*4
Mexico City I Mexico
- --
3 . 59~~
New York USA
- -
3. 9 ~~
-- -
Sao Paulo Brazil 2 . 55~~
Buenos Aires -
Argentina 2.2~~
Tokyo Japan 0.8J':~

FIGURE 10.12 O utpu t o f Exe rcise 7.


474 • Cha pter 10 Databases

es from the C ities


te a prog ram that show s (in a list box ) the nam es of a ll the cou ntri
8. Wri ld display (in a text
of the co untr ies, the prog ram sho u
table. Wh en the user clic ks on one
c ity in 2010.
box) the nam e of its most populous
s in the C ities tabl e
(in a list box) the nam es of the citie
9. Wri te a prog ram that dis plays 5. The c ities sho uld
exc eed 20 million by the yea r 201
whose pop ulat ions are proj ecte d to
lat ion in descend ing o rder.
be orde red by thei r proj ecte d popu
es of the c ities in the
a Dat aGr idVi ew con trol) the nam
10. Wri te a program that disp lays (in co untr ies and
are betw een 13 and 19 million. The
Cit ies tab le whose 2010 pop ulat ions be ordered a lpha -
be di played, and th e reco rd s sho uld
thei r 20 10 pop ulat ions also sho uld
es.
betically by the names of the cou ntri re reco rd for the
te a prog ram to find and disp lay (in a Dat aGr idV iew con trol ) the enti
11. Wri th from 2010 to
erie nce the greates t perc enta ge grow
city in the C ities tab le that will exp
is (pop 2015 - pop 201 0) / pop 201 0.
2015. Not e: The perc enta ge growth
of all the c ities, thei r
a Dat aGr idV iew con trol ) the nam es
12. Wri te a prog ram that displays (in lived in that city
tage of its co untr y's pop ulat ion that
cou ntri es, and for each city the pe rcen
desc end ing orde r by the perc enta ges.
in 2010. Records sho uld be so rted in
clicks on one of the
te a prog ra m that disp lays the c ities in a list box. Wh en the use r
13. Wri ntry' pop ulat ion
a text box) the perc enta ge of its cou
c ities, the prog ram ho uld display (in
that lived in that city in 2010.
user clicks on one of the
the c ities in a list box. Wh en the
14. Wri te a prog ram that displays
a text box) the city's curr ency.
cities, the prog ram sho uld display (in
s of the C ities tab le.
Wri te a prog ra m that crea tes a CSV text fi le co nta ining the con tent
15. size of the file
the prog ra m, and com pare the size of the text fi le with the
Run
Megacities.accdb.
s of the Citi es table.
16. Wri te a program that crea tes
an XML fil e con tain ing the con tent
the 192 mem ber
base UN .acc bd has the sing le table Nat ion s that con tain s data for
The data
The fields for the table are nam e,
con tinent, population,
cou ntri es of the Uni ted Nat ions . the Uni ted Nat ion s
ions and area in squ are mile s.) Use
and area. (Po pula tion is given in mill
19. Some records in the table are
data base in Exe rcises 17 thro ugh

32.9 385 500 0


Can ada Nor th Am eric a
63.5 211 2 0 9
Fra nce Eur ope
4.18 103 738
New Zea land Aus tral ia/O cea nia
146 .5 356 669
Nig eria Afr ica
164 310 403
Pak ista n Asi a
27.9 496 226
Per u Sou th Am eric a

ions tabl e in a li t
te a prog ram that disp lays the nam es of th e con tine nts from the Nat
17. Wri con tine nt sho u ld be
tine nt's nam e, the cou ntri es in that
box. Wh en the use r clicks o n a con ntri es in desc end ing
ne list box sh ould di play the cou
displayed in two other list boxes. O end ing orde r by
er sho uld disp lay the cou ntri es in desc
orde r by the ir pop ulat ion, and the oth
thei r area. See Fig. 10.13.
the Nat ions tabl e in a list
te a prog ram that disp lays the names of the con tine nts from
18. Wri tine nt sho uld be
Wh en the user clic ks on a con tine nt's nam e, the cou ntri es in that con
box. reco rds sho uld be
g with thei r popu latio n densities. The
displayed (in a Dat aGr idV iew ) alon
ion den sities.
in ascend ing orde r by thei r pop ulat
10.1 A n In trod ucti o n to Databases
• 475

Continents : Countries by Population : Countries by Area :


.Africa Braz il ;. Brazil ;.
Asia Colombia Argentina

~
AJ..Jstralia/D ceania Argentina

I~
Peru
Europe Peru Colombia
North America Venezuela Bolivia
South lvnerica Chile Venezuela
Ecuador Chile
Bolivia Paraguay

FIGURE 10.13 Sam ple outp ut of Exe rcis e 17.

19. Wr ite a prog ram to find and disp


lay (in a Dat aGr idV iew con trol )
the firs t reco rd gives the data for two enti re reco rds, whe re
the cou ntry wit h the largest popu
the da ta fo r the cou ntry wit h the lati on, and the seco nd
sma lles t popu lati on.
The data bas e Exc hra te.a ccd b has
the single table Rat es tha t gives
term s of Am eric an doll ars) for the exc han ge rates (in
45 cur ren cies of maj or cou ntri
Fig ure 10. 14 sho ws the firs t eigh es in Dec emb er, 200 9.
t reco rds in the data base in a Dat
dol larR ate colu mn gives the num a Gri d View con trol . The
ber of uni ts of the cur ren cy tha t
Am eric an dollar. For inst anc e, can be pur cha sed for one
one Am eric an dol lar pur cha ses
Use the Exc hra te data bas e in Exe 1.0 587 5 Can adia n doll ars.
rcis es 20 thro ugh 22.

country monetaw Unit dollarRat e


America Dollar
Argentina Peso '' .B1 7
Australia Dollar 1.1
1
Braz il Real 176:
Canada Dollar 1. 5B7 ~=:
Chile Peso " 39. ~78
China Yuan S. •, 'lE;
Colo mbia Peso 1 ~94 . 5

FIGURE 10.14 Exc han ge rate s.

20. Wri te a prog ram tha t sho ws


the nam es of the cou ntri es in a list
on one of the nam es, the mon etar box . Wh en the use r clic ks
y uni t and the exc han ge rate sho
21. Wri te a program tha t d isplays uld be disp laye d.
the nam es of the coun tries in a
dete rmi ned by the num ber of unit list box in asce ndi ng ord er
s tha t can be purc hase d by one Am
u er clic ks on one of the names, the erican dollar. Wh en the
mon etary uni t and exc han ge rate
22. Wri te a prog ram con tain ing sho uld be displaye d.
two list boxes as sho wn in Fig. 10.1
the use r se lects two cou ntri es, ent 5 on the nex t pag . Wh en
ers an amo unt of mon ey, and clic
prog ram sho uld con ve rt the amo ks on the but ton, the
unt from one curr ncy to the oth
er.
476 • Cha pte r 10 Database

a.. Curren cy Convert er

12 Convert
Amount of money to convert :

.Pvnenca j Arnerica
rgentina Arge ntina
ustralia
.AJ.Jstralia
IBrazil I Brazil
Canada
Canada
Chile
Chile
China
China
Colombia Colombia
Czech Rep
Czech Rep
Den mark
Denmark

als 12. 1 Dollars from Canada .


12.00 Doll ars from America equ

e 22.
FIGURE 10.15 A possible out put for Exe rcis
ms. Th e fields for the Players
ll.a ccd b has the two tables Pla yer s and Tea
Th e dat aba se Bas eba le are nam e, location,
e, tea m, atB ats , and hits . Th e fields for the Teams tab
table are nam rma tion fro m the
atB ats , and hits . Th e dat abase has been filled wit h info
league, stadium, ue players wit h
for the maj or leag ue. Th e Pla yers table list s all maj or-leag
200 9 baseball season all major-league teams. Us e the
s dur ing the season. Th e Tea ms table lists
at leas t 350 at bat ord s fro m eac h table:
aba se in Exe rcis es 23 thr oug h 38. H ere are thr ee sample rec
Baseball dat

PI ayer s 195
Blu e Jay s 682
Aar on Hi ll 225
Ma rin ers 639
Ich iro Suz uki 212
Yan kee s 634
De rek Jet er

Tea ms 548 6 13 9 8
Na tio nal Wr igle y Fie ld
Cub s Ch ica go 549 3 143 2
Na tio nal Na tio nal Par k
Na tio nal s Wa shi ngt on D.C . 554 3 149 5
Am eric an Fen way Par k
Red Sox Bo sto n

Wh en the user
t sho ws all the team s from the Teams tab le in a list box.
23. Wr ite a program tha a tex t box.
s, the pro gra m sho uld disp lay the team's hom e stad ium in
clicks on one of the team tab le wit h the
m to disp lay in a list box the playe r (or players) in the Player
24. Wr ite a progra
hig hes t bat ting ave rage . Players tab le wit h the
gra m to disp lay in a list box the player (or players) in the
25 . Wr ite a pro
most hit . es of all the teams, the ir
m to disp lay in a Oa taG ridView con trol the nam
26. Wr ite a pro gra sor ted in asc end ing
s, and the team s' bat ting ave rages. Rec ord s sho uld be
hom e stad ium
ord er by the bat ting ave rages. box. Wh en the user
m tha t sho ws all the team s from the Tea ms table in a list
27. Wr ite a pro gra trol the names
team s, the pro gra m sho uld disp lay in a Oat aGr idV iew con
clicks on one of the wit h the ir bat ting ave rages. Th
e
s tab le from tha t team, alo ng
of all the players in the Player rages. See Fig. 10.1 6.
d ing orde r of the ir bat ting ave
players sho uld be listed in. descen .30 0 in a list box. When.
gra m tha t sho ws all the playe rs' bat ting ave rages abo ve
28. Wr ite a pro lay in a Oa taG rid-
on. one of the bat ting ave rages, the pro gra m sho uld disp
the user clic ks t bat ting ave rage,
nam es of all the play ers in the Playe rs tab le wit h tha
View con trol the
10.1 An Introduction to Databases
• 477

~~ ~ aseba ll

Teams : Plar ers :


Allgels ,.. Batting
Astros Name
.verage

~
ihletics
Blue Jays lbert Pujols .3 7
Braves
-
Cubs
.. .
Brewers Skip Schumaker

Yadier Molir a
.3.
3
Diamondbacks Brendan fi.r an
Dodgers
Giants Ryan Ludwi ck &5

FIGURE 10.16 Samp le ou tput of Exerc ise 2 7.


along with the ir teams. The playe r hould
be listed in alpha betical orde r of their last
names.
29. Write a program that conta ins two rad io
butto ns captioned American League and Natio
League. Whe n the u er clicks on one of them, the nal
program should display in a Data G ridVi ew
cont ro l the name s of all the teams in the Team
s table from that league, along with their team
batti ng averages. The teams should be listed in
desce ndin g order of their batti ng averages.
30. Writ e a program that uses the Teams table
to ca lcula te the tota l numb er of hits by teams
the National Leag ue. in
31. Writ e a program that uses the Teams table
to calculate the overall batti ng average for play-
ers in the Ame rican Leag ue.
32. Write a program to coun t the number of playe
rs in the Playe rs table who play for a New York team.
33 . Wr ite a prog ram to coun t the num ber
of playe rs in the Players table who play for a Nat
Leag ue team. ional
34. Writ e a prog ram that cont ains two radio
butto ns captioned American League and Natio
League. Whe n the use r clicks on one of the radi o nal
butto ns, the program should d isp lay ( in a
Data Grid View co ntrol) the name s of all the
playe rs from the league who had more than
150 hits, along with their batting averages and
home stadiums. The playe rs should be listed
in desc endin g ord er of their batti ng avera ges.
35. Writ e a program that shows all the teams
from the Teams tab le in a list box. Whe n the user
clicks on one of the teams, the program shou ld displ
ay (in anoth er li t box) the names of all the
playe rs in the Playe rs table from that team, whos
e batti ng average wa greater than their team's
batting average. The players hould be listed in
desce nding order of their batting averages.
36. Writ e a prog ram to di play (in a list box
) the player (or playe rs) in the Ame rican Leag
with the most hit . ue
37. Writ e a program to displ ay the playe r (or
playe rs) in the N ation al Leag ue with the high
batti ng ave rage. es t
38. Write a program that requests a batti ng avera
ge and a league (Am erica n or Nati onal) and
then disp lays (in a list box ) the names of all the
playe rs in the league whose batti ng ave rage
is great e r than the given batt ing ave rage. The
playe rs should be listed in de cend ing orde r
by the numb er of hits they had durin g the seaso
n . The program should not allow the given
batti ng avera ge to be great er than 1 or less than
0.
The datab ase Mov ies.a ccdb has two tables name
d Line s and Acto rs. The Line s table con-
tains famo us lines from films that were spok
en by the leadi ng male actor . The first field
the table gives the famo us line and the seco nd of
fie ld gives the film. Figu re 10.1 7 (a) show s the
478 • Chap ter 10 Databases

of films and
The Acto rs table cont ains som e nam es
first three reco rds of the Line s table. Act ors table.
(b) show s the first three reco rds of the
thei r leading male acto rs. Figu re 10. 1 7 Acto rs table . Use the
ign key to the film field in the
The film field in the Line s table is a fore
44.
Movies data base in Exe rcises 39 thro ugh

film maleLead
famo us Line film
On the Wate rfron t Marl on Brand o
Rose bud. Citizen Kane
Sudd en Impa ct C lin t Eastwood
We'll a lways have Paris. Casa blanc a
Tax i Driver Robe rt OeNi ro
I could a been a conte nder. On the Wate rfron t
(b) Acto rs
(a) Lines
ies datab ase.
FIGURE 10.17 Som e reco rds from the table s in the Mov

rs table?
39. Wh at is the prim ary key in the Acto
table?
40. Wha t is the primary key in the Line s
s table. Whe n
with the nam es of the fi lms in the Line
41. Wri te a program that fills a list box layed in
lead male acto r in that film should be disp
the user clicks on the name of a film , the
a text box. See Fig. 10.18.

a::;' tlo ies

Male lead :
Rims :
Marton Branda
Otizen Kane
asablanca
On the Waterfront

FIGURE 10.18 Sample outc ome of Exer cise 41.


us lines from
G ridView cont rol cont aini ng all the famo
42. Wri te a program that disp lays a Data Fig. 10.19. Note :
spoke them and the film . See
the Lines table alon g with th e acto rs who
of the Data G ridView cont rol to A llCe lls.
Set the Aut o izeColum nMo de property
l = I @) I; -M J
a •ilovi es

Display Famous Unes . .Actors , and Rims

.Actor Rim
Famous Une
j Orson 1/1/ells Otizen Kane
Rosebud .
Humphrey Bogart Casablanca
We 'II alwa) ' have Paris .
Marton Brand a On the W aterfront
I coulda been a contender.
Oint Eastw ood Sudden Impac t
Go ahead - make my day.
~mold Schwarzen eger 1 ~e Term
inator
I'll be back .
Jack Nicholson A Fe•N Good Men
You can't handle the truth !

FIGURE 10.19 Outc ome of Exer cise 42.


10.2 Editing and Des igni ng Dat aba
ses
• 479
43. Wr ite a pro gra m tha t disp
lays the names of the act ors from
Wh en the use r clic ks on an the A cto rs table in a list box.
act or's nam e, the famou lines from the
spo ke sho uld be displayed in a Lines table tha t he
second list box .
44. Wr ite a progra m tha t disp
lays the names of the film s from
Wh en the use r clic ks on a film the A cto rs table in a list box
's name, the famous lines from .
ken in tha t film sho uld be d ispl the Lin es tab le tha t were po-
aye d in a second list box .
Solutions to Practice Problem
s 10.1
1. In the abse nce of the Dist
in ct ope rato r, bo th "peso" and
"rup ee" would app ea r twic e in
2. Th e prob lem here is that the th e list box.
Se lect clause con ta ins both city.
crea te two fie lds nam ed nam e. nam e and country. name. The
qu ery wo uld try to

10.2 Editin g and Designing Database


s
In Sec ti on 10. 1, we showed how
to con nec t to a dat abase and
ma nip ula te info rma tion retriev how to use LIN Q que ries to
ed from the dat abase. In this
reco rds, delete record s, and add sec tion we lea rn how to alte r
new record s to a dat abase table.
cussio n of goo d dat abase des ign We end the sec tion wit h a di -
.

A Program to Edit the Cities Tab


le
We beg in by exa min ing a progra
m tha t edi ts the C ities table of
show how to create the progra the Megac ities dat abase; the n
m. Th e progra m, named 10- 2- we
tha t yo u downlo aded from the 1, is in the fold er Progra ms \Ch Vide o ote
compan ion web ire for this boo 10
Fig ure 10.20 sho ws the fo rm for k. Edit ing
the progra m. A ll of the co ntr datab ase>
exc ept fo r th e nav iga tion too lba o ls on the form are familia r
r doc ked at th e top of the form
and ide n t ifies its com pon ent s. . Fig ure 10. 21 sho ws the too lba
r

a_. lv1egacities
navigation ~[§D [ID
toolbar - - - - t..~l 0 of {O} • + )< C
name: Cit)• to find :
country :

pop 10:

pop2 1~ :

FIGURE 10.20 For m for the edit ing pro gram


.

Total

rT
number
of items

of {O } • •1 ~ X
_1--!-~
~~
FIGURE 10.21 Nav igat ion too lbar.
Ch apt er 10 Databases
480 •
co nte nts of the first record
t aft er the pro gra m is run. The
Figure 10.22 sh ow s the for m jus form. The Move first
es arr ang ed ver t ica lly on the left ide of the
are sho wn in the fo ur tex
t box the first record.
dis abl ed, sin ce the re are no reco rds pre ced ing ve
and Move previous bu tto
ns are s. In gen era l, the fo ur Mo
the Mo ve nex t bu tto n, the sec on d rec ord app ear the tab le is
W he n you cli ck on t rec ord of
iga te to any rec ord of the C ities table. Th e firs fro m 1
bu tto ns all ow you to nav ce a nu mb er
sec on d rec ord pos itio n 2, and so on . If you pla , th e
sa id to have po sit ion 1,
the En ter key
lba r's "C urr en t po sit ion " box and the n press the
tio n too ce, if yo u en ter 7 int o the
"C ur-
thr ough 10 in the nav iga l be displayed. For ins tan
t po siti on nu mb er wil y to ob tai n a
record ha vin g tha no th er wa
inf orm at ion for Ne w York wil l be displayed. A and the n
ren t po sit ion " box, the a c ity int o th e tex t box lab e led "C ity
to find:"
the nam e of
pec ific reco rd is to type
cli ck on the Sea rch for Cit y bu tto n .
l
I. = @] I. .S"2. .I
c::;J 1egacities

1 ofl O ~I + L

Otyto find :
name: Bombay

country : India

pop2010: 20.1

pop2015: 22
l Sea rch
forCrty
J

sta rtu p.
FIGURE 10.22 Tab le- edi tin g pro gra m at
on e o r more of
ren tly dis pla yed rec ord , jus t rep lace the va lu e in
To alte r the dat a in the cur bu tto ns.
cli ck on on e of the Move tto n ( cQa ). Th e tex t boxes
the tex t boxes and the n tab le, cli ck on the Add new bu
ord to the C itie s record, an d cli ck on
To add a new rec you type in the da ta for the new
om e bla nk . Af ter ota l nu mb er of
for the fo ur fields will bec wil l be add ed and the nu mb er in the "T
the new rec ord
on e of the Move bu tto ns,
an ge fro m 10 to 11. on the Delete bu tto n
items" box will ch rec ord from the C it ies table, cl ick
ren tly dis pla yed of items" box wi ll
To rem ov e the cur nu mb er in the "T ota l nu mb er
de let ed and the
( I'. ). Th e rec ord will be
ry is act ua lly
decrease by 1.
ere d in any way , on ly the copy of the tab le in memo
Each time the C ities table
is alt tto n ( ~ ). Note 1:
on the disk, you mu st click on the Update bu
altered. To alter the dat aba
se file e copy is always
tai ns two cop ies of the file Megacities.accdb. On
The So lu tio n Explo rer act
ually con
d copy is located in the
bin \Debug
lut ion Ex p lor er. A sec on
of the So 2: lf the changes you made
displayed near the bo tto m upd ated by the program. Note
d cop y tha t can be o appear in the pri-
folder. It is this secon (ev ery val ue in the foreig n key mu st als
ial Int egr ity updated. Note 3:
vio late the Rule of Referent m wil l cra sh wh en the database file is
le), the pro gra primary key
mary key of the oth er tab Int egr ity (no rec ord may have a null en try in its
le of En tity is
Ch ang es tha t vio late the Ru as soon as a Move bu tto n
ry key s mu st be uni qu e) cause the program to crash 2 and 3.
and ent ries for prima add re sing the issues in No
tes
ssed. Ex ercise s 10 thr ou gh 12 discuss tec hniqu es for op e rat ion of the program.
pre ter acq ua int yo u wi th the
ugh wil l bet
Th e following wa lkt hro
m na med 10- 2- 1.
1. Op en and run the progra eal the thi rd record, the
t bu tto n in the n av iga tio n too lba r tw ice to rev
2. Press the Move nex
on e fo r Ca lcu tta. rch for City bu t-
"C ity to fin d:" tex t box and the n cli ck on the Sea
the
3. Type "N ew York" into
pla y the rec ord for Ne w York.
ton to dis
10.2 Editing and Designing Databases
• 481

4. C lick on the Add new butto n in the navigation too


lbar and then enter the following data
into the ve rtical set of fo ur empty text boxes for the fie
lds: Lo Ange les, USA, 12.8, 13 .2.
5. C lick on one of the Move butto ns in the nav igatio n
toolba r. N otice that the "Tota l numb er
of items" box now shows that there are 11 reco rds.
6. Term inate and then rerun the program. N otice that
the "Tota l numb er of items" box shows
that there are 10 record s. The Megacities database file
in the bin \Debug fo lder was not
updat ed because we did not click on the Update butto n
before termi nating the progra m.
7. Redo steps 4 and 5, and then click on the Update butto
n.
8. Term inate and then rerun the program. Notic e
that the "Total numb er of items" box shows
that there are 11 records. The Megacities database file
in the bin \Debug folder was upd ated.
9. Exper iment furthe r with the program to test its other
fe atures.

Designing the Form for the Table-Editing Program


The fo llowing teps create the nav iga tion too lbar for
program 10-2-1, create the four sets of
labe l and text boxes on the left side of the form, bind
the text boxes to the nav igatio n toolbar,
and imple ment the search capab ility.

1. tart a new program and bind the C ities tab le as was done
in Sectio n 10.1.
2. Add a Bindi ngNa vigato r contro l to the form designer.
(This contr ol can be found in the All
Windows Forms or Data group s of the Toolbox.) After you
doub le-clic k on the contr ol in
the Toolb ox, a contro l named Bindi ngNa v igator l appea
rs in the comp o nent tray at the
botto m of the Form Desig ner. A lso, a nav igatio n too lbar
will appea r ancho red to the top of
the form.
3. Go to the Properties window for Bindi ngNa v igator
1, click on the down-arrow at the right
side of the Bindi ngSou rce property's Settin gs box, and
set the Bindi ngSource prope rty to
Bindi ngSo urce1.
4. Not ice that the too lbar is miss ing the Update
button . The rightm ost item on the too lbar
(see Fig. 10.23) is used to add an updat e butto n to the
nav iga tion too lbar. C lick on the
small down -a rrow on the righ t side of the rightm ost item
and then click on Button in the
drop- down li t that appea rs. A butto n show ing a moun
ta in ( o ) appea rs.

0 of {0} ~ 1>1 9}> l<. ~ click here

FIGURE 10.23 Origin al naviga tion toolba r.

5. Open the Prope rties window for the moun tain butto
n, change its name fro m ToolS tripBu t-
to nl to btnUp d ate, and se t its Tex t property to Upda te.
6. C lick on the ellipses at the right side of the Image
prope rty's Settin gs box, and then click
on th Import butto n in the Se lec t Resource dialog ue
box that appea rs. (An Open dialog
box appea rs.)
7. Browse to locate the fo lder Progr ams\ C h 10, and doub
le-clic k on the file Disk. bmp to place
its pictur e in the Selec t Reso urce window.
8. C lick on the OK butto n to change the image on btnUp
date to a diske tte ( Ji ).
9. C lick on the Data menu in the Visua l Basic Toolb ar,
and then click on Show Data Sources.
A Data ources window show ing the names of the tab
les in the database will appea r in the
location occupied by the Solut ion Explo rer window.
10. Double-cl ick on Cities in the Data Sources windo
w to ob tain the display in Fig. 10.2 4.
482 • Chap ter 10 Databa es

Data Sources
(?1+
J
4 ~ Megaciti esDataSet

abl nam e
abl count ry
abl pop2010
abl pop2015
Coun tries

FIGURE 10.24 Data Sourc es wind ow.

a label and text box for the field name appear on


11. Click on name and drag it onto the form. Both
the text box will be named Nam eTextBox .
the form. The label will be named Nam eLabel and
field . The left side of the form has now been
12. Repe at Step 11 for each of the othe r three
d to the nav iga tion toolbar.
creat ed and the four tex t boxes have been boun
in the usua l way.
13. Crea te the rema ining controls in Fig 10.20

Writing the Table-Editing Program


is given a pos ition numb er from 1 through 10
We have seen that each record of the C ities table
oses, each record has an index num ber that
by the navig ation too lbar. For programm ing purp for
for Bombay has index num ber 0, the record
ranges from 0 throu gh 9. That is, the record Posit ion prop erty
BindingS ource contr ols have a
Buen os Aires has index numb er 1, and so on.
and a Find meth od that retur n index numb ers.
the reco rd whose fields are displayed as the
Assume the program is runn ing. Let's refer to
curr ent recor d. At any time, the va lue of
Bind ingS ourc el.Po sitio n
atten tion to the fact that the Pos ition prop erty
is the index of the curre nt record. Pay particu lar
gives the index, not the position!
If n is a nonn ega tive integer, then the state ment
Bind ingS ourc el.Po sitio n = n

makes the record of index n the curre nt reco rd.


in the C ities table, then the va lue of
If strVar is a strin g variab le whose va lue is a city
)
Bind ingS ourc el. Find ( "nam e" , s t rVar
lue of strVar is not a city in the table, then the
is the index of the record for that city. If the va
meth od retur n the same value , 0, both for
Find meth od returns the va lue 0. Note : The Find
table .
Bombay and for a city not present in the C ities

Assume that the C ities table


-./ Example 1 The following program ed its the C ities table.
boxes, and Search for City butto n have been
has been bound, and the navig ation toolbar, text
inside the Load even t procedure is optio nal.
creat ed as described above. The second state ment
ighte d when the program is first run. In the
It preve nts the city Bombay from being highl
ments that refe r to currentCity are optio nal. If
btn earch _Clic k even t procedure, the two state
record for the first city (in thi case Bombay)
they are omit ted, the program will display the
ment s are self-explan atory.
after an unsuccessful earch. The rema ining state
10.2 Editing and Designi ng Databases
• 483

OBJECT PROPERTY SETTING


a:; Megac it ies GJ[ ID@ ]
frmC ities Text Megacities
0 of {0 } ~ X NameL abel Text name:
Otytofind : Na meTextBox
name :
Countr yLabel Text country:
country: Countr yTex tBox
pop 1 : Pop2010Labe l Text pop2010:
Pop20 1OTextBox
pop2 15:
Pop2015Label Text pop201 5:
Pop2015TextB ox
lblCity Text C ity to find:
•·,i! BindingNaviga orl
~ Bindin gSourcel txtCity
btnSea rch Text Search for ity
~ Meg ac i iesDa-aSe @ G iesTabl • dap er

Privat e Sub frmCi ties _ Load( ... ) Handle s MyBase


.Load
Me .Citie sTabl eAdap ter.Fi ll( Me .Mega citiesD ataSet
.Citie s)
End Sub

Privat e Sub btnUp date_ Click( .. . ) Handle s btnUp


date.C lick
'These two lines update the databa se file n the
bin Debug folder .
Bindin gSour cel.En dEdit( )
Cities Table Adapt er.Upd ate(M egacit iesDa taSet. Cities
)
End Sub

Privat e Sub btnSea rch_ Click( ... ) Handle s btnSe


arch.C lick
Dim curren tCity As String = NameT extBox .Text
If txtCit y.Tex t <> "" Then
Bindin gSour cel.Po sition = Bindin gSour cel.Fin d(
"name" , txtCit y.Tex t)
If NameT extBox .Text <> txtCit y . Text Then
Messag eBox .Show( "City not found. " )
Bindin gSour cel.Po sition = Bindin gSour cel.Fin d(
"name" , curren tCity)
End If
Else
Messag eBox .Show( "You must enter the name of a
city . " )
End If
End Sub

Principles of Database Design


Good relat ion al databa se des ign is more of an a rt than a sc ience.
H oweve r, the des ign e r sh o uld
keep in mind certain fundam en ta l guid elines.
• Data should often be stored in their smalles t jJarts.
For instan ce, c ity, state, and zip code are usually best stored in three
fi elds. So do ing will allow
you to eas ily sort a ma iling by zip code or target a mailing to the
res iden ts of a specific city.
• Avoid redundancy .
The process of avo iding red und ancy by sp litting a table into two
or more re la ted tables is
ca lled data norma lizatio n. For instanc e , the excess ive duplica
tion in Tab le 10.4 can be
avo ided by rep lac ing th e table with the two re lated tab les l O.S(a)
and l O.S(b) .
484 • Chapt er 10 Databases

lt!!:JIII•I I A table with redundant data.


Cours e Sectio n Name Time Credit s Prereq uisites

1001 Intra to Databases MWF 8-9 3 CS l Ol


CS 102
1002 lntro to Database MWF 1-2 3 CS 10 1
CS 102
lntro to Database MWF 2-3 3 CS 10 1
CS 102 1003
CS102 1004 Intra to Databases MWF 3-4 3 c 101
Visual Ba ic MWF 1-2 4 CS200
CS105 1001

Cours e Sectio n Time


CS102 100 1 MWF 8-9 lf!1:JIII•I1U)M
CS102 1002 MWF 1-2 Cours e Name Credi ts Prereq uisites
CS102 1003 MWF 2-3 3 CS10 1
CS 102 lntro to Databases
CS102 1004 MWF 3-4
CS l OS Visual Bas ic 4 CS200
CS 105 100 1 MWF 1-2

• Avoid tables with intenti onally blank entries.


use space ineffic iently. Tab le 10.6,
Tab les with entries that are intent ionall y left blan k
has an excess ive numb er of blank
which serves as a direct ory of fac ulty and stude nts,
dealin g with just one of the gro ups.
entries. The tab le hould be split into two tab les, each

lm:JII(eiJ A table with an excessive number of blank entries.


Date Office Credi ts
Hired Dept Numb er gpa Earne d
Name ssn Classi ficatio n
3.7 78
Sarah Brown 816-3 4-9012 studen t
facult y 9/1/02 bio logy Y-30 14
Pat Riley 409-22-1234
faculty 9/ 1/05 math T- 2008
Joe Russo 690-32- 1108
3.2 42
Juan Lopez 509-43-41 10 studen t

• Strive for table cohesion .


in the table are conne cted.
Each tab le should have a bas ic topic to which all the data
• Avoid fields whose values can be calculated from existing fields.
and area of count ries, then there is
For instan ce, if a tab le has field s for both the popu lation
no need to includ e a field for the popul at ion density.

Comments
1. Since the name fi eld of the C ities tab le is the
prima ry key, each record of the table must
ase does not requir e thatvalues
have a va lue ass igned to its name field. Howeve r, the datab
be assign ed to the other three field s.
on the left side of the form have the
2. In Example 1, the four pairs of labels and text boxes
were dragged from the Data Sourc e
names given to them by Visual Bas ic when the fields
if you like. For instan ce, Coun -
window to the Form Designer. Yo u can change the e names
s of the contr ols Bindi ngSource1
tryTextBox can be changed to txtCountry. Also, the name
ingfu l ones, such as C itiesB inding-
and Bindi ngNa v igato rl can be changed to more mean
Source and C itiesB indingNav igator.
10.2 Editing and Designing Databases
• 485

Practice Problems 10.2


1. Ca n a record for any city be added to the C
ities table?
2. Can a record fo r any coun try be added to the Coun
tries tab le?
3. Can any record in the C ities table be de leted?
4. Can any record in the Coun tries tab le be de leted?

In Exerc ises 1 throu gh 8, carry out the following


tasks on th e Citie s table with the progr am
from Exam ple 1.
1. C hange the name of the city Bombay to Mum
bai.
2. Add the following record: Karac hi, Pakis tan, 13.1,
14.9.
3. Use the Searc h for City butto n to find the reco rd
for Mex ico C ity.
4. Find the record for the city in posit ion 8.
5. Delet e the record for Delhi .
6. Add a record that will ra ise an excep tion when
you try to Upda te the database file.
7. Add a reco rd that will raise an excep tion as soon
as yo u move to anoth er record.
8. Add a record with ome empt y fie lds.
9. Cons ider Example 1. Let strVar be a string varia
b le. G ive a cond ition that will be True if
the va lue of strVar is not the name of a city in the
C ities tab le.
10. Cons ider Example 1. If you viola te the Rule of
Referentia l Integ rity, an excep tion is ge ner-
ated when you click on the Upda te butto n. Rev ise
the btnU pdate _Ciic k even t procedure so
that the program will not crash when the princ
iple is violated. Note : The name of the
excep tion is O leDB .OleD bExceptio n.
11. Modify Example 1 so that a Rule of Refer
entia l Integ rity vio lat ion is caugh t as soon as an
improper coun try is entered into the co untry text
box.
12. Modify Examp le 1 so that a Rule of Entit y Integ
rity viola t ion is caugh t as soon as the use r
leaves an empt y Na meTextBox or a Name TextB
ox whose entry dup lica tes a city from
anoth er record.

Exer cises 13 throu gh 18 refer to the datab ase


Movies.accdb discu ssed in the exerc ises for
Secti on 1 0.1.
13. Write a program that can be used to make
chan ges to the Lines tab le. (The re is no need to
inclu de a Searc h capab ility.)
14. Write a program that can be used to make
chan ges to the Acto rs table. (The re is no need
to inclu de a Searc h capab ility.)
15. Use the program creat ed in Exercise 13
to chan ge the famous line "Here's looking at you
kid." to the line "Play it Sam." Both lines are from
the same film.
16. Use the program creat ed in Exercise 14 to
add th e fo llow ing record to the Acto rs tab le: Pat-
ton, George Scott .
17. Why can't the following reco rd be added
to the Lines tab le: "Hou ton, we have a prob-
lem.", Apo llo 13?
18. Why can't the following reco rd be delet ed
from the Acto rs tab le: Casa blanca, Hum phrey
Bogart?
486 • Chap ter 10 Databases

19. Elim inate th e redu nd a ncy in Ta ble 10. 7.

ltt1:J!II•Q A table with redundancies.


city state state Capi tal
name address
Seattle Wash ingto n O lymp ia
R. Mye rs 3 Map le St.
Wash ingto n O lymp ia
T. Murphy 25 Main St. Seattle
Baltimore Maryland A nnapolis
L. Scot t 14 Park Ave.
Wash ingto n O lymp ia
B. Jones 106 5th St. Seattle
Maryland A nnapo lis
29 7th Ave. Baltimore
W. Smi th Sprin gfield
4 Flower Ave. C hi cago Illino is
V. Miller

a table of mem bers of the U.S . H o use of R epresent a-


20. Elim inate the redu nd ancy in Table 10.8, 's tate. )
the num ber of colleges in the represent ative
tives. (Not e: The va lue of numColleges is

lt!1:J!IIel:l Atable with redundancies.


state Pop numC olleg es
name state party
10.2 97
]. Dingell Michigan. Democ ratic
7.8 83
E. Can tor Virginia Republ ican
7.8 83
]. Moran Virgini a Democratic
5.8 97
J. Sarbanes Maryland Democratic
5.8 97
S. !-!oyer Maryland Democrat ic
7.8 83
F. Wolf Virginia Republi can

t as of Ja n -
ra ms \ C h10 \Da tabases fo ld er was c urren
21. The data base ]usti ces.a ccdb in the Prog been appo inted since t h en ,
a nd n ew ju tices have
uary 1, 2010 . If some justi ces h ave retir ed
upda te the da tabase.

Solutions to Practice Problems 10.2


r ing in the Cou ntri es table.
1. No. The city must be fro m a coun try appea
2. Yes.
3. Yes.
Indo nes ia can be delete d.
4. No. On ly the records fo r Pak ista n and

CHAPTER 10 SUMMARY
con ta ining
d in a recta ngul a r array, with each row
1. A table is a grou p of d ata item s arran g (co lumn ) is
row is ca lled a record. Each categ ory
the ame categ ories of info rmat io n . Each .
o n e o r mo re tab les tha t are usua lly re lated
ca lled a field. A database is a co llect io n of
a tab le of a d atab ase to a p rog ra m .
2. A BindingSo urce control can be used to bind
iew
r Explorer in Visu a l Stud io ca n be used to v
3. Database Explorer in V B Express and Serve
conn ected to a p rog ra m .
t he table fro m a d atab ase that h as been
ion retri eva l from a ta ble.
4. LINQ can be used to set c rite ri a fo r info rmat
disp layed in a
the exec utio n of a U NQ q uery can be
5. A sequ en ce of reco rds resul t ing fro m
DataGridView control.
Programmin g Projects
• 487

6. A jJrimary key is a fie ld o r set


of fields tha t uniq u e ly id enti fies
Rule of Entity Integrity stat e tha t no eac h reco rd of a ta ble. The
reco rd can h ave a nu ll ent ry in
ent ries for prim ary keys mu t be a prim ary key and tha t
uniq u e. A foreign key is a fie ld or
tha t refe rs to a prim ary key in an s t of fie lds in o n e tab le
oth er tab le. The Rule of Referen
valu e in the fore ign key mus t a tial Integrity stat es tha t eac h
lso app ear in the pr ima ry key in
the re late d tab le.
7. The Join operator links two tab
les based o n ma tchi ng fie ld valu
es.
8. A navigation toolbar, whi ch
ha icon s o n its but ton s sim ila r
be used to v iew reco rds, a lter to th ose on a DV D play er, can
reco rds, de lete reco rds, and add
tabl e. A BindingNavigator control n ew reco rds to a data bas e
bind s the n av igation tool bar to
Sou rce con trol. earc hin g for reco th e tab le via a Bin ding -
rd s in the tab le can be fac ili tate
erty a nd the Find methods of the Bin d wit h th e Position prop-
ding Sou rce con trol.
9. Som e fun dam enta l des ign prin
cipl es h e lp data ba e des igne rs c
reat e effic ient da tabases.

CHAPTER 10 PROGRAMMING PRO


JECTS
1. The data bas e Mic rola nd.a ccd b
is ma inta ined by the Mic ro land
mai l-or der com p uter-sup p ly com Com put e r W a reh o use, a
pan y. Tab les 10.9 th ro ugh 10.11 Vide oNo te
in the data ba e. The tab le C usto sh ow part s of thre e tab les
me r iden tifie s eac h c usto me r by Rich ard's
in add it ion to the nam e and add a n ID num ber a nd gives,
ress , the tota l a mo unt of pur cha catering
prio r to toda y. The tab le Inv ent ses dur ing the cur ren t yea r (Ho mework)
o ry id ent ifies eac h pro d uct in stoc
give , in add itio n to its des crip tion k by an 10 num ber and
a nd pric e (per uni t) , the qua nt ity
nin g of the day. The tabl e Ord in stoc k at t h e beg in-
ers gives the o rde rs rece ived toda
the end of the day. Wri te a pro y. S upp ose tha t it is n ow
gram tha t uses the thre e tab les
tasks. to do the fo llow ing two

IM:J!II•D First three records of the Customers tabl


e.
Cus tlD Nam e Stre et City
1 Am tPur cha ses
Michae l Smi th 2 Park St
2 Dallas, TX 75201
Brittany Jon es 5 2nd Ave. 234.50
3 Tampa, FL 33602 121.90
War ren Pease 7 Map le St. Boston, MA 02 101 387 .20

lf4:l!ll•ll•l First three records of the Inventory tabl


e.
item lD description
price qua ntit y
PL208 Visua l Basic
SW 109 89.50 12
MS Office Upgrade
HW913 195 .95 2
Sca nne r
49.95 8

lf4:1!11•111 First four records of the Orders table.


cus tlD item lD
qua ntit y
3 SW 109
1
PL208
1 3
HW 913
2 2
PL208
488 • Cha pte r 10 Databa es

se tha t mu st be reo rde red to


s tha t are o ut of sto ck and tho
(a) D isp lay in a list box the item
10.2 5(a ).
satisfy tod ay 's o rde rs. See Fig.
the day. Eac h bill sho uld
in a list box bill s for all custom ers wh o ord ered dur ing
(b) Dis play and to ta l cos t of the
cus tom er's nam e, add ress, items o rd ere d (wi th cos ts),
show the
o rde r. See Fig. 10.25( b) .

[= 1 @J 1- n . - 1 c_. •1icro land


D -' •1icro land

II
Bills for Today's
I Out of Stock
~ems
Bills for Today 's J
Orders .
Out of Stock
~ems
Orde rs .

Mich ael Smith


Here are the items that are out of 2 Park St
inventory or m1Jst be reordered. Dall as . TX 75201

The numbers shown give the 3 Visual Basic-Stand ard S21i8 .


.
minimum reorder quantity requ ired 2 PaperPort ix
2 Kurzwell VD ICE for Nin SASB.
S1N1 01 2 Kurzwell VO ICE for Win Total Cost : ~ 1.327.
SIN109 0 MS Office Upg rade
SW 5l4 5 T-Shirt Mak er
Brittany Jones
5 Second A.ve
Tampa . FL 33fi 2
.
1 Visual Basic-St and ard S~
VO ICE for 'Nin SLZSt.
1 Kurzwell __...- I
Total Cost: 5318.5

(b)
(a)
ect 1.
FIGURE 10.25 Ou tpu t of Pro gra mm ing Pro j

ent s and G rades .


ch er ma inta ins a dat aba e con ta inin g two tab les -S tud
2. Grade Boo k. A tea G rades tab le
le h as thr ee fi eld s: stud ent iD , lastName, and firstNa me. Th e
Th e S tud ent s tab . A t the beg inn ing of the
h as fo ur fields: studentiD, firs
tExam , secondExam , and finalE xam
o rd fo r eac h stud ent in a class,
Stu den ts tab le is fill ed in co mp lete ly wit h a rec
sem est er, the s o nly the stu d ent 's ID
es tab le has a rec ord for eac h stud ent tha t con tain
and the G rad db fro m the fo ld er
te: Th e dat aba se is con ta ine d in th e fil e G rad ebo ok. acc
num ber. (No process the
Wr ite a pro gra m tha t a llow s t he inst ruc tor to rec o rd and
C h lO\ Da tabases. )
ing:
progra m h ould do the fo llow
grades fo r the sem es ter. Th e
(a) Use a naviga tion too lba
r to fill the G rad es table.
l sho win g th e nam e
des h ave bee n ent ere d , display a Da taG rid View con tro
(b) Aft e r all gra o uld be cal cu-
and his or her em este r ave rage. Th e se mes ter ave rage sh
of eac h stud ent Fig. 10. 26.
Exa m + 2 · fina lEx am )/4. See
lated as (firstE xa m + second
Progra mming Projec ts
• 489

a... Crad e Boo l= l @) l~ J


4 of 5
[ Display Semester Grades j
student ID: GG-567876
full Name semGra de

first Exam: 8
.AJ Jones B5
George Jackson 93
second oom: Lauren Smith 77
Grace Green &5
final Exam : &5
Fred Adams 9

FIGURE 10.26 Possib le outcom e of Progra mming Projec t 2 .


Ob jec t . . Or ien ted
Programming

11.1 Classes and Objects 492


• Objec t Const ructor s • Auto- Imple mente d Properties
11.2 Working with Objects 507
• Arrays of Objec ts • Events • Conta inmen t
11.3 Inheritance 518

• Polymorphism and Overr idi ng • Abstr act Prope rties, Meth


ods, and C la ses
Summary 535

Programming Projects 536

491
Programming
492 • Cha pte r 11 Object- Ori ent ed

11.1 Classes and Objects


quality, or act.
or name a person, place, thin g,
nou n A wo rd use d to den ote
occ urre nce.
expresse existe nce , action , or
ver b Th at par t of spe ech tha t lim iting, qual-
class of wor ds use d to mo dify a noun or oth er sub stan tive by
adj ect ive A ny of a
ifying, or specify ing. of the English Language
The American Heritage Dictionary
are the nouns in your
thu mb for obj ect -or ien ted programming is tha t classes
"A good rule of t the nou n does.
ble m. Th e me tho ds in you r obj ect co rrespond to verbs tha
ana lys is of the pro
tha t describ e the noun."
Th e properties are the adj ect ives Gary Cornell & David]ezak

industries has
in the fina nci al, scie ntif ic, eng ineerin g, and softwa re des ign in
Practical exp erie nce tho dologies. As programs grow
ealed som e d iffic ulti es wit h trad itio nal program design me the sam e pro jec t
rev working on
bec om e mo re com ple x, and as the num ber of progra mm ers e inc rea ses
size and thr oughou t the cod
enc ies and inte rrelatio nsh ips
inc reases, the num ber of depend pro gra mmer in one place may hav
e ma ny effects,
ll cha nge mad e by one ripple
expone ntia lly. A sma er plac es. Th e effects of this cha nge may
nde d, in ma ny oth
bot h inte nde d and uni nte l of cod e alo ng the way.
ire pro gra m, req uiri ng the rew riti ng of a grea t dea
thr oug hou t the ent uni t, as mu ch imple-
on to this pro ble m is "da ta hid ing" wh ere, wit hin a
A par tial so luti erlying object-
pos sib le is hid den . Dat a hid ing is an imp ort ant prin cip le und
me nta tion det ail as a and procedures tha t act on
the
nte d pro gra mm ing . An obj ect is an encapsula t ion of dat obj ect can per -
orie tha t the
gra mm er usin g an obj ect is con cerned onl y wit h the tasks ced ure s
data. A pro res and pro
ram ete rs use d by the se task s. Th e det ai ls of the dat a stru ctu
fo rm and the pa
are hid den wit hin the object. us: con tro l obj ect s and code obj
ects. Examples of
Tw o typ es of objects wi ll be of con cern to ls tha t can be cre ate d
,t.fP
tex t box es, list box es, but ton s, and all the oth er con tro
con tro l obj ects are class blo ck beg inn ing
fa r, mo st of our pro grams have con tained a sin gle
from the Too lbo x. So d C lass." A cod e
Vide oNo te
as "Pu blic C lass frm Nam e" and end ing wit h the line "En
a line suc h larl y to a
C las>cs and ohj cc ts wit h
e of a use r-de fine d typ e, call ed a class, wh ich is defined imi
object is a specifi c instanc
s blo ck of the form
structure, but in a separate clas

Cla ss Cla ssN arn e


sta tem ent s
End Cla ss
cke t app earing to the
is del ine ate d in the Co de Edi tor by an elo nga ted left bra
Each class blo ck ds, and eve nts.
con trol obj ects and clas s object s have properties, me tho
left of the block. Bo th nifes tati ons,
tha t con tro l obj ects are pre defined and have physica l ma
Th e ma in differences are
ects. ln this section, wh en we
as the pro gra mm er mu st cre ate the class blo cks for cod e obj
where ect."
a qualifier, we mea n "code obj
use the word "ob ject " wit hou t Too lbox, a new tex t box is created.
dou ble -cli ck on the Tex tBox ico n in the
Wh ene ver you , me thods, and
t box is a sep a rate ent ity, the y all have the same properties
Alt hou gh eac h tex the TextBox
said to be an ins tan ce of the class Tex tBox. In so me sen se,
events. Eac h tex t box is es. Wh en you loo k at the
is a tem pla te or blu epr int for creatin g tex t box
ico n in the Too lbo x of the window read some-
a tex t box , the drop-down list box at the top
Properties win dow for name of the con tro l
x tBo x l Sys tem .W ind ows .Fo rms.Tex tBox." TextBox l is the
thin g like "Te or invoke
an ins tan ce of the cla "Te xtBox." You can 't set properties
object and it is said to be
tho ds of the specifi c tex t
tBo x clas s; yo u can onl y set properties or in voke me
me tho ds of the Tex n a cla s and a coo kie
inst anc es of the clas s. Th e analogy is ofte n made bet wee
boxes tha t are
11.1 Classes and Objects • 493

cutter. The cookie cutter is used to create cookies that you can eat, but you can't eat the cooki e
cutter.
Object-oriente d programs are popu lated with objects that ho ld data, have propertie ,
respond to methods, and raise events. (The generation of eve nts will be discussed in the nex t
section.) Six examples of objects are as follows:

1. In a professor's program to ass ign and display semester grades, a student obj ect might ho ld
a single student's name, social secu rity number, midterm grade, and final exam grade. A
CalcSemGrad e method might calculate the stud ent's se mes ter grad e. Events might be
raised when imprope r data are passed to the object.
2. In a payroll program, an emp loyee object might hold an employee's name, hourly wage, and
hours worked. A CalculatePay method wou ld te ll the object to calculate the wages for the
current pay period.
3. In a checking accou nt program, a check register obj ect might have methods that record
and tota l the checks written during a certain month, a deposit slip object might record and
to tal the depos its made during a ce rtain month, and an account object might keep a run-
ning total of the balance in the account. The account object wou ld raise an event to alert
the bank when the balance got too low.
4. In a bookstore inven tory program, a tex tbook obj ect might hold the name, author, quantity
in stock, and wholesale price of an individual tex tbook. A CalculateRetailPrice method
might instruct the textbook object to calculate the selling price of the tex tbook. An event
co uld be raised when the book went out of stock.
5. In a game program, an airplane object might hold the location of an airplane. At any t ime,
the program could tell the object to display the airplane at its current location or to drop a
bomb. An eve nt could be raised each time a bomb was released so that the program cou ld
determine if anything was hit.
6. In a ca rd ga me program, a card object migh t hold th e denomination and uit of a spe-
cific ca rd . An ldentifyCa rd method might return a string such as "Ace of Spades." A
deck-of-ca rd s objec t might cons ist of an array of card objects and a ShuffleDeck method
that thoroughly shuffl ed the deck. A Shuffl ing event might indicate the progre of the
shuffle.

An importa nt object-o ri ented term is class . A class i a te mplate from whic h objec ts
a re c reated. The class spec ifi es the propert ies and methods that will be co mmon to a ll
objec ts that are insta nces of that class. C lasses a re fo rmulated in class bloc ks. An object ,
whi ch is an insta nce of a clas , can be c rea ted in a program with a pair of state me nts of
the form

Dim objectName As ClassName


objectName = New ClassName (argl, arg2, ... )

The first of these two lines of code declare what type of obj ect the variable wi ll refe r to. The
actual object does not exist until it is crea ted with the New keyword , as done in the second line.
This is known as crea ting an instance of an object and is where an obj ect is actually created
from its class. After this second line of code execute , the object is then ready for use. The first
line can appear either in the Declarat ions section of a program (to declare a class-leve l vari-
able) or inside a procedure (to declare a loca l va riable ). The instantiation line can appear only
in a procedure; however, any object variable can be instantiated when declared (as either class
leve l or local) by using the single line

Dim objectName As New ClassName(ar gl, arg2, ... )


494 • Chapter 11 Object-Ori ented Programming

In a program, properties, methods, and events of the obj ect are accessed with statements of
the form shown in the following tab le:

TASK STATEMENT

Assign a va lue to a prope rty ob j e c tName . propertyN ame = v alue


Assign the va lu e of a property to a variable v arName = ob je ctName.p ropert y Nam e
Ca rry out a method ob j ec t Name.me t hodName (argl , .. . )
Raise an event Ra i seEvent e ventName

The program in Examp le 1 use a class named Student to calculate and d isplay a student's
semeste r grade. The informatio n sto red by an object of the type Student consists of a student's
name, social security number, and grades on two exams (midterm and final). This data is stored
in variables declared with the sta tements
Private m name As String 'Name
Private m s sn As String 'Social security number
Private m midt erm As Double 'Numeric al grade on midterm exam
Private m f i nal As Double 'Numeric al grade on final exam

The word Private guarantee that the variab l s cannot be accessed directly from outside the
object. In object-ori ented programming terminology, these variables are called member vari-
ables (or instance variables). We wi ll fol low the common conventio n of beginning the name
of each member var iable with the prefix "m_". Each of these variables is u ed to hold the value
of a property. However, instead of being accessed directly, each member variab le is accessed
indirectly with a property bloc k. For instance, the fo llow ing property block cons ists of a Get
property procedure to retr ieve (or read ) the va lue of the Name property and a Set property pro-
ced ure to assign (or write) the value of the Name property:
Public Property Name () As String
Get
Return m name
End Get
Set (ByVal v alue As String )
m name = v al u e
End Set
End Property

In a property block, additiona l code can be add ed 'after the Get and Set statements to va li-
date the data befo re they are returned or sto red. T he word Public allows the property to be
acces ed from outside the code for the Student class block. For instance, the Name property can
be accessed by code in the form's class block. On the other hand, since the member va riables
were declared as Private, they cannot be accessed di rec tly from code in the form's block. They
can be accessed on ly through Property procedures that allow values to be checked and perhaps
modified. A lso, a Property procedu re is able to take other steps necess itated by a change in the
value of a member variable.
A property block needn't contain both Get and Set property procedu res. For instance, the
block
Public WriteOnl y Property Mid t erm() As Double
Set (ByVal v al u e As double )
m mi d term = value
End Set
End Property

specifies the Midterm property a "write only." This property could be specified to be "read
only" with the block
11 .1 lasses and Objec ts
• 495

Publ ic Read Only Prop erty Midt erm ( )


As Doub le
Get
Retu rn m_ midte rm
End Get
End Prop erty
Meth ods are const ructed with Sub or Func tion proce
dures. A Func tion procedure is used when
the meth od return s a value; otherwise a Sub proce
dure wi ll suffice. For instartce, the meth od
Ca lcSemGrad e, whic h is used to calculate a stud
en t's semeste r grade, is crea ted as follows:
Func tion CalcS emGr ade() As Strin g
Dim grad e As Doub le
grad e = (m_ midte rrn + m_ final ) I 2
grad e = Math .Rou nd(gr ade) 'Roun d the
grad e.
Sele ct Case grad e
Case Is >= 90
Retu rn "A"
Case Is >= 80
Retu rn "B"
Case Is >= 70
Retu rn "C"
Case Is >= 60
Retu rn "D"
Case Else
Retu rn "F"
End Sele ct
End Func tion
An objec t of the type Stude nt is declared in the fonn's
code with a pair of statements uch a
Dim pupi l As Stud ent 'Dec lare pupi l as an obje ct of type
Stud ent
pupi l = New Stud ent () 'Crea te an insta nce of type Stud ent
Afte r these two state ment s are execu ted, prope
rtie and meth ods can be utilized with tate-
ment s such as
pupil .Nam e = "Adam s, Al"
'Assi gn a valu e to m_ name
txtB ox.te xt = pupil .Nam e
'Disp lay the stud ent's name
lstBo x.Ite ms.A dd(p upil. Calc SemG rade)
'Disp lay seme ster grad e
The first state ment ca lls the Set prope rty proced
ure for the Nam e prope rty, the secon d state-
ment calls the Get prope rty proce dure for the Nam
e prope rty, and t he th ird state men t calls the
meth od CalcS e mG rade.

Example 1 The follow ing program uses the class Stude nt to


ca lcula te and display a stu -
dent' se meste r grade . The stru cture Perso n in frmG
rades is used by the btnD isplay _Clic k pro-
cedur e to place infor matio n into the DataG ridVi
ew contr ol.

a:} Seme ster Grade

Name:

SSN : _ -_ -_ Midterm : Anal:

£nter Information ] ...


[ __Qi_s_
· pl_a)_' G
_ ra
_ de_ ___,] [~. . __Q_u_it -~
496 • Chap ter 11 Obje ct-Oriente d Programm ing

PROPERTY SETTING
OBJECT

fr mG rades Text Semester G rade


lblNa me Text Name:
txtNa me
lblSS N Text SSN:
mtbS SN Mas k 000-00-0000
lblMi dterm Tex t Midt erm:
tx tM idte rm
lblFin a l Tex t Fina l:

txtFin al
Tex t & En te r Info rmatio n
btnEn rer
Tex t & Display G rade
btnD isplay
Text &Qu it
btnQ uit
dgvG rades Row H ead rsVisible False

Publ ic Clas s frrnG rades ent


Dim pupi l As Stud ent 'pup il is an obje ct of clas s Stud
ispla y Clic k
Stru ctur e Pers on 'for use in btnD
Dim name As Strin g
Dim socS ecNum As Strin g
Dim semG rade As Strin g
End Stru ctur e
Hand les btnE nter .Clic k
Priv ate Sub btnE nter_ Clic k( .. . )
pupi l = New Stud ent () Crea te an insta nce of Stud ent.
boxe s.
Read the valu es stor ed in the text
pupi l.Na me = txtN ame. Text
pupi l.So c SecN um = mtbS SN. Text
xt)
pupi l.Mi dterr n = CDbl (txtM i dterr n.Te
pup il.Fi nal = CDbl (txtF inal .Tex t)
'Cle ar text boxe s and list box
txtN ame. Cle ar ()
mtbS SN. Clea r ()
txtM idterm.Cl ear( )
txtF inal . Clea r( )
stud ent have been reco rded .
Noti fy user that grade~ for the
." )
Mess ageB ox . Show ( "Stu dent Reco rded
End Sub
) Hand les btnD ispla y.C lick
Priv ate Sub btnD ispla y_ Clic k( ...
Dim pers ons( O) As Pers on
pers ons( O) .nam e= pupi l .Nam e
cNum
pers ons( O) .socS ecNu m = p u pil.S ocSe
= pupi l . CalcS emG rade
pers ons( O) .sem Grad e
one In pers ons
Dim quer y = From some
ecNu m, some one . semG rade
Sele ct some one.n ame, some one .socS
dgvG rade s. Data Sour ce = quer y.To List
dgvG rades .Cur rent Cell = Noth ing
ext = "Stu dent Name "
dgv Grad es.C o lumn s( "nam e" ) .Hea derT
derT ext = "SSN "
dgvG rade s. Colu mns( "socS ecNu m" ) .Hea
derT ext = "Gra de"
dgvG rades .Colu mns( "sem Grad e" ) .Hea
End Sub
11 .1 C lasses and Objects
• 497
Priva te Sub btnQu it_ Click ( ... ) Handl es btnQu
it.Cli ck
Me .Clos e()
End Sub
End Class 'frmG rades

Class Stude nt
Priva te m name As Strin g 'Name
Priva te m_ ssn As Strin g 'Soci al secur ity numbe r
Priva te m midte rm As Doubl e 'Nume rical grade on midte rm exam
Priva te m final As Doubl e 'Nume rical grade on final exam

Publi c Prope rty Name( ) As Strin g


Get
Retur n m name
End Get
Set (ByVa l value As Strin g )
m name = value
End Set
End Prope rty

Publi c Prope rty SocSe cNum( ) As Strin g


Get
Retur n m ssn
End Get
Set (ByVa l value As Strin g )
m ssn = value
End Set
End Prope rty

Publi c Write Only Prope rty Midte rm() As Doubl


e
Set (ByVa l value As Doubl e )
m midte rm = value
End Set
End Prope rty

Publi c Write Only Prope rty Final () As Doubl


e
Set (ByVa l value As Doubl e )
m_ final = value
End Set
End Prope rty

Funct ion CalcS emGra de() As Strin g


Dim grade As Doubl e
grade = (m_ midte rm + m_ final) I 2
grade = Math .Roun d(grad e) Round the grade .
Selec t Case grade
Case Is > = 90
Retur n "A"
Case Is > = 80
Retur n "B"
Case Is >= 70
Retur n "C"
Case Is >= 60
Retur n "D"
ming
498 • Cha pter 11 Object- Orie nted Program

Cas e Els e
Ret urn "F"
End Sel ect
End Fun ctio n
End Cla ss 'Stu den t
, "87"), clic k on the
h as "Ad ams, Al", "123 -45-678 9", "82"
[Ru n, ente r the data for a stud ent (suc Grade button to
to the obj ect, and click on the Display
Enter Information butt on to send the data
rity num ber, and semeste r grad e.]
display the stud ent's name, soci al secu

a;} Se mes te r Grad e


l = I @) l,..tJ "J
Name:

- -
- - Midterm : Rnal:
SSN : - -

[ Enter Inform ation


ll Display Grade 1[ Quit
l
SSN Grade
Student Name -
123-45-67&9 8
J\dams . AJ

are u ed to crea te a class:


In sum mary, the follo win g six reps
is to beco me an object.
1. Iden tify a thing in your program that
to have. (As a rule of
hod s that you would like the obj ect
2. Det erm ine the properti es and met ns.)
, and met hod s sho uld perform ope ratio
thum b, prope rties sho uld access data
s is plac ed in a clas
for the obj ect. The cod e for the clas
3. A class will serv e as a template
bloc k of the form
Cla ss Cla ssN ame
stat eme nts
End Cla ss
with a tate men t of
2, declare a priv ate member vari able
4. For each of the propertie s in Step
the form
aTy pe
Pri vat e var iabl eNa me As Dat
ws direct acces to
with the key word Public, whi ch allo
Member vari ables can be preceded side red poo r pro-
e in the form. H owever, this is con
the member va riables from the cod , we can enfo rce
erty proc edures to upd ate the data
gram min g prac tice . By usin g Set prop
con stra ints and carr y out validati on.
G et and /or Set pro-
in Step 4, crea te a Pro pert y bloc k with
5. For each of the member vari ables the procedu res are
res to retri eve and as ign va lues of the vari able . The gen eral fo rms of
cedu
me( ) As Dat aTy pe
Pub lic Pro per ty Pro per tyNa
Get
(Po ssi bly add itio nal cod e)
Ret urn var iabl eNa me
End Get
pe)
Set (By Val val ue As Dat aTy
add itio nal cod e)
(Po ssib ly
11 .1 C lasses and O bj ects • 499

variabl eName val ue


End Set
End Propert y
In the Get or Set code, addition al code can be added to prevent the object from storing
or
returning invalid or corrupted data. For exa mple, an If block cou ld be added to only
allow
va lid social security numbers, alerting the user in the event of an invalid number.
6. For each method in Step 2, create a Sub procedur e or Function procedur e
to carry out
the task.

Example 2 The following modifica tion of the program in Example 1 calculates semester
grades for students who have regi tered on a "Pass/Fail" ba is. We create a new class,
named
PFStude nt, with the same member variables and property procedures as the cla s Student.
The
only change need ed in the class block occurs in the CalcSem Grade method. The new
code for
this method is

Functio n CalcSem Grade() As String


Dim grade As Double
grade = (m_ midterm + m_ final) I 2
grade = Math .Round( grade) Round the grade.
If grade >= 60 Then
Return "Pass"
Else
Return "Fail"
End If
End Functio n

The only change needed in the form's code is to replace the two occurren ces of Student
with
PFStudent. When the program is run with the sa me input as in Example 1, the output will
be
Adams, Al 123-45-6 789 Pass

Object Constructors
Each class has a special method called a construc tor that is alway invoked when an
object is
instantia ted. The construc tor takes ze ro or more argumen ts, and the code inside the
procedure
block performs any tasks needed for initializing an object. It is often us d to se t default
va lue
for member va riab les and to create other obj ects assoc iated with this object. The first
line of the
constru ctor for a class has the form

Public Sub New(ByV al parl As DataTyp el, ByVal par2 As DataTyp


e2, ... )

The graphica l program in Exa mple 3 illustrates the use of a construc tor to specify the
size
and initial placeme nt of a circle. This task invo lves pixe ls. To ge t a fee l for how big
a pixe l is,
the initial size of the fo rm when you create a new project is 300 pixe ls by 300 pixe ls.
Section
9.4 exp lains how graphic are created inside a picture box with the Graphic obj
ect gr =
picBox.C reateGra phics. In Examp le 3, the statemen t

gr.Draw Ellipse( Pens.Bl ack, Xcoord , Ycoord, Diamete r, Diamete


r)

draws a circle inside a picture box, where Xcoord andY coord are the distances (in pixels)
of th e
circle fro m the left side and top of the picture box.
500 • Chapte r 11 O bj ect-Oriented Program ming

track of
Example 3 The fo llowing program contain s a C ircle object. The obj ect keeps
by two numbe rs, called th e
the locatio n and diamet er of the circle. (The loca tion is specified
box. Distan ces and the
coordin ates, giving the distance from the left side and top of the picture
the circle, and a Move method adds
diamet er are mea ured in pixels.) A Show method d isplays
loca ted at the upper-
20 pixe ls to each coordin ate of the circle. Ini t ially, the (unsee n) circle
is
a button caption ed Move
left corner of the picture box and has a diamet e r of 40. The form has
Ycoord, and Diame ter
and Show Circle that invokes both methods. Not ice that the Xcoord,
s.
properties, rather than the member va ri ab les, appea r in the method
OBJECT PROPERTY SETTING

a ~- Moving Circle GJI ~ ICID frmC ircle Text Mov ing


C ircle
Move and Show Orcle
l0 btnMov e Text Move and
Show C ircle
btnQui t Text Quit
picCircle

Public Class frmCi rcle


Dim round As New Circle ()

ck
Privat e Sub btnMov e_ Click( ... ) Handle s btnMo ve.Cli
round . Move(2 0)
round. Show( picCir cle.Cr eateGr aphics )
End Sub
k
Privat e Sub btnQu it_ Click( . . . ) Handle s btnQu it.Clic
Me .Close ()
End Sub
End Class 'frmC ircle

Class Circle
Privat e m x As Intege r 'Dist from left side of pictur e box to circle
Privat e m_ y As Intege r 'Dista nce from top of pictur e box to the circle
Privat e m d As Intege r 'Diame ter of circle

Public Sub New ()


uppe~-left
'Set the initia l locati on of the circle to the
to 40.
'corne r of the pictur e box, and set its diame ter
Xcoord = 0
Ycoord = 0
Diame ter 40
End Sub
11.1 C lasses and Obj ects
• 50 1

Pub lic Prop erty Xco ord( ) As Inte


ger
Get
Retu rn m_ x
End Get
Set (ByV al valu e As Inte ger )
m x = valu e
End Set
End Prop erty
Pub lic Prop erty Yco ord( ) As Inte
ger
Get
Retu rn m_ y
End Get
Set (ByV al valu e As Inte ger )
m_ y = valu e
End Set
End Prop erty
Pub lic Prop erty Diam eter( ) As
Inte ger
Get
Retu rn m d
End Get
Set (ByV al valu e As Inte ger )
m d = valu e
End Set
End Prop erty
Sub Show ( ByV al gr As Grap hics )
'Draw a circ le with the g1ve n
grap hics cont ext
gr.D raw Elli pse( Pens .Bla ck, Xcoo
rd, Ycoo rd, Diam eter, Diam eter)
End Sub
Sub Mov e( ByV al dist ance As Inte
ger )
Xcoo rd += dist ance
Ycoo rd += dist ance
End Sub
End Clas s 'Cir cle
[Run, and cl ick on the Mov e butto n ten time
s. ]

.....__r_~l_ov_e_a_n_d_S_h_o_··•_'a_._rc_le_~) ~
ing
502 • Cha pter 11 Obje ct-O rien ted Programm

es of these argu-
obje ct con tain s argu men ts, the valu
Wh en the line that insta ntiates an 3, the first line typed
procedure. Fo r insta nce, in Exa mpl e
men ts are passed to the o bj ect's New
in the form's code can be cha nged to
0 , 40)
Dim roun d As New Cir cle ( O,
class ca n be cha nged to
and the New proc ed ure for the C ircle
,
Inte ger , ByV al y As Inte ger
Pub lic Sub New (ByV al x As
ByV al d As Inte ger )
h rc:e to x pix els from
'Set the ini tial lo atio n o box .
from the top of the pic ture
'the lef t side and y pix els
els.
'Set the di ~eter to d pix
Xco ord = x
Yco ord = y
Dia met er d
End Sub

Auto-Implemented Properties
ly or Wri teO nly key-
t in that they do not con tain Rea dOn
Som e prope rty bloc ks are very clear-cu blocks can use the
the ir Get or et bloc ks. Suc h property
words and have no addi tion al code in reduce a clea r-cu t
-to-V B20 10 auto -imp lem ente d prop ertie s feature. Thi s feature allows you to
new the property. Visual
omit declaring a member variable for
property block to just its header, and to ber vari able. The
and Set procedur es and a hidd en mem
Basic auto mat ica lly crea tes hidd en Get arac ter. For exam-
erty name preceded by an und erscore ch
nam e of the mem ber variable is the prop ber variab le will be
if you decl are an auto- imp leme nted property named Soc SecN um, th mem
ple, er of this chap ter.
- imp leme nted propertie s in the remaind
named _So cSec N um. We will use auto

Practice Problems 11.1

1. Wh ich of the fo llow ing ana logi


s i out of place?

(a) class : obje ct


(b) sewing patt ern : ga rme nt
(c) blueprin t : house
(d) program mer : program
(e) cook ie cutt er : coo kie
nter_C iick are
five lines of the even t proc edur e btnE
2. In Exa mple 1, supp ose that the first
replaced with
... ) Han dles btn Ent er .Cl i ck
Priv ate Sub btnE nt er_ Cl ick(
5-67 8 9" 'So c ial s ecu ri t y Num ber
Dim s sn As St r ing = " 123 -4
t .
'Cre ate an inst anc e o f Stu den
pup il = New Stud e nt ( s s n )
pup il.N ame = txtN ame .Tex t
ent class to
Soc Sec N um prop erty bloc k for the Stud
Cre ate a New proc edur e and revise the
prec ed ing cod e.
be cons isten t with the last line in the

EXERCISES 11.1 ·

appl icab le, assu me


class Stud ent from Exa mple 1. W h en
Exe rcises 1 thro ugh 14 refe r to the
that pup il is an in stan ce of the class.
11.1 C lasses and Objects
• 503

1. Wha t wi ll be the effect if the Midt erm prop


erty bloc k is chan ged to the fo llowing?
Pub lic Writ eOn ly Prop erty Mid
term () As Dou ble
Set(B yVa l valu e As Dou ble)
Sele ct Case valu e
Case Is < 0
m midt erm = 0
Case Is > 100
m midt erm 100
Case Else
m midt erm valu e
End Sele ct
End Set
End Prop erty

2. Wha t wi ll be the effect if the Midt erm prop


erty bloc k is changed to the followi ng?
Publ i c Writ eOn ly Prop erty Mid
term () As Dou ble
Set (ByV al valu e As Dou ble)
m midt erm = valu e + 10
End Set
End Prop erty

3. Modify the class bloc k for Student so


that the follo wing state men t wi ll display the
midt erm grade: stude nt's
Mess ageB ox. Show (CS tr(p upil . Mid
term ))
4. Modify the class bloc k fo r Student so
that the stud ent's se mest er average can be
with a state men t disp layed
of the form
Mess ageB ox . Show (CSt r (pup il.A vera
ge))
5. In the class bloc k for Stud ent, why can'
t the th ird line of the Ca lcSe mG rade meth
writ ten as follows? od be
grad e = (Mid term + Fina l ) I 2

6. Writ e code for the class bloc k that


sets the two grad es to 10 whe neve r an insta
class is crea ted. nce of the
7. Wha t is the effec t of addi ng the follow ing
code to the class bloc k?
Publ i c Sub New( )
SocS ec Num = "99 9 -99- 9999 "
End Sub
In Exer cises 8 thro ugh 14, dete rmin e the
erro rs in the give n fo rm code .
8. Dim s c hola r As Stud ent
Priv ate Sub btnG o Clic k( . . . ) Han
dles btnG o.Cl ick
Dim first Nam e as Stri ng
scho lar . Name = "Wa rren"
first Nam e = scho lar.N ame
End Sub

9. Dim scho lar As Stud ent


Pr ivat e Sub btnG o_ Clic k( ... ) Han
dles btnG o . Clic k
Dim nom as Stri ng
s c hola r = Stud ent ( )
ing
504 • Chap ter 11 Object-O rient ed Prog ramm

scho lar.N ame = "Pea ce, War ren"


nom = scho lar.N ame
End Sub

10. Dim sch olar As Stud ent


Han dles btnG o.C lick
Priv at e Sub btnG o Clic k( ... )
Dim nom as Stri ng
sch olar = New Stud ent( )
m_ name = "Pea ce, War ren"
nom = scho lar.N ame
End Sub

11. Dim sch olar As Stud ent


Han dles btnG o .C lick
Priv ate Sub btnG o_ Clic k( ... )
Dim nom As Stri ng
sch olar = New Stud ent( )
sch olar . Name = "Pea ce, War ren"
nom = m name
End Sub

12. Dim sch olar As Stud ent


Han dles btnG o . Clic k
Priv ate Sub btnG o_ Clic k( .. . )
Dim grad e As Stri ng
sch olar = New Stud ent( )
scho lar.C alcS emG rade = "A"
()
grad e = scho lar.C alcS emG rade
End Sub

13. Dim pup il, sch olar As Stud ent


Han dles btnG o.C lick
Priv ate Sub btnG o_ Clic k( . . . )
sch olar New Stud ent( )
pup il = New Stud ent( )
scho lar.M idte rm = 89
pup il . Midt erm = sch olar . Mid term
dter m)
lstG rade s.Ite ms. Add (pup i l.Mi
End Sub

14. Dim sch olar As Stud ent


sch olar =Ne w Stud ent( )

Han dles btnG o.C lick


Priv ate Sub btnG o_ Clic k( ... )
, Man uel"
scho lar.N ame = "Tra nsm issio n
End Sub
n the butt on is
e the outp ut d isplayed in the list box whe
15. ln the follo wing prog ram, det rmin
click ed on:
Pub lic Clas s frmC ount ry
nada ", "Ott awa ")
Dim nati on As New Cou ntry ("Ca

. .. ) Han dles btnD ispl ay.C lick


Priv ate Sub btnD ispl ay_ Clic k(
nati on. Pop ulat ion = 31
& nati on.N ame )
lstB ox.I tem s.Ad d("C oun try: "
& nati on . Cap ital)
lstB ox.I tem s.Ad d("C apit al : "
11.1 Classes and Objects
• 505

lstB ox.I tem s.Ad d("P op: " & nati on.P opu lati on & " mil lion ")
End Sub
End Clas s 'frm Cou ntry

Clas s Cou ntry


Priv ate m nam e As Stri ng
Priv ate m_ cap ital As Stri ng
Priv ate m_ pop ulat ion As Dou
ble

Sub New (ByV al nam e As Stri ng,


ByV al cap ital As Stri ng)
m nam e = nam e
m_ cap ital = cap ital
End Sub

Pub lic Read Only Pro pert y Nam


e() As Stri ng
Get
Retu rn m nam e
End Get
End Pro pert y

Pub lic Read Only Pro pert y Cap


ital () As Stri ng
Get
Retu rn m_ cap ital
End Get
End Pro pert y

Pub lic Pro pert y Pop ulat ion( )


As Dou ble
Get
Retu rn m_ pop ulat ion
End Get
Set( ByV al valu e As Dou ble)
m_ pop ulat ion = valu e
End Set
End Pro pert y
End Clas s 'Cou ntry
Exe rcise s 16 thro ugh 18 refe r to the class
Circle.
16. Enh ance the program in Example
3 so that the Get and Set prop erty proc
Xco ord and Ycoor d prop ertie s are used ed ures of the
by the form code.
17. Modify Exam ple 3 so that the circl
e orig inall y has its loca tion at the lowe r-rig
the pictu re box and moves diagonally upw ht corn er of
ard each time btnMove is clicked on.
18. Modify the form code of Example 3
so that each time btnMove is clicked on,
moved (in pixe ls) is a rand o mly se lected the dista nce
num ber from 0 to 40.
19. Writ e the code for a class called Sq
uare. The class should have thre e propertie
Perimete r, and Are a-w ith their obv ious - Leng th,
mea nings. Whe n a va lue is assigned to one
properties, the values of the othe r two shou of the
ld be reca lculated auto matically. Whe n
lowing form code is exec uted, the numbers the fol-
5 and 20 should be disp layed in the text
boxes:
Dim poly As Squ are

Priv ate Sub btnG o_ Clic k( ...


) Han dles btnG o.C lick
pol y= New Squ are( )
poly .Are a = 25
min g
506 • Cha pter 11 Obj ect- Ori ente d Prog ram

ly . Len gth)
txtL eng th.T ext = CSt r(po
ly.P erim eter )
txtP erim ete r.T ext = CSt r(po
End Sub
e lengths betw een 1
ious exe rcise so that all squa res wi ll hav
20. Modify the class Squ are in the prev a squa re of length 1, and
y. Are a = o. s sho uld result in
and 10. For inst anc e, the stateme nt pol ing length 10.
ld result in a square with ach side hav
the stat eme nt pol y.A rea = 200 hou
used to o bta in the
te the cod e for a class ca lled Pair OfD ice. A Ran d o m obje ct sho uld be
21 . Wri bers (suc h as 3, 4,
ing form cod e is exe c uted, three num
va lu e for eac h die. Wh en the follow
boxes.
and 7) sho u ld be eli played in th e text
Dim cub es As Pair OfD ice
... ) Han dles btn Go. Clic k
Pri vat e Sub btnG o_ Cli ck(
cub es =Ne w Pai rOf Dic e()
cub es. Rol l ()
txtO ne.T ext CSt r (cub es .Di el)
txtT wo. Tex t CSt r(cu bes .Di e2)
txtS um. Tex t CSt r(cu bes .Sum OfF ace s)
End Sub
ber of time s that the
. te a prog ram to ro ll a pair of d ice 100 0 t imes, and disp lay the num
22 Wri class Pa irOf Dic e dis-
of the two face s is 7. The prog ram sho uld use an inst ance of the
sum
cussed in the previous exercise.
s Nam e, Num Stud ents ,
l ege. The class should have propertie
23. Wri te the code for a class called Col lty ratio . When the
atio should compute the stud ent- facu
and N umFaculty. The met hod SFR text box:
num ber 12.4 should be disp laye d in the
following fonn cod e is exec uted , the
Dim sch ool As Col lege
.. . ) Han dles btn Go. Clic k
Pri vat e Sub btnG o_ Cli ck(
sch ool = New Col leg e()
of Mar ylan d, Col lege Par k"
scho ol.N ame = "Un ive rsit y
sch ool. Num Stu den ts = 360 41
sch ool. Num Fac ulty = 289 6
ber( sch ool. SFR atio , 1)
txtB ox. Tex t = For mat Num
End Sub
the h ourly wage and
te a prog ram that calc ulat es an employe e's pay for a wee k base d on
24. Wri an inst anc e of the
puta t ions sho uld be perform ed by
the num ber of hou rs wo rked. A ll com
cla s Wa ge.
The prog ram sh ould h ave a
25. W rite a prog ram to implem
ent the cash regi ster in Fig. 11.1.
dep os its and with -
ps trac k of the bala nce and allo ws
cla s call ed Cas hRegiste r that kee
it a negativ e bala nce .
drawals. The class sh ould not perm

c;:; Cash Register GJI @J ~~ c.. Ave rage

Number: [ Record Number J


Amount :

Calculate Average
Jl.dd Subtract

Average :
Balance :

FIGURE 11 .2 Form for Exe rcise 26.


FIGURE 11 .1 Form for Exe rcise 25.
11.2 W orking with Obj ects
• 507

26. Write a progra m that calcu lates th average of up to


50 n umbers input by th e use r and
sto red in an array. See Fig. 11. 2. The progra m should use a
class named S tat istics and have
an AddN umber metho d that stores numbe rs into an array
one at a time. T he class should
have a Coun t prope rty that keeps track of the nu mber of
numbe rs sto red and a metho d
called Ave rage that return s the ave rage of the n umbers.
27 . Write a progra m th at calcu lates an emp loyee' FIC A tax,
with all compu tat ions perfo rmed
by an instan ce of a class FIC A. The FIC A tax ha two co mpone
n ts: t he social s cur ity ben -
efi ts tax , which in 2009 is 6.2% of the first $ 106,80 0 of
earnin gs for the year, and the
Medic are tax, which is 1.45 % of ea rn ings .
28. W rite a progra m that adds two fractio ns and d isplays the
ir sum in reduced fo rm. T he pro-
gram sho uld use a Fract ion class that stores the numerato
r and deno minat or of a fractio n
and has a Redu ce metho d that divides each of the numer
ator and deno minat or by the ir
grea tes t comm on d iviso r. Exerc ise 29 of Secti on 6.1 conta
in an algorit h m for ca lcu lating
the greate st comm o n diviso r of two numbe rs.

Solutions to Practice Problems 11.1

1. (d) A progra m mer is not a tem plate fo r creati ng a program


.
2. Publ ic Sub New {By Val ssn As String )
' As s ign the value of ssn to the membe r varia
ble m ssn .
m ssn = ssn
End Sub

Pub l i c ReadO nly Prope rty So c SecNu m{) As Strin


g
Get
Retur n m ssn
End Ge t
End Prope rty

Note: S ince a stud ent's social securi ty n umber never changes, there
i no need to have a Set
proper ty proced ure for SocSe cNum .

11.2 Working with Objects


"An object witho ut an even t is like a te lepho ne witho ut a
ri nge r. "
Anonymous
Arrays of Objects
The eleme nts of an array can have any data type- includ ing
a class. The progra m in Examp le 1
uses an array of type Stude n t. Vid eoN ote
Arrays of
objects

Example 1 In the follow ing progra m, whi ch uses the same form des ign as
Examp le 1 of the
prev ious section , the user enters four pieces of data about a studen
t into text boxe . W h en the Enter
Information button is clicked on , the data are used to create and initiali
ze an approp ri ate object and
the object i added to an array. W h en the DisJJ/ay Grades button
is clicked on, the name, ocial
security numbe r, and semest er grade for each studen t in the array
are displayed in the grid.
Publi c Class frmGr ades
Dim s t udent s ( SO) As Stude nt
Dim lastSt udent Adde d As Integ er - 1 'Posi tion in array 0f stude nt
most recen tly added
508 • Chap ter 11 Objec t-Orie nted Programming

les btnE nter. Clic k


Priv ate Sub btnE nter_ Click ( ... ) Hand
lastS tuden tAdd ed += 1
ent
stude nts(l astSt uden tAdd ed) = New Stud
tAdd ed) .Nam e= txtNa me.T ext
stude nts(l astSt uden
tAdd ed) .SocS ecNu m = mtbS SN.T ext
stude nts(l astSt uden
ed) .Mid term = CDbl (txtM idter m.Te xt)
stude nts(l astSt uden tAdd
CDbl (txtF inal. Text )
stude nts(l astSt uden tAdd ed) . Fina l =
'Clea r text boxe s
txtNa me.C lear( )
mtbSS N . Clea r ()
txtM idter m.Cl ear()
txtFi nal.C lear{ )
txtNa me. Focu s ()
)
Mess ageB ox .Show ( "Stud ent Reco rded. "
End Sub

Hand les btnD ispla y.Cl ick


Priv ate Sub btnD ispla y_ Click ( ... )
ed)
ReDim Pres erve stude nts(l astSt uden tAdd
Dim query = From pupi l In stud ents
pupil .Calc SemG rade
Sele ct pupil .Nam e, pupil .SocS ecNu m,
dgv Grad es.D ataSo urce = quer y.To List
dgvG rades .Curr entC ell = Noth ing
= "Stud ent Name "
dgvG rades .Colu mns( "Nam e" ) .Hea derT ext
derT ext = "SSN"
dgvG rades .Colu mns( "SocS ecNum " ) .Hea
"Calc SemG rade" ) .Hea derT ext = "Grad e"
dgvG rades . Colum ns(
ReDim Pres erve stude nts(S O)
txtNa me . Focu s ()
End Sub

les btnQ uit.C lick


Priv ate Sub btnQ uit Click ( . . . ) Hand
Me .Clos e()
End Sub
End Clas s 'frmG rades

Clas s Stud ent


Priv ate m midte rm As Doub le
Priv ate m fina l As Doub le

Publ ic Prop erty Name () As Strin g

g
Publ ic Prop erty SocSe cNum () As Strin

As Doub le
Publ ic Write Only Prop erty Midt erm()
Set (ByV al value As Doub le )
m midte rm = value
End Set
End Prop erty

Doub le
Publ ic Write Only Prop erty Fina l() As
Set (ByV al value As Doub le )
m fina l = value
End Set
End Prop erty
11 .2 Work ing with Objects
• 509

Fun ctio n Calc Sem Grad e() As Stri


ng
Dim grad e As Dou ble
grad e = (m_m idter m + m_ fina l)
I 2
grad e = Math .Rou nd(g rade ) 'Rou nd the grad e.
Sele ct Case grad e
Case Is >= 90
Retu rn "A"
Case Is > = 80
Retu rn "B"
Case Is >= 70
Retu rn "C"
Case Is >= 60
Retu rn "D"
Case Else
Retu rn "F"
End Sele ct
End Fun ctio n
End Clas s 'Stu den t
[Run , type in data for A l Adams, click on
the Enter Informati on butto n , repe at the proc
Britt any Brow n and Caro l Cole, click on ess for
the Display Grades butto n, and then ente r
Dan iel Doy le.] data for

D 1 Se ester Grade

Name : Do)~e . Daniel

55 N: 1 -JH555 Midterm: HS Anal: BEl


Enter Information ] Display Grades Ouit

Student Name SS N Grade


dams. J 1- 5JS7& 8
Bro•• •n. Brtttafll,r -J,J
Cole. arol

Events
In the prev ious section, we drew a para llel
betw een clas es and cont ro ls and showed
defin e properti es and meth ods for cla se . Even how to
ts can be defin ed by the programm er to co mmu
nica te ch anges of prope rties , errors, and the -
progress of lengthy ope rat ions. Such eve nts
called user -defi ned even ts. The state men t are
for ra ising an even t is loca ted in the class bloc
the even t is dealt with in the form's code . k, and
Suppose that the even t is named Use rDefined
and has the parameters par 1, par 2, and so on. Even t
In the class bloc k, the state men t
Pub lic Even t User Defi nedE vent (ByV
al parl As Data Type l,
ByV al par2 As Data Type 2, . . .)
should be placed in the Decl arati ons section
, and the state men t
Rais eEve nt Use rDe fine dEv ent( argl
, arg2 , ... )
ing
510 • Chapter 11 Object-O riented Programm

nt sho uld be raised.


the class bloc k code at whi ch the eve
shou ld be plac ed at the loca tion s in with a stat eme nt of
class , ca ll it object/, must be decl a red
In the form 's code , an inst ance of the
the type

Clas sNa me
Di m Wi thEv en t s obj ect l As

or the type

New Clas sNa me


Dim Wi thE ven ts obj ect l As
must be inse rted
r to be able to resp ond to the even t. Tha t is, the keyw ord Wit hEv ents
in orde be
er of an even t proc edur e for objectl will
into the decl arat ion state men t. The head
Typ e l,
fine d Eve nt(B yVa l par l As Data
Priv a te Sub ob jec tl_ Use rDe Dat aTy p e 2, . .. )
ByV a l par2 As
Han dles obj ect l . Us e r Def i nedE ven t

Exa mple 3 of Sec tion 11.1 . In the fol-


Example 2 Con side r the Circ le class defi ned in le ch anges. The
is raise d whe neve r the loca tion of a circ
low ing prog ram, we add an eve nt that form's code uses the
t h as para met ers to pass th e loca tion and diam eter of th e circle. The
even pict ure box . If so, the
the draw n circle will fa ll outs ide the
even t to dete rmin e if part (or all ) of s call the even t
"C ircle Off Scre en" in a text box. Let'
eve nt proc edur e disp lays the message
Pos ition C han ged.

OBJECT PROPERTY SETTING

a~ Mov ing Circl e GJ I §] I~ frmCircle Text Moving


C ircle

Move and Show Qrde ~ btnM ove Text Move and


how Ci rcle
btnQuit Text Quit
txtCautio n ReadOnly True
picCircle
11 .2 Wo rking with Obj ects
• 511

Pub lic Clas s frmC ircle


Dim With Even ts roun d As New Circ
le ()

Priv ate Sub btnM ove Clic k( ...


) Han dles btnM ove. Clic k
roun d.Mo ve(2 0)
roun d.Sh ow( picC ircle .Cre ateG raph
ics)
End Sub

Priv ate Sub btnQ uit_ Clic k( ...


) Han dles btnQ uit . Clic k
Me . Clos e ()
End Sub

Priv ate Sub roun d_ Posi tion Cha nged


( ByV al x As Inte ger ,
ByV al y As Inte ger , ByV al d As
Inte ger ) Han dles roun d.Po sitio nCh
'Thi s even t is rais ed when the ange d
loca tion of the circ le chan ges.
'The code dete rmin es if part of
the circ le is off the scre en.
If (x + d > picC ircle .Wi dth) Or
(y + d > picC ircle . Heig ht) Then
txtC auti on . Text = "Cir cle Off
Scre en"
End If
End Sub
End Clas s 'frm Circ le

Clas s Circ le
Pub lic Even t Posi tion Cha nged ( ByV
al x As Inte ger ,
ByV al y As Inte ger , ByV al d As
'Eve nt is rais ed when the circ Inte ger )
le move s

Pub lic Sub New ()


Set the ~nitial loca tion of the
circ le to the upp er-l eft
'cor ner of the pict ure box, and
set its diam eter to 40.
Xcoo rd 0
Ycoo rd = 0
Diam eter 40
End Sub

Pub lic Prop erty Xco ord( ) As Inte


ger

Pub lic Prop erty Yco ord( ) As Inte


ger

Pub lic Prop erty Diam eter( ) As


Inte ger

Sub Show ( ByV al gr As Grap hics )


'Draw a circ le with the give n
grap hics con text .
gr.D raw Elli pse( Pens .Bla ck, Xcoo
rd, Ycoo rd, Diam eter, Diam eter)
End Sub

Sub Mov e( ByV al dist ance As Inte


ger )
Xcoo rd += dist ance
Ycoo rd += dist ance
Rais eEve nt Posi tion Cha nged (Xco
ord, Ycoo rd, Diam eter)
End Sub
End Clas s 'Cir cle
ing
512 • Cha pter 11 Obje ct-O rient ed Programm

[Run, and click on the Move and Show


Circle butt on eleve n times.]

11 _. •lovin g Circl e

Orcle Off Screen


Move and Show Orcle

the text box.


s "Circle Off Scree n" are disp layed in
Note : As the last circle appears, the word

Containment
use of an obje ct
n a mem be r vari ab le of class A makes
We say that class A con tains cla s B whe .
DeckOfCards co ntains the class Ca rd
of type class B. In Example 3, the class

d poker hand . The program has a


Example 3 The following program deals a five-car ha two properties,
kO fCa rds obje ct con tain ing an array of 52 Card obj ects. The Card obj ect
Dec met hod returns a
hod , ldentifyC ard . The Iden tifyC ard
Den omi nati on and Suit, and one met nt procedure ass igns
DeckOfCards object, the New eve
strin g such as "Ac e of Spade ". In the strin g iden tifying
s. The met hod ReadCa rd(n ) retu rns the
den omi nati ons and suits to the 52 card mix up the cards
ShuffleDeck uses the Rand om class to
the nth card of the deck. The met hod
deck . The even t
while making 2000 passes thro ugh the
ax As Inte ger )
Shu ffli ng (n As Inte ger , n M
the number of
the deck, and its para mete rs communicate
is raised during each shuffling pass through k of the progre s.
that the prog ram that uses it can keep trac
the pass and the tota l number of passes, so ING
OBJECT PROPERTY SETT

o;1 Po ker Hand [£]~ ~ frmPoker Text Poker Han d


lstH and
lstHa nd btnS huffl e Text &Shuffle
bmD eal Text &De al
bmQ uit Text &Qu it

~huffie ] [ Qeal ] [ Q)Jtt


11.2 Wo rkin g wit h Ob jec ts
• 513
Pu bli c Cla ss frm Po ker
Dim Wi thE ven ts car ds
As New De ckO fCa rds ()

Pr iva te Sub btn Sh uff


le_ Cl ick ( ... ) Ha ndl
es btn Sh uff le. Cl ick
car ds . Sh uff leD eck
End Sub

Pr iva te Sub btn De al_


Cl ick ( ... ) Ha ndl es
Dim str As Str ing btn De al. Cl ick
lst Ha nd .Ite ms .C lea r()
Fo r i As Int eg er =
0 To 4
str = car ds. Re adC ard
(i)
lst Ha nd .Ite ms . Ad d(s
tr)
Ne xt
End Sub

Pr iva te Sub btn Qu it_


Cl ick ( ... ) Ha ndl es
Me .Cl ose () btn Qu it.C lic k
End Sub

Pr iva te Sub car ds Sh


uff lin g( By Va l n As Int
eg er ,
By Va l nM ax As Int eg
'n is the num ber of er ) Ha ndl es ca rds .Sh
the sp ec ifi c pas s thr uff lin g
'nM ax is the tot al ou gh the dec k (1, 2,
num ber of pa sse s wh 3.. )
lst Ha nd .It em s.C lea r() en the dec k is sh uff
led .
lst Ha nd . Ite ms . Ad d( "S
hu ffl ing Pa ss: " & n
Fo r i As Int eg er = & " ou t of " & nM ax)
1 To 100 000 0 'Sl ow dow n the sh uff
Ne xt le
lst Ha nd .U pd ate () 'Re fre sh co nte nts of
End Sub lis t box
End Cl ass 'frm Po ker

Cla ss Ca rd
Pr iva te m den om ina tio
n As Int eg er 'A num ber fro m 0 thr
Pr iva te m_ su it As Str ou gh 12
ing 'He art s, Clu bs, Dia mo
nds , Sp ade s
Pu bli c Pro pe rty De nom
ina tio n() As Int eg er
Ge t
Re tur n m den om ina tio
n
End Ge t
Se t (By Va l va lue As
Int eg er )
'On ly sto re va lid va
lue s.
If (va lue >= 0) An d
(va lue <= 12) Th en
m den om ina tio n = va
lue
End If
End Se t
End Pro pe rty

Pu bli c Pro pe rty Su it(


) As Str ing
Ge t
Re tur n m su it
End Ge t
Se t (By Va l va lue As
Str ing )
'On ly sto re va lid va
lue s.
If (va lue "H ear ts" ) Or (va lue
"C lub s" ) Or
(va lue = "D iam ond s"
) Or (va lue = "Sp ade
s" ) Th en
ed Progra mm ing
514 • Ch apt er 11 Ob jec t-O ri ent

m su i t va lue
End If
End Se t
En d Pr op ert y

ard () As Str ing


Fu nc tio n Ide nti fyC
= ""
Dim den om As Str ing
t Ca se De no mi nat ion + 1
Se lec
Ca se 1
den om = "A ce"
Ca se Is <= 10
+ 1)
den om CS tr (D eno mi nat ion
Ca se 11
den om "Ja ck"
Ca se 12
den om "Q uee n"
Ca se 13
den om = "K ing "
En d Se lec t
" & m su it
Re tur n den om & " of
End Fu nc tio n
End Cl ass 'Ca rd

Cl ass De ckO fCa rds ss Ca rd


fCa rds co nta ins cla
As Ca rd 'Cl ass De ckO
Pr iva te m_ dec k(S 1) eg er , By Va l nM ax As Int eg er )
lin g( By Va l n As Int
Pu bli c Ev ent Sh uff

Pu bli c Sub New () the


rte en car ds he art s,
'Ma ke the f1 rst thi .
d am ond s, and so on
ne xt thi rte en car ds s" , "D iam ond s" , "Sp
ade s" }
its () As Str ing = { "H ear ts" , "C lub
Dim su
0 To 3
Fo r i As Int eg er = fou r su its .
nd s to one of the
'Ea ch pa ss co rre spo
0 To 12
Fo r j As Int eg er = the
m 0 thr ou gh 12 to
'As sig n num ber s fro
'ca rds of eac h su it
= New Ca rd ()
m_ de ck (i * 13 + j)
j) . Su it = su its (i)
m_ de ck (i * 13 +
j) .De nom ina tio n = j
m_ de ck (i * 13 +
Ne xt
Ne xt
En d Sub
eg er ) As Str ing
By Va l car dN um As Int
Fu nc tio n Re adC ard (
m) .Id en tif yC ard ()
Re tur n m_ dec k(c ard Nu
En d Fu nc tio n
Int eg er )
Int eg er , By Va l j As
Sub Sw ap( By Va l i As
ard s in the dec k
'Sw ap the ith and jth
rd
Dim tem pC ard As Ca
tem pC ard = m_ de ck (i)
m_ de ck (i) m_ de ck (j )
m_ de ck (j) = tem pC ard
End Sub
11 .2 Working with Objects
• 515

Sub Shu ffleD ec k ()


'Do 2000 pa~ses thro ugh the
deck . On each pas s,
•swa p each card with a rand oml
y sele cted card .
Dim inde x As Inte ger
Dim randomNum As New Rand om
()
For i As Inte ger = 1 To 2000
For k As Inte ger = 0 To 51
i ndex ·= rand omN um.N ext(O , 52)
'Ran dom ly sele ct a num ber
from 0 thro ugh 51 incl usiv e.
Swap (k , inde x)
Nex t
Rais eEv ent Shu ffli ng( i, 2000
)
Nex t
End Sub
End Clas s 'Dec kOf Card s
[Run , click on the Shuffle butt on, and click
on the Deal butt on after the shuffl ing is
com plete.]

B of Hearts
17of Diamond~{
Jac:k of Hearts
Queen of Spades
1 of Hearts

[ Shuffle ] ( Deal J [ Quit

Practice Problems 11.2

Con side r the prog ram in Exa mple 1 of


Section 11.1 , and supp ose that mtb SSN
nary (rath er than a mas ked) text box. is an ordi-

1. A lter the et SocS ecN um property proc


edur e to raise the even t lmp rope rSSN
soci al security num ber does not have 11 whe n the
char acte rs. The eve nt hou ld pass the leng
social security num ber and the stud ent's th of the
name to the form's code.
2. Wh at state men t must be placed in the
Dec larat ions secti on of the Stud ent class
?
3. Wri te an eve nt proc edur e to hand le
the even t l mpr oper SSN .
4. Wh at state men t in the form's code mu
t be alter ed?

EXERCISES 11.2

1. In Exam ple 1 of this sect ion, modify


the even t procedur e btnD ispla y_C lick so
stud ents who rece ive a grad e of A are d that on ly the
isplayed.
The file Uni tedS tates .txt prov ides data
on the 50 states. (Thi s file is used in Exe
thro ugh 5.) Eac h reco rd cont ains five rcises 2
pieces of info rma tion abou t a single state
abbr evia tion , date it ente red the u nion : nam e,
, land area (in squa re miles ), and popu
latio n in
ramm ing
5 16 • Cha pter 11 Object- Orie nted Prog

union. T he firs t
ered by the date of entr y into the
the yea r 200 0. T he reco rds are ord
thre e lines of the file are

4 ,759 000
De l a war e,D E, 1 2/ 7 / 178 7 , 195
2 / 1 2/ 178 7 , 4 4 817 ,122 960 00
Pen nsy lva nia , PA,1
4 1 7, 813 500 0
New Jer sey ,NJ ,l2/ 18 / 178 7,7
a ingle stat e and a
ert ies to hold the info rma tion abo ut
2. C reat e a class Stat e with five prop
(peo ple per sq uare mile) of the state.
met hod that calcu lates the density
displays the state's
tate 's name in an inpu t di alog box and
3. Wri te a prog ram that requ est a ram sho uld use an
entr ance into the unio n. The prog
abb reviation, density, and date of
array of Stat e objects.
s in a Dat aGr idV iew
names of the stat es and their den sitie
4. Wri te a program that displays the
uld use an array of Stat e objects.
ordered by den sity. The program sho
an array of Stat e
from the file one line at a time into
5. Wri te a program that read s the data ten million . Stat es
er the populat ion of a stat e exceeds
objects and raises an eve nt whe nev d in a list box by
their nam es and popu latio ns disp laye
with a large popu latio n sho uld have tate s that con tains
(Hin t: Cre ate a class call ed Uni tedS
the correspo ndin g eve nt procedure. The Add met hod
that add s a new stat e to the array.
the array and defines a met hod A dd
sho uld raise the eve nt.) IllegalN umb er
r the class Squ are from Exe rci e 19 of Sec tion 11.1. Add the eve nt
6. Con side w the new cla s
erties is set to a negat ive num ber. Sho
that is raised whe n any of the prop message.
for the eve nt that d ispla ys an error
block and write an eve nt procedure
.1. Add the eve nt
s in Exe rcise 25 of Sec tion 11
7. Con side r the Cas h Reg iste r clas e mon ey tha n
emp tTo Ove rdra w tha t is rais ed whe n the use r tr ies to sub t ract mor
Att
is in the cash register.
.1. Add the eve nt
ussed in Exercise 21 of Sec tion 11
8. Conside r the class PairOfD ice disc dice. Wri te a pro-
two ones appear dur ing a roll of the
SnakeEyes that is raised whe nev er
gram that uses this eve nt.
Den omi nato r
side r the Frac tion class in Exe rcise 29 of Sec tion 11.1. Add the eve nt Zero
9. Con the eve nt.
r is set to 0. Write a program that uses
that is raise d whe nev er a den ominato
the num erators and
calcu lato r show n in Fig. 11 .3. Aft er
10. Wri te a program for the frac tion ed in the four text
to the left of the equals sign are plac
den omi nato rs of the two frac tion s ears to the righ t
sho uld be clicked on. The re ult app
boxes, one of four operat ions buttons tain s three mem-
the equ als sign . The prog ram sho uld use a Cal cula tor class, whi ch con
of e: In Fig. 11 .3, the
in Exe rci e 28 of Sec tion 11 .1. Not
bers of the type Frac tion d iscussed
frac tion bars are very sho rt list boxes.

ai Game of Dice ~~
lL.==::JI~@)="'~~~
Player 2
a Frac tion Calcu lato r l = I @] II'"'"·EJ I Playe r 1
3
6 5 4

3
=
00 = 4
=
1
Play

~ [±]
8 15 10 Play er 1 wins.

FIGURE 11.4 Sam ple Out put for Exe rcis e 11.
FIGURE 11.3 Sam ple O utpu t for Exe rcise 10.
11.2 Working with Objects
• 5 17

11. Wri te a prog ram for a simp le gam e


in whic h each of two players rolls a pair
with the high est tally wins. See Fig. of dice. T h e pers on
11.4 . The prog ram sh ould use a class ca
h avin g two mem ber vari ables of the lled H1ghRo ller
type Pa irOf Dice discussed in Exercise
21 of Sec tio n 11 .1.
12. Wri te a prog ra m that take s orde rs
at a fast food res taur ant. See Fig. 11
two men u - a regu lar men u and a .5. The re taUI·ant h as
kids men u . An item i o rd ered by h
of the list boxe s and then clic k ing igh ligh ting It 1n o n e
o n the> > o r << butt o n to p lace it
in the cen ter of the form. A each in th e o rde r list box
item is o rd ered , a runn ing tota l is d
box at the lowe r righ t part of the form isp layed in the text
. The prog ram sh ou ld use a Cho ices
tain a Foo d class. (Th e con tent s of class, whi ch con -
each of the thre e list boxe s sh o uld be
obje cts.) Eac h Foo d obje ct sh o uld trea ted as C h o ices
h o ld the n ame and pric e of a sing
Cho ices clas s shou ld have a C h oice le food ite m. The
Ch ang ed even t that can be used by
upd ate the cost of the orde r. the form code to

a~ Fast Food Restaurant Cash Reg ister


l= I@) l..a""!l
Regular Menu Custom er Order Kids Menu
- - --,
pizza slice (S1.75)
pizza slice (S1.75)
burger (S2.55)
salad (S3.29)
salad (S3.29) ~f ~S1
.••m] .50~
burger (S2 55) (]• l-
Iaroe soda (S1 .25) i ~ medium soda (S0.90) [;: :] cookie (S0.96)
hot dog (S1 .50)
cook1e (S0.96)
small soda ( .60)

[ Clear l [ Quit l L
Tota l: S11 .55

FIGURE 11.5 Sa mple outpu t for Exercise 12.

13. Wri te a prog ram to prod uce a


n emp loyee's wee kly payc heck rece
con tain the emp loye e's nam e, a mo ipt. The rece ipt sho uld
unt ea rned for the wee k, tota l a mo
yea r, FIC A tax ded ucti on, with hold unt earn ed for the
ing tax ded uct io n, and take -hom e
gram sh ou ld use an Emp loye e class amo unt. The pro-
and a Tax class. The Tax class mus t
the a mou nt ea rned for the wee k, the hav e prop ertie s for
prio r tota l a mo unt ea rned for the yea
of with hold ing a llow ance s, and mar r, the num ber
ita l statu s. It shou ld h ave met hod s for
a nd with hold ing taxes. The Emp loye com puting FIC A
e class sh o uld store th e emp loyee's
with ho ld ing allo wan ces, mar ital statu na me, num ber of
s, hours wor ked this week, h o urly salar
amo unt earn ed for th e year. The Emp y, and prev io us
loye e class sh ou ld use the Tax class
taxe s to be dedu cted . The form ula to calc ulat e the
for calc ulat ing th e FIC A tax is give
Sec tion 11.1. To com pute the with hold n in Exe rcise 2 7 of
ing tax, mu ltipl y the num ber of with hold
by $70 .1 9, subt ract the prod uct from ing allow ances
the amo unt earned, and use Table 11.1
or Tab le 11.2.

I4':J!IIII 2009 Federal income tax withheld for a sing


le person paid weekly.
Adju sted Wee kly Inco me
Income Tax With held
$0to $13 8
$0
Ove r $138 to $200
10% of amo unt over $138
Ove r $200 to $696
$6.20 + 15% of amo unt ove r $200
Ove r $696 to $ 1,2 79
$80.60 + 25% of amo unt over $696
Ove r $1,279 to $3,338
$226 .35 + 28% of amo unt over $1,279
Ove r $3,338 to $7,2 12
$802.87 + 33% of amo unt over $3,338
Ove r $7 ,212
$2,08 1.29 + 35% of amo unt over $7,2
12
ram min g
5 18 • Cha pter 11 Object- Ori ented Prog

ried person paid weekly.


lt;1:1!11fl 2009 Federal income tax withheld for a mar
Inco me Tax Wit hhe ld
Adj usted Wee kly Inco me
$0
$0 to $303
10% of amo unt ove r $303
Ove r $303 to $ 4 70 0
$ 16. 70 + 15 % of amou nt ove r $47
Ove r $47 0 to $ 1,455 un t ove r 1,45 5
164.45 + 25% of amo
Ove r $ 1,455 to $2,272 ove r $2 ,2 72
$368.70 + 28% of amo unt
Ove r $2,272 to $4,165 65
$898.74 + 33% of amou nt ove r $4,1
Ove r $4,165 to $7,321 r $ 7,321
$ 1,940.22 + 35% of amo unt ove
Ove r $7,32 1

Solutions to Practice Problems 11.2


() As Str ing
1. Pub lic Pro per ty Soc Sec Num
Get
Ret urn m ssn
End Get
)
Set (By Val val ue As Str ing
If val ue. Len gth = 11 The n
m ssn = val ue
Els e
(va lue .Le ngt h, m_ nam e)
Rai seE ven t Imp rop erS SN
End If
End Set
End Pro per t y
r,
SN (By Val len gth As Int ege
2. Pub lic Eve nt Imp rop erS ame As Str ing )
ByV al stud entN
ege r ,
erS SN (By Val len gth As Int
3. Pri vat e Sub pup il Imp rop ng) Han dles pup il .Im pro
perS SN
ByV al stud entN ame As stri for 11 &
eBo x.Sh ow( 11
The soc ial sec uri ty num ber ent ere d
Mes sag
con sist ed of
11 & len gth &
stu den tNa me &
11
& 11 11

dat a for 11 & stud entN ame


• )

11
cha rac ter s. Ree nt er the
End Sub

4. T he state men t

Dim pup il As Stu den t

mus t be cha nge d to


Stu den t
Dim Wit hEv ent s pup il As

11.3 Inheritance
and "inh erit ance." O ne class
classes are "use," "co nta inment ,"
VideoNo te The three rela tion ship s betw een t class A con tain s class B
s obj ects of tha t class. We say tha
use s ano the r class if it manipu late Sec tion 11.2 presen ts
es use of an obje ct of type class B.
Inhe ritan ce
a mem ber vari able of class A mak
whe n
exa mp les of use and con tainmen t. s ) inh erit s the proper-
one class (the chil d or der ived clas
Inh erit anc e is a pro ce by whi ch child has access to all
s, and eve nts of ano the r class (th par ent or base class ). The
ties, met hod pare nt is itse lf a
pro perties, met hod s and eve nts as well as to all of its own. If the
of its pare nt's
11.3 lnh eri ranee
• 519
ch ild , the n it and its chi ldr en
h ave access to all of its par ent
Co ns id er the classes sh ow n 's pro per ties , me tho ds a nd ev
in Fig. 11. 6. All thr ee chi ldr nts.
from the ir par ent . C hild 2 and en inh eri t Pro per ty A and S ub
C hild 3 hav e an add itio nal B
Gr and Ch ild ! ha access to eve nt and a pro perty, res pec
Pro per ty A, Sub B, and Ev tive ly.
tio n E and Sub F. Th e col ent C from its par ent and add
lec tio n of a par ent class a s Fun c-
lo ng wit h its des cen dan ts
hie rar chy . is ca lled a

Parent
Property A
Sub B

I
I
Child1 Child2 Child3
Event C Property D

I
I I
GrandC hild1
GrandChild2
Function E
Event G
Sub F

FIGURE 11.6 Exa mp le of inh erit anc e hie rarc


hy.

Th ere are two ma in ben efit s


ga ined by using inh erit anc e:
to sha re som e co mm on feature Fir t, it allo ws two or mo re clas
s yet dif fer ent iate the mse lve ses
reusability by avo idin g the ext s on oth ers. Sec ond, it suppor t cod
ra effo rt req uired to ma inta in e
For the se reasons, inh erit anc dup lica te cod e in mu ltip le clas
e is one of the mo st powerfu ses.
ming. Co nsi derab le work goe l tools of object -or ien ted pro
s int o pla nni ng and def inin g gram-
the par ent class. Th e child clas the me mb er variab les and me
ses are beneficiaries of thi s effo tho ds of
Jus t as stru ctu red pro gra mm rt.
ing req uires the ab ilit y to bre
ubp rob lem s, obj ect -o rien ted ak com ple x pro ble ms int o sim
pro gra mm ing req uires the skil ple r
classes and der ive d classes. Sof l to ide ntify usefu l hie rar chi
tware eng ine er are ti ll wo rki es of
how to est ablish hie rarc hie s. ng on the guid elin es for wh en
On e useful crit erio n is the ISA and
case of ano the r class, the firs test: If one class is a mo re spe
t class sho uld be der ive d from cifi c
Th e Visual Basic keyword Inh the second class.
erit s id ent ifies the par ent of
the cla Par ent and its chi ld a class. Th e cod e used to def
class C hild 2 as illu stra ted in ine
Fig. 11.6 is
Cla ss Pa ren t
Pu bli c Pro per ty A
'Pr op ert y Ge t and Set
blo cks
End Pro per ty

Sub B ()
'Co de for Sub pro ced
ure B
End Sub
End Cla ss

Cla ss Ch ild 2
Inh eri ts Pa ren t
Ev ent C ()
End Cla ss
Progra mm ing
520 • Ch apt er 11 Ob jec t-O rien ted

using a similar sta tem ent :


itse lf a par ent , its ch ild Gr and C hil d! can be declared
As Ch ild 2 is
Cla ss Gr and Ch ild l
Inh eri ts Ch ild 2

Fu nct ion E ()
'Co de for fun cti on E
End Fu nct ion

Sub F ()
'Co de for Sub pro ced ure
F

End Sub
End Cla ss

ic add ing machi ne.


llow ing pro gra m, the use r is presen ted wit h a bas
Example 1 In the fo FirstNum-
ent s the Mu ltip ly and Div ide me thods and inh e rit the
Th e Ca lcu lato r class implem ds fro m its Ad din gM ach ine
pro per ties and the Ad d and Su btr act me tho
ber and Sec ond Nu mb er r may add or sub tra ct two
ing Ma chi ne rad io but ton is selected, the use
par ent . Wh en the Add ton is select ed, the
chi ne obj ect . Wh en the Ca lculator radio but
num bers using an Ad d ing Ma ect . No tice tha t
ltip ly, or div ide two num bers usi ng a Ca lcu lato r obj
mu
use r may add, sub tract, chi ne is sele cte d, and how the
ton s are hid den wh en the Ad d ing Ma
the multip ly and d ivid e but the tat e of the radio
ced ure s for the btn Ad d and btnSubtract but ton s exa mi ne
C lick eve nt pro
machi ne to use.
but ton to det erm ine wh ich
PROPERTY SETIING
OBJECT
Cal cu lations
a.., C a lc ulat i on~ ~~ ~ ICID frmCa lcul ate Tex t
Tex t First N um ber:
lblN um ber l
Rrst Number: txtN um ber 1
Tex t Sec ond Nu mb er:
lb1Nu mb er2
Second Number: txtN um ber 2
Tex t Result:
lblR esu lt
Rea dO nly True
Machine txtResu lt
Tex t Ma chi ne

GJ [ ] Add ing grp Ma chi ne


0 Tex t Ad di ng Machi ne
Mach ine rad Ad d ingM ach ine
Ch eck ed Tru e

0 GJ Calculator Tex t Cal cul ato r


rad Cal cu lato r
btn Ad d Tex t +
btn Sub trac t Tex t
Tex t X
Resu~ : btn Mu ltiply
Fon t Sym bol
btn Oiv ide
Tex t , (Ce d illa)

lat e
Pu bli c Cla ss frm Ca lcu
ma chi nes .
'Cr eat e bo th
New Ad din gM ach ine ()
Dim add er As
lat or ()
Dim cal c As New Ca lcu
( ... ) Ha ndl es
ach ine _ Ch eck edC han ged
Pr iva te Sub rad Ad din gM edC han ged
rad Ad din gM ach ine .Ch eck
div ide fun cti on ali ty.
'Hi de the mu ltip ly and
b tnM ult ipl y.V isi ble
= Fa lse
b tnD ivi de .V isi ble = Fa lse
End Sub
11.3 Inh erit ance
• 521
Pri vat e Sub rad Ca lcu
lat or_ Che cke dCh ang ed( ... ) Ha ndl es
rad Ca lcu lato r.C hec ked Ch
'Sh ow the mu ltip ly and ang ed
div ide fun cti on ali ty.
btn Mu ltip ly . Vi sib le =
Tru e
btn Div ide .Vi sib le = Tru
e
End Sub

Pri vat e Sub btn Ad d Cli


ck( ... ) Ha ndl es btn Ad
'Ad d two num ber s. d.C lick
If rad Ad din gM ach ine .Ch
eck ed The n
'If add ing ma chi ne sel
ect ed, use 1t to get
add er. Fir stN um ber = CD the res ult .
bl (tx tNu mb erl .Te xt)
add er.S eco ndN um ber =
CD bl (tx tNu mb er2 .Te xt)
txt Re sul t.T ext = CS tr
(ad der .Ad d)
Els e
'If cal cul ato r sel ect ed,
use it to get the res
c alc .Fi rst Nu mb er = CD ult .
bl (tx tNu mb erl .Te xt)
cal c . Sec ond Num ber = CD
bl (txt Nu mb er2 . Tex t)
txt Re sul t . Tex t = CS tr
(ca lc . Add )
End If
End Sub

Pri vat e Sub btn Su btr act


_ Cli ck( ... ) Ha ndl es btn
'Su btr act two num ber s. Su btr act .Cl ick
If rad Ad din gM ach ine .Ch
eck ed The n
'If add ing ma chi ne sel
ect ed, use it to get
add er . Fir stN um ber = CD the res ult .
bl (tx tNu mb erl .Te xt)
add er.S eco ndN um ber =
CD bl (tx tNu mb er2 .Te xt)
txt Re sul t.T ext = CS tr
(ad der . Su btr act )
Els e
'If cal cul ato r sel ect ed,
use it to get the res
cal c.F irs tNu mb er = CD ult .
bl (tx tNu mb erl .Te xt)
cal c.S eco ndN um ber = CD
bl (tx tNu mb er2 .Te xt)
txt Re sul t . Tex t = CS tr
(ca lc . Su btr act )
End If
End Sub

Pri vat e Sub btn Mu ltip


ly_ Cli ck( ... ) Ha ndl es
'M ult ipl y two num ber s. btn Mu ltip ly. Cli ck
cal c.F irs tNu mb er = CD
bl (tx tNu mb erl .Te xt)
cal c.S eco ndN um ber = CD
bl (tx tNu mb er2 .Te xt)
txt Re su l t . Tex t = CS tr
(ca lc. Mu ltip ly)
End Sub

Pri vat e Sub btn Div ide


_ Cli ck ( ... ) Ha ndl es btn
'Di vid e two num ber s. Div ide .Cl ick
cal c . Fir stN um ber = CD
bl (tx tNu mb erl . Tex t)
cal c.S eco ndN um ber = CD
bl (tx tNu mb er2 .Te xt)
txt Re sul t . Tex t = CS tr
(ca lc.D ivi de)
End Sub
End Cla ss 'frm Ca lcu lat e

Cla ss Ad din gM ach ine

Pu bli c Pro per ty Fir stN


um ber () As Do ubl e
Prog ram ming
522 • Ch apter 11 Ob jec t-O rien ted

e
ond Nu rnb e r () As Do ubl
Pu bli c Pro pe rty Sec

ubl e
Fu nct ion Ad d() As Do
stN urn ber + Sec ond Nu rnb er
Re tur n Fir
End Fu nct ion

As Do ub l e
Fu nct ion Su btr act ()
- Sec ond Nu rnb er
Re tur n Fir stN urn ber
End Fu nct ion
End Cla ss 'Ad din gM ach ine

Cla ss Ca lcu lat or


ine
Inh eri ts Ad din gM ach ber and Sec ond Nu rnb er
eri ts pro pe rti es Fir stN urn
'Ca lcu lat or inh
and Su btr ac t() .
'an d fun cti on s Ad d()

As Do ubl e
Fu nct ion Mu ltip ly( )
Re tur n Fir stN urn ber * Sec ond Nu rnb er
End Fu nct ion

Do ubl e
Fu nct ion Div ide () As
Re tur n Fir stN urn ber I Se c ond Nu rnb er
End Fu nct ion
End Cla ss 'Ca lcu lat or
the Calculator radio but ton ,
12 and 3, and clic k on the + and - but ton s. C lick on
[Ru n, type in
but ton s.]
and click on the +, - , X , and

~~ ... Ca lcul a ·a ns l= i §J I~ d

Rrst Number: 12

Second Number: 3

Machine
- Add ing
Machine
-
1 1 Calculat or

Resutt : 4

Polymorphism and Overriding ss int erf ace . ln essence, the


tho ds, and eve nts for a class is called the cla
The set of pro per tie , me sses Ad d ingMachi ne
def ine s how it sho uld beh ave . The interfaces of the cla
interface of a class 3.
mple 1 are sho wn in Tab le 11.
and Ca lculat or used in Exa tio n 11.1. Bo th tud ent and PFS
tud ent
der the cla sses use d in Exa mp les 1 and 2 of Sec
me ste r gra de dif-
Co nsi ing a se
int erfa ce, eve n tho ugh the y carry out the tas k of com put
have the same
fere ntl y. See Table 11.4.
11.3 Inh erit ance
• 523

1'4:J!IIII Interfaces used in Example 1.


Add ing Ma chin e Cal cul ato r
Pro per ties Firs tNu mbe r Firs tNu mbe r
Sec ond Num ber Sec ond Num ber
Me tho ds Add Add
Sub trac t S ubtr act
Mu ltip ly
Eve nts Divide
(no ne) (no ne)

1'4:JIIIJI Interfaces used in Examples 1 and 2


in Section 11.1.
Stu den t PFS tud ent
Pro per ties Nam e
Nam e
Soc Sec Num
Soc Sec Nu m
Mid term
Mid term
Fin a l
Me tho ds Final
Cal cSe mG rade
Eve nts Ca lc emG rad e
(no ne)
(no ne)

If a pro gra mm er wants to write


a program tha t manipu late s obj
he or she nee d onl y know how ect s from these two classes,
to use the interfac e. Th e progra
wit h wh at specifi c imp lem ent mm er need not be con cer ned
atio n of tha t inte rface is being
acc ord ing to its specific implem use d. Th e obj ect wi ll the n beh ave
ent atio n.
Th e progra mm er nee d onl y be
awa re of the Cal cSe mG rad e me
ce rned abo ut its implement at tho d and nee dn 't be con -
ion. The fea ture tha t two clas
nam ed the same and have esse ses can hav e me tho ds tha t are
ntia lly the sa me purpose, but diff
pol ym orp his m. ere nt implement atio ns, is call ed
A progra mm er may employ pol
ymorphism in thr ee easy steps.
ods, and eve nts tha t ma ke up an Firs t, the properties, me th-
inte rface are defined. Sec ond ,
forms the fun ctio nal ity dic tate a par ent class is cre ated tha t per-
d by the inte rfac e. Fin ally, a chi
ove rrid e the me thods tha t req ld class inh e rits the par ent and
uire diff ere nt implement atio n
Ov err ida ble is used to des ign tha n the par ent . Th e keywo rd
ate the par ent 's me tho ds tha t
wo rd Ov err ide s is used to des can be ove rridd en, and the key
ignate the child's me tho ds tha -
Th ere are situ atio n where a chi t are do ing the ove rriding.
ld class needs to access the par
a me thod tha t the child is ove ent cla s 's implement atio n of
rriding. Visual Bas ic prov ides
this functionality. the keywo rd My Bas e to suppor
t
Co n ide r the cod e from Examp
le 1 of Sec tion 11.1. To emplo
Ov rrid ab le is inse rted into the y polymorphism, the keywo rd
hea der of th e Ca lcS em Gra de
me tho d in the tud ent class:
Ov err ida ble Fun ctio n
Cal cSe mGr ade ( ) As Str
ing
Th e PFS tud ent clas inh erit s
all of the properties and me tho
the Cal cSe mG rade me thod as ds from its par ent , ove rriding
foll ows:
Cla ss PFS tud ent
Inh eri ts Stu den t
ed Progra mm ing
524 • Ch apt er 11 Ob jec t-O ri ent

ing
Ca lcS em Gra de( ) As Str
Ov err ide s Fu nct ion est er
for the sem
'Th e stu de nt' s gra de
If My Bas e .Ca lcS em Gra
de = "F" Th en
Re tur n "F ail "
Els e
Re tur n "Pa ss"
End If
End Fu nct ion
End Cla ss 'PF Stu den t

t informatio n and display the


ow ing pro gra m, the use r can enter studen
Exa mp le 2 In the foll perties fro m its parent Stu -
s. Th e PFS tud ent cla ss inherits all of the pro
semester grades for the clas n.. The btn.En.ter_C lick
lcS em Gra de me tho d with it own imp lementatio
den t, but overrides the Ca y. Ho we ver, the
ele me nt cre ate d by eith er class into the students arra
eve nt proced ure sto res an thus
ments are from wh ich class,
lick eve nt pro ced ure doe s not need to kno w which ele ure , the sta te-
btnDisplay_C eve nt proced
ym orp his m. No te: In. the six th line of the btn._Ente r a Stu den t.
dem ons trat ing pol Stu den t is
den t () is val id, sin ce, due to inheritan ce, every PF
me nt pu pil = New PF Stu
PROPERTY SETTING
OBJECT
Tex t Sem este r Gra de
FnnG rades
o::t Sem ste r Grade Tex t Na me:
lblN am e
txtN am e
Name : Tex t SSN :
lblS SN
Midterm : Final: Ma sk 000-00-0000
SSN : _ _ _ mtb SSN
Tex t Mid term :
lblM idte rm
Gra ding Opt ion
Pas s/ Fail txtM idte rm
o Lett er Grade Tex t Final:
lblFin al
txtF ina l
Gra din g Op tion
.Enter Information .Qisplcrl Grades grp Grad ing Op tion Tex t
Tex t Let ter G rad e
radLet te rG rad e
C hec ked Tru e
Tex t Pass/Fail
radPas Fail
Tex t &E nte r
btn Ent er
InFo rma tion
Tex t &D isp lay Gra des
btn Ois p lay
Tex t &Q uit
btn Qu it
dgv Gra des

des
Pu bli c Cla ss frm Gra 'St ore s the cla ss
den ts( SO ) As Stu den t to stu de nts ( )
Dim stu 'La st stu de nt add ed
As Int eg er = -1
Dim las tSt ud ent Ad ded
btn En ter . Cl ick
_ Cl ick ( ... ) Ha ndl es
Pr iva te Sub btn En ter
o the arr ay .
'St ore s a stu de nt int
t
Dim pu pil As Stu den n the rad 1o bu tto n.
e the ap pro pri ate ob jec t dep end ing upo
Cr eat
ed The n
If rad Pa s sF ail .Ch eck
pu pil New PF Stu den t ()
Els e
pu pil New Stu den t ()
End If the ob jec t .
the tex t box es int o
'St ore the va lue s in
.Te xt
pu pil . Name = txt Na me
11.3 Inheri tance • 525

pupil.S ocSecN um = mtbSSN .Text


pupil . Midterm = CDbl (txtMid term.T ext)
pupil . Final = CDbl (txtFin al.Tex t)
'Add the studen t to the array.
lastStu dentAd ded += 1
studen ts(lastS tudentA dded) =pupi l
'Clear text boxes and list box.
txtNam e. Clear ()
mtbSSN . Clear ()
txtMid term.C lear()
txtFin al.Cle ar( )
Messag eBox .Show( "Stude nt #" & lastStu dentAd ded + 1 &
" recorde d. " )
txtNam e . Focus ()
End Sub

Private Sub btnDis play_ Click( ... ) Handle s btnDis play.C


lick
ReDim Preserv e studen ts(lastS tudentA dded)
Dim query = From pupil In studen ts
Select pupil.N ame, pupil.S ocSecN um , pupil.C alcSem Grade
dgv Grades .DataS ource = query . ToList
dgvGra des.Cu rrentCe ll = Nothin g
dgvGra des.Col umns( "Name" ) .Heade rText = "Stude nt Name"
dgvGra des.Col umns( "SocSec Num" ) .Heade rText = "SSN"
dgvGra des.Col umns( "CalcSe mGrade " ) .Heade rText = "Grade"
ReDim Preserv e student s(SO)
tx tName . focus ( )
End Sub

Privat e Sub btnQui t_ Click( ... ) Handle s btnQui t . Cl i ck


'Quit the program
Me . Close ()
End Sub
End Class 'frmGra des

Class Studen t
'Membe r variab les to hold the proper ty values
Privat e m midterm As Double
Private m final As Double

Public Proper ty Name() As String

Public Proper ty SocSecN um( ) As String

Public WriteO nly Proper ty Midterm () As Double


'The studen t's score on the midterm exam
Set (ByVal value As Double )
m midterm = value
End Set
End Proper ty

Public WriteO nly Proper ty Final() As Double


'The studen t's score on the final exam
Set (ByVal value As Double )
m final = v alue
End Set
End Proper ty
526 • Chapt er 11 O bj ect-O ri ented Progra mming

Strin g
Over ridab le Func tion CalcS emGr ade() As
h 1.de o he seme ster
Dim grade As Doub le
'T~ rade i~ bas d upc verag e of the midte rm and final exam s.
grade = (m_ midte rm + m_ fina l) I 2
grade = Math .Roun d(gra de) ' ·ound the grade .
Selec t Case grade
Case Is >= 90
Retur n "A"
Case Is >= 80
Retur n "B"
Case Is >= 70
Retur n "C"
Case Is >= 60
Retur n "D"
Case Else
Retur n "F"
End Selec t
End Func tion
End Class Stude nt

Class PFStu dent


Inhe rits Stude nt

g
Over rides Func tion CalcS emGr ade() As Strin
tud nt' rade the ceme ster
If MyBa se . CalcS emGr ade = "F" Then
Retur n "Fail "
Else
Retur n "Pass "
End If
End Func tion
End Class
n for three stude nts. Then click on the
[Ente r the data and click on the Enter Information butto
student.]
Displa y Grades butto n, and fina lly enter the data for anoth er

SSN: £1'1' ·~· .. 5Ei78 Midterm : 8Ei

Grc1ding Option
o Letter Grc1de

Enter lntorrncltion

Student Nc1rne SSN


.1'} :~ 7 B9 B

Brown, Brittc:,ny
c~,le . CamI A
11.3 Inheritance • 527

Example 2 employ inheritanc e and overriding to provide functional ity to one child class.
lf a program contains two or mo re children of a class, however, th e techniqu e of overriding can
lead to confusing programs. Visual Bas ic prov id es a cleaner des ign through the use of abstract
classe .

Abstract Properties, Methods, and Classes


Sometime s yo u want to insist that each child of a class h ave a ce rta in property o r method
that it must imp leme n t fo r its own use. S uch a property or meth od is sa id to be abstract and
is declared with the keyword MustOve rride. An abstract prope rty o r method consists of just
a header with no code fo llowi ng it. It h as no cor respo nding End Property , End sub , o r End
Function state ment. Its class is ca lled an abstract base class and mu st be declared
with the
keyword Mustlnhe rit. Abstract classes ca nnot be instant iated; o nly their childre n can be
instantiat ed.

Example 3 The fo llow ing program calculates the area of several regular two-d imensiona l
sh apes, given the length of one side. (A regular hape is a shape whose sides have identical
length and whose interior angl s are identical.) The abstract parent class hape implemen ts the
Length prope rty and decle1res the N ame and A rea funct ions a MustOver ride. N otice that meth-
od declared with MustO .ride do not have any implemen tation code. Each child class inherits
the property from the parent and implemen ts the two functions. The btnOispla y_C lick event
procedure uses polymorph ism to set the shapes' length and display the shapes' names and areas.

OBJECT PROPERTY SETTING


D~ Two-Dim ensional Shapes ~~ § ![};!] frm hapes Text Two-D imen ional
Length of a side : Shapes
Display
lblLength Tex t Length of a side:
txt Length
/'""'"''"' btnOisplay
lstOutput
Text Display

Public Class frrnShape s


'Declare shape array.
Dim shape(3) As Shape

Private Sub frmShape s _ Load( ... ) Handles MyBase .Load


'Populate the array with shapes.
shape(O) New Equilate ralTriang le ()
shape(l) New Square ()
shape(2) New Pentagon ()
shape(3) New Hexagon ()
End Sub

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


Dim length As Double
'Set lengths of all shapes.
length= CDbl (txtLeng th.Text)
For i As Integer = 0 To 3
shape(i) .Length= length
Next
528 • C hapter 11 Object-O riented Programm ing

'Display results .
lstOutp ut.Item s.Clear ()
For i As Integer = 0 To 3
l s tOutput .Items.A dd( "The " & shape( i ) . Name & " has area " &
FormatN umber(s hape(i) .Area)) & " "
Next
End Sub
End Class 'frmShap es

Mustinh erit Class Shape


Public Propert y Length( ) As Double

MustOv erride Functio n Name() As String


'Returns the name of the shape.

MustOv erride Functio n Area() As Double


'Retu ns the area of the shape.
End Class 'Shape

Class Equilat eralTria ngle


Inherit s Shape

Overrid es Functio n Name() As String


'The name of this shape
Return "Equila teral Triangl e"
End Functio n

Overrid es Functio n Area() As Double


'Formula for the area o an equilat eral tr1angl e
Return Length* Length* Ma th.Sqrt( 3) I 4
End Functio n
End Class 'Equila teralTri angle

Class Square
Inherit s Shape

Overrid es Functio n Name() As String


'The name of this shape
Return "Square "
End Functio n

Overrid es Functio n Area() As Double


'Formula for the area oF ~ square
Return Length * Length
End Functio n
End Class 'Square

Class Pentago n
Inherit s Shape

Overrid es Functio n Name() As String


'The name of th1s o ap
Return "Pentago n"
End Functio n
11.3 lnheritance • 529

overrides Function Area() As Double


'Formula for the area of a pentagon
Return Length* Length* Math . Sqrt(25 + (10 * Math . Sqrt(5)) ) I 4
End Function
End Class • >entagon

Class Hexagon
Inherits Shape

Overrides Function Name() As String


'The name ot this sha~e
Return "Hexagon"
End Function

Overrides Function Area () As Double


• Formu for. .he area of hexagon
Return Length * Length* 3 * Math .Sqrt(3) I 2
End Function
End Class Hexagon

[Run the program, enter 5, and click on the Dis[Jlay button.]

Length of a side : 5 Display

~
Equilateral Triangle has area 1 .&3.
e Square has area 25. .
e Pentagon has area ~ . 1.
e Hexagon has area 04 .95.

Comments
1. Visual Bas ic uses inheri tance in eve ry Wind ows applica ti on th at is written. Exam inati on
of an y program's code revea ls that the fo rm's class inherits from the .NET framewo rk class
System. Wind ows. Forms. Fo rm.
2. In Example 2, the btnOisplay_ Click event procedure doe not need to know wh ich e le-
ments of the S tudent array are instances of the S tud ent clas and which are instances of the
PFStudent class. In ome situati ons, however, the program may want to know this. Visual
Bas ic provides t he ex press ion TypeOf ... Is to test if an instance was created from a pa rtic-
ular clas (or fro m th e class' parents, grandparent s, etc.) Fo r example, t he follow ing proce-
d ure counts the number of pass/fa il tud ents in th e students array:
Sub CountPass Fail()
Dim query = From student In students
Where TypeOf (student) Is PFStudent
Select student
Dim numPF = que ry.Count
MessageBox .Show( "There are " & numPF & " pass/fail students out of " &
lastStudent Added + 1 & " students in the class." )
End Sub

3. C hild classes do no t have acces to t he parent's Private member va riables.


530 • Chapter 11 Object-O ri en ted Programm ing

Practice Problems 11.3,

1. In the class A ddingMachine of Example 1, the Add function could h ave bee n defin ed with
Functio n Add() As Double
Return FirstNur nber + SecondN urnber
End Functio n

Exp lain wh y the Multiply function of the class Ca lculator ca nnot be defined with
Functio n Multipl y() As Double
Return FirstNum ber * SecondN urnber
End Functio n
variab le
2. Conside r th e hierarch y of classes shown below. What valu e is ass igned to the
phrase by th e fo llowing two lines of code?
Dim mammal As New Mammals ( )
Dim phrase As String = mammal. Msg
Class Animals
Overrid able Functio n Msg() As String
Return "Can move"
End Functio n
End Class
Class Vertebr ates
Inherit s Animals
Overrid es Functio n Msg() As String
Return MyBase.M sg & " " & "Has a backbon e"
End Functio n
End Class
Class Mammals
Inherit s Vertebr ates
Overrid es Functio n Msg() As String
Return MyBase.M sg & " " & "Nurtur es young with mother' s milk"
End Functio n
End Class
Class Arthrop ods
Inherit s Animals
Overrid es Functio n Msg() As String
e"
Return MyBase.M sg & " " & "Has jointed limbs and no backbon
End Functio n
End Class

EXERCISES 11.3

two classes:
In Exercises 1 through 4, identify the output of the code that uses the followin g
Class Square
Overrid able Functio n Result(B yVal num As Double) As Double
Return num * num
End Functio n
End Class
11.3 Inh erit ance
• 531
Cla ss Cub e
Inh eri ts Squ are

Ov err ide s Fun ctio n Re


sul t( ByV al num As Do ubl
Re tur n num * num * num e) As Dou ble
End Fun ctio n
End Cla ss

1. Dim sq As Squ are =N ew


Squ are ()
txt Ou tpu t.T ext CS tr(s q.R esu lt(2 ))

2. Dim cb As Cub e New Cub e()


txt Ou tpu t.T ext CS tr(c b.R esu lt(2 ))

3. Dim mA s Squ are =N ew


Squ are ()
Dim n As Cub e = New Cub
e()
txt Ou tpu t.T ext = CS tr(m
.Re sul t(n .Re sul t(2 )))

4. Dim mA s Squ are = New


Cub e()
txt Ou tpu t.T ext = CS tr(m
.Re sul t(2 ))

5. Co n ide r the class hie rarc hy


in the second pra ctice proble m.
variable phrase by the fo llow ing W hat va lue is ass ign ed to th e
two lines of code?
Dim ant hro pod As New
Art hro pod s()
Dim phr ase As Str ing
= art hro pod .M sg

6. Co nsid er the class hierarc


hy in the second prac tice proble
var iab le phrase by the follow ing m. Wh at va lue is as ign ed to the
two lines of code?
Dim ver teb rat e As New
Ve rte bra tes ()
Dim phr ase As Str ing
= ver teb rat e.M sg

In Exe rcis es 7 thr oug h 16, ide


ntify the err ors in the code.
7. Cla ss He llo
Fun ctio n Hi( ) As Str ing
Re tur n "hi !"
End Fun ctio n
End Cla ss

Cla ss Gr eet ing s


Ov err ide s He llo
Fun ctio n Goo dBy e() As
Str ing
Re tur n "go odb ye"
End Fun ctio n
End Cla ss

8. Cla ss He llo
Fun ctio n Hi( ) As Str ing
Re tur n "hi !"
End Fun ctio n
End Cla ss
Progra mming
Ch apt er 11 Ob jec t-O rien ted
532 •
Cla ss Gr eet ing s
Inh eri ts Hi ()
As St rin g
Fu nct ion Go odB ye( )
Re tur n "go odb ye"
End Fu nct ion
End Cla ss

9. Cla ss He llo
ing
Fu nct ion Hi( ) As Str
Re tur n "h i!"
End Fu nct ion
End Cla ss

Cla ss Au ssi e
Inh eri ts He llo
ing
Fu nct ion Hi( ) As Str
Re tur n "G 'da y ma t e!"

End Fu nct ion


End Cla ss

10. Cla ss He llo


ing
Fu nct ion Hi( ) As Str
Re tur n "h i!"
End Fu nct ion
End Cla ss

Cla ss Wi thi t
Inh eri ts He llo
Hi( ) As Str ing
Ov err ide s Fu nct ion
Re tur n "He y"
End Fu nct ion
End Cla ss

11. Cla ss He llo


Hi( ) As Str ing
Ov err ida ble Fun c t ion
Re tur n "h i!"
End Fu nct ion
End Cla ss

Cla ss Cow boy


Inh eri ts He llo
ing
Fu nct ion Hi( ) As Str
Re tur n "ho wd y !"
End Fu nct ion
End Cla ss

12. Cla ss He llo


ion Hi( ) As Str ing
Mu stO ver rid e Fu nct
Re tur n "hi !"
End Fu nct ion
End Cla ss
11.3 Inheri tance
• 533

Clas s Drag Race r


Inhe rits Hello

Over rides Func tion Hi() As Strin g


Retu rn "Sta rt your engi nes!"
End Func tion
End Clas s

13. Clas s Hello


Mus tinhe rit Func t ion Hi() As Strin
g
End Clas s

Clas s Gent lema n


Inhe ri t s Hello

Ov errid es Func tion Hi() As Strin g


Retu rn "Goo d day"
End Func tion
End Clas s

14. Clas s Hello


Must Over ride Func tion Hi() As Strin
g
End Clas s

Clas s Euro
Inhe rits Hello

Over rides Func tion Hi() As Strin g


Retu rn "Caio "
End Func tion
End Clas s

15. Must Over ride Clas s Hello


Must Over ride Func tion Hi() As Strin
g
End Clas s

Clas s Sout hern er


Inhe rits Hello

Over rides Func tion Hi() As Strin g


Retu rn "Hi y'al l"
End Func tion
End Clas s

16. Mus tinhe rit Clas s Hello


Must Over ride Func tion Hi() As Strin
g
End Class

Clas s Nort hEas terne r


Inhe rits Hello

Over rides Func tion Hi (ByV al name As


Strin g) As Strin g
Retu rn "How ya doin ', " & name
End Func tion
End Clas s
534 • Chap ter 11 Obje ct-O ri ented Programming

Calc u-
ificC alcu lator that is derived from the class
17. Expa nd Exam p le 1 to use a class Scie nt meti c butto ns.
add ition to the four arith
lator and has an expo nent iatio n butto n in
e and
ent has an abs tract meth od CalcSem Grad
18. Rewrite Exam p le 2 so that the class Stud uden t.
stand s for "Let ter G rade" ) and PFSt
two deriv ed classes ca lled LGS tude nt (LG
ed class
Exe rc ise 25 of Sect ion 11.1. Crea te a deriv
19. Con sid er the class Cash Register fro m cles
at a toll boot h to co llect mon ey from vehi
called FastTrackReg ister that cou ld be used and
processed . Write a progra m using the class
and keep track of th e num ber of ve hicles and two do llar
uld be co llected from each car
havi ng the for m in Fig. 11.7. One dolla r sho
from each truck.

101 .... FastTrack ~~ ~ 18;[1


Type of Vehicle :Jrade :
C Record

o Car TnJck
Count :

Process Vehicle Calcu late verage : a.


! Average
Total Re11enue: Spread: 15
Number of vehicles :

FIGURE 11 .8 Sample outp ut for Exer cise 20.


FIGURE 11.7 Form for Exercise 19.

called
26 of Sectio n 11.1. C rea te a deriv ed class
20. Con side r the class tatis tics from Exe rcise nt calle d N ewS p read .
ad func tio n a nd an eve
Com p leteS ta ts t hat a lso prov ides a Spre d iffer ence
sprea d chan ges. (The spread is the
Video Note This even t sh o uld be ra i ed whe neve r the class es to
e . ) Writ e a prog ram that uses the
Stude nt reg istratio n betw een th e high est and the lo we t grad ber
use r. The prog ra m sh o uld d isp lay th e num
(Homework) ana lyze up to 50 exa m grades inpu t by the ulate A verag e butt o n is
t imes . Whe n the Calc
of grad es and the curre nt sp read at all sa mple o utpu t is
th e ave rage of t he grad es. A
click ed on , the prog ram sh ould disp lay
show n in Fig. 11 .8.
trade
book store's inve n tory. The sto re o rders both
21. Writ e a prog ram that keeps track of a Book
prog ram sh ould defin e an abstract class
books and textb ooks from publ ishers. The ,
Price, and the ordin ary prop erties Qua ntity
that cont ains the MustOve rride prop erty deriv ed from the class
eboo k classes sho uld be
Nam e, and Cost. The Text book and Trad up is
by addi ng a markup. (Ass ume that the mark
Book and should override prop erty Price t from the
k.) The prog ram should acce pt inpu
40% for a trade book and 20% fo r a tex tboo ber of
ing stati stics : total num ber of book , num
u er on book o rders and disp lay the fo llow of the
tota l va lue of the inve ntory. (The va lue
textb ooks , tota l cost of the orde rs, and sells all of the book s in
book sto re can mak e if it
inve nto ry is the amo unt of mo ney that the
stock .) A sa mple outp ut is sh own in Fig. 11.9.
salar ied
kly payro ll of a depa rtme nt that hires both
22. Writ e a prog ram that reco rds the wee ber of
ld acce pt use r inpu t and displ ay the num
and hour ly employees. The progra m shou of
s, the total payro ll, and the average num ber
emp loyees, the num ber of salar ied empl oyee (The
sh ould cont a in N ame and Rate prop erties.
hour s worked. The abstr act cla s Emp loyee hour ly
week ly salary for salaried work ers and the
Rate text box hould be fill ed in with the e
H ourly classes sho uld inhe rit the Emp loye
wage fo r hourly work ers. ) T he Sala ried and
S ummary • 535

a':} Bookstore l = I @] l....tJ .J a~ ayroll l = I @] l!....s:i-1


Type of Book Name:
I
- Textbook
- Trade book
~

Type
Rate :
Name: () Salaried

Quantity: Cost :
- 1G 1 Hourly Hours:

[ Order Book
l Record Employee and Hours

( Display Inventory ) Display Payroll

Total cost : $21 , 422.0 0 Numbe !: o :: e mplo~•ee s : 6


Tot a l value : $25 , 7 1 2 . 80 Salai:i e d e mploye es : 3
:Numbe z: o:: books : 3 7 Tot a l pay!:oll : $3,541 . 2 0
:Numbez: a:: t e xtbooks : 345 Av e z: a g e houz:s woz:k e d : 38 . 7

FIGURE 11.9 Sample output for Exercise 21. FIGURE 11.10 Sample output for Exercise 22.

class and overrid e the method G rossPay that accepts the n um ber of hours worked as a
paramete r. A sa mple output i hown in Fig. 11 . 10. (Hint: U e an array of a structure that
ho lds the employee object and the numbe r of hours worked during the week.)

Solutions to Practice Problems 11.3

1. W hil e rhe derived c lass C a lculato r has access to rhe Propenie and Merhods of rhe base class Add ingMachi ne,
ir does nor have access to irs Pri vare membe r va ri ables.
2. The srr ing "Can move H as a bac kbone Nu rwres young wir h morher's milk"

CHAPTER 11 SUMMARY
1. A n object is an en tity that stores data, has methods that manipulate the data, and can raise
eve nts. A class is a template from wh ich obj ec ts are created. A method spec ifies the way in
which an object' data are manipulated . An event is a message sent by an obj ec t to signal
the occurrence of a condition.
2. Each class is defined in a separate block of code starting with C lass ClassName and ending
with End C lass. Data are stored in member variab le and accessed by procedures ca lled
properties.
3. A prope rty routine contains a G et block to retrieve the value of a member variable or a Set
block to assign a va lue to a member va riable. These procedures can also be used to enforce
constraints and carry out validation.
4. Visual Basic automatically invokes a N ew procedure when an obj ect is created.
5. A n object variable is declared with a statement of the form Dim objectName As ClassName,
and the object is created with a statement of the form obj ectName = New ClassName ( argl,
arg2, ••• ) . These two statements are often combined into the single statement Dim
objectName As New ClassName (argl, arg2, . . . ).

6. A uto-implemented properties enable yo u to quickly specify a property of a class without hav-


ing to write code to Ge t and Set the property.
536 • Chapter 11 O bj ect-Orien ted Programm ing

form
7. Events are declared in the Declarations section of a class with a statemen t of the
Pub lic Event UserDef inedEve nt ( argl, arg2, . . . ) and raised w ith a RaiseEv ent

statemen t. The declarati on tatement for the obj ect mu t include the keyword wi thEvent
s

in order for the event coming from the obj ect to be processed . The header of an event-
.. . )
hand ling procedur e has the form Private Sub procedu reName (parl , par2,
Handles objectNa me.User DefinedE vent .

8. The properties, methods, and events of a class are referred to as its interface.
the
9. Inheritance, which i impleme nted with the keyword Inherits, allows a new class (called
(called the base or parent class ) and
derived or child class) to be created from an existing class
to gain its interface .

10. Polymorphism is the fe ature that two cla ses can have methods that are named
the same and
have essentially the same purpose, but different impleme ntations.
classes to
11. The keywords Overridable, Overrides , Mustlnherit, and MustOve rride allow derived
customize inherited properties and methods.

CHAPTER 11 PROGRAMMING PROJECTS


.
1. Bank Account. Write a program to maintain a person's Savings and C hecking accounts
The program should keep track of and d isplay the balances in both accounts , and maintain
a list of transact ions (d posits, withdrawals, fund transfers, and check clea rings ) se parately
for each account. The two lists of transacti ons should be stored in text fil es.
C onside r the form in Fig. 11.11. The two drop-dow n combo boxes should each con ta in
of
the ite m C hecking and Savings. Each of the four group boxes correspo nds to a type
box
transacti on. (When Sav ings is selec ted in the Account combo box , the C heck group
by typing data into th e text boxes of a
should disappea r.) The use r makes a transacti on
g in the DataGrid View
group box and press ing the associated button. The items appearin

•~ Accounts

Account . [?-:long · I Balance:


51.11 2.50 Today's Date: 11 / 1212010

Deposit Transfet"" D1eck


Transferfrom [ Dlecking •I Pay this amount $
$ Depostt
to the order of
to Savings $
Withdrawal
Transfer Sign Check
$ Wtthdrawal

New
Date Type of Transaction Amount Balance

1012/2010 Deposit s1.ooooo s1. oo


10n12010 Transferfrom Savings S200.00 $1,200.00

10/ 1512010 Check cashed by Bectric Co . S75.00 51.125.00

10/2612010 Withdrawal 550.00 51.075.00

11/ 5/2010 Deposit S37.50 S1 ,11250

FIGURE 11.11 Bank acco unts.


Programm ing Proje cts
• 537

cont rol should correspond to the type of acco unt


that has been selec ted. The capti on of the
secon d label in the Tran sfer group box should
toggle betw een "to C heck ing" and "to Sav-
ings" depe ndin g on the item selec ted in the
"Tran sfer fro m" comb o box. lf a transactio n
cann ot be carri ed out, a message (such as "Insu
fficie nt fund s") should be d ispla yed. Two
tex t files should be main tained (one for each
type of acco unt) and should be upd ated each
t ime a transactio n is carri ed out.
The prog ram should use two classes, Tran sacti
on and Acco unt. The class Tran sacti on
should have properties for transactio n name
, amou nt, date, and whet her it is a cred it
(deposit) or debit (with drawal/ch eck).
The class Acco unt, whic h will have both a chec
king acco unt and a sa vings acco unt
as insta nces, should use an array of Tran sacti
on obj ects. In addit ion , it should have prop-
erties for nam e (C heck ing or Savi ng ) and balan
ce. It should have meth ods to carry out
a transac ti on (if poss ible) and to load the set
of transactio ns from a tex t fi le. The even ts
Insuffi cie ntFu nds and Tran sacti onCo mmi tted
should be raise d at appr opria te times.
2. Writ e a prog ra m for the ga me BlackJ ac k.
See Fig. 11.12 . The prog ra m sho uld use a
DeckO fCa rds class simil a r to th one prese nted
in Exa mple 3 of Sect ion 11.2 .

c_. BlackJack Ga e

5 of Diamond: ]
3 of Hearts
~k of Diamonds
Ace of ~~bs-
6of 0oh~
-l
Plcf'lerTotal: 18 Deale r Tatal: 17

Hit Me J [ Ne'll' Hand Hold

You win

FIGURE 11 .12 Samp le outpu t for Progr amm ing Proje ct 2.


Web Ap pl ica tio ns

12.1 Programming for the Web, Part I 540


• C reati ng a Web Prog ram with Visua l Web Deve
loper • Using a Table to Lay O ut a
Web Page's Con tent • Accessing a Text File in a
Web Program • Bind ing a Cont ro l
to a LINQ Qu ry • Open ing an Exist
ing Web Program • Bu ildin g on an Exist ing Web
Prog ram
12.2 Programming for the Web, Part II 550
• Multiple Web Pages • Validation Cont rols • Po
tback • The Page Load Even t
• C lass-Level Variables • The Radi oBut tonList Con
tro l • The C heckBox Con tro l
12.3 Using Databases in Web Programs 560
• Crea ting a Bar C hart from a Database • Disp lay
ing Data base Information in a Grid
Summary 571

Programming Projects 572

539
540 • Chapter 12 Web Applica ti ons

12.1 Programming for the Web, Part I


ll crea te programs
ran directly und er Win dows. N ow we'
In ea rlier cha pters all of our programs Safa ri) . The pro-
run in a Web brow se r ( uch as Inte rnet Exp lore r, Firefox, C hro me, or
that to use Visual
with Visual Bas ic 201 0 Express; we'l l need
grams in this cha pter cann ot be crea ted k) or a full vers ion
d on the DVD acco mpa nying this boo
Web Developer 2010 Express (provide 0 Express (abbre-
wi ll refer to Vi ual Web Developer 201
of Visual Studio 20 10. Our disc us ion
ified to appl y to Visual Studio.
viat ed as VW D), but it can easily be mod requ ests to
pute r (refe rred to as a clie nt) is mak ing
Wh en you use a Web browse r, your com send a particul ar
er). Some requ es ts ask the se rver to
ano ther com pute r (refe rred to as a serv ided by the cli ent
perform an ope ratio n usin g inpu t prov
Web page. Oth ers require the server to roso ft tech nology
then to retu rn a new vers ion of a page . Visual Web Developer uses a Mic
and
(AS P stands for Act ive Serv er P ages.)
called ASP.NE T to respond to requ ests. Web pro-
ally sepa rate com pute rs, VW D allo ws
A ltho ugh the clie nt and serv er are norm ram, it laun ches a
mpu ter. Wh en VW D runs a Web prog
grams to be deve loped on a single co the prog rams are
serv er and then ope ns a Web brow se r that con nect s to the serv er. Afte r
Web ssed by any com-
a ded icated se rver and can then be acce
developed, they can be tran sferr ed to D requires spec ial
er runn ing programs crea ted with VW
pu te r's Web browse r. A dedi cated serv
t Info rma tion S rvi ces).
Web server soft ware called IIS (Interne

Web Developer
Creating a Web Program with Visual
al Bas ic Win d ows
crea ted in muc h the same way as a Visu
As we will soon see, a Web program is u ghs to be pe r-
a Web prog ram here into three walk thro
Video ote
program. We brea k up the crea tion of the steps of the
thro ugh we prese nt a tabl e showing how
Programm ing
form ed in successio n. Afte r each walk
for the Web their Visual Bas ic cou nterpart s.
Web prog ram wa lkth rough diffe r from
prog ram
Firs t wal kthr oug h : Star ting a new Web rosoft Vis ual
click on All Programs, and clic k on Mic
1. C lick on the Win d ows Start butt on, simi lar to the Visual
programs. (A Start page ve ry
Web Deve loper 20 10 Express in the list of
Basic Start page will appea r. ) O ptio ns dialog
se lect Gen eral from the left side of the
2. C lick on Ojni ons in the Tools menu, (Th is step will
o butt on in the Start Pages in section .
box, and clic k on the Design V iew radi "Tab and
rams. ) O ptio nall y, set the va lue for the
not have to be don e for subseque nt prog
on to close the Opt ions wind ow.
inde nt size" to 2. C lick on the OK butt will appea r. Visu al
menu. (A N ew Web Site dialog box
3. C lick on New W eb Site in the File loca tion." If
c hou ld be sele cted as the Inst alled Temp late and File Sys tem as the "We b
Basi
not, cha nge these items. ) tion and name of
The wide com bo box at th e cent er-b otto m of the d ialog box gives the loca
4. the name to
WebS ite I.) We reco mm end cha ngin g
the prog ram . (Th e defa ult name wi ll be e path .
you might wan t to cha nge th
somethi ng like MyW ebProgram. A lso, mod e. See
ble- clic k on ASP .NE T We b Site. The IDE for VW D appea rs in de ign
5. Dou tab "Ma in-
be ente red insid e the red rect ang le with
Fig. 12 .1. The tex t and con trols will regi on.
this regio n as the Mai n Con tent
Con tent (C usto m) ". We will refe r to
star ting a
start ing a prog ram in VW D diffe rs from
Tab le 12. 1 shows three ways in whi ch
program in Visual Bas ic.
Web page
Sec ond wal kthr oug h: Des igni ng the
at ion of the first walk thro ugh.
Not e 1: Thi s walk thro ugh is a con tinu same way as in
a page and form atted in somewh at the
Not e 2: In VW D, text can be type d into
a word processo r.
12.1 Prog ramm ing for the Web, Part l
• 541

Account
App_Data _
Script>
Styles
1> jj] About. a spx

can also fmd docu ment ation on ASP.NET


at MSDN .

rrr

FIGURE 12.1 The VWD integ rated deve lopm ent envi ronm
ent in design mode.

IM:JIIfJI Web program counterparts to starting a Visual Basic


program.
Visu al Basic Wind ows Prog ram
VWD Prog ram
1. Program ca n be crea ted with Visua l
Basic Program must be crea ted with Visua l Web
Expr ess.
Deve loper Expr e s o r Vi ual S tudio .
2. You launc h a program by click ing on New
You launc h a program by clicking on New
Project from the File menu and then double-
Web Site from the File menu and then
clicking on Wind ows Form s Application.
double-cli cking A SP.N ET Web Site.
3. The name give n to a program when it
is The name given to a program when it is
launc hed is temp o rary. The actua l name is
launc hed is perm anen t. It is not spec ifi ed
specifi ed with the Save All comm and.
after you click o n the Save A ll butto n.

1. Sele ct the text in th e Ma in C onte nt


regio n and then press the DEL key to dele
in the regio n. te the text
2. Type the word s "Tip C alculator" into
the Main Con ten t window, drag the curso r
two word s and click on across the
the Bold butt on ( B ) on the Toolbar. (The
bold face . Oth er butto ns on the Toolba r can word now appea r in
be used to chan ge the font nam e, the font
and the foreg roun d and background colo rs size,
of the word s.)
3. Press the Ente r key and type the word
s "Cos t of mea l:". (No tice th at a faint blue
with the tag labe led p appe ars. Thin k of recta ngle
p as stan ding for "paragra ph". As with a word
proce sor, the press ing of the Ente r key crea
tes a new paragrap h.)
542 • Cha pter 12 W eb App licat i o ns

in the Standard
dou b le-click on the Tex tBox co ntro l
4. Press the space bar twice and then t is, at the
box appears at the inse rtion poin t (tha
group of the Too lbox. N otice that a text
cursor loca tion ).
the Alphabetize
d. In the Prop erties window, clic k on
5. Make sure that the tex t box is se lecte and set the value of
top of the Prope rties wind ow,
butt on, loca te the ID prop erty nea r the Bas ic's Nam e
property is the cou nter part to Visual
the ID property to txtC ost. (VW D's ID
tex t box read s "asp :Tex tBox #txt Cos t".)
prop erty. N otice that the tab above the
cen t tip (suc h
tion the cursor to the righ t of the text box , press the Ente r key, type "Per
6. Posi con trol in
twic e, and double- clic k on the TextBox
as, 15, 18.5 , or 20):", press the space bar
the Too lbar. (An othe r text box appears.)
erce nt.
7. Set the text box's 10 property to txtP k on the But-
text box, press the Ent er key, dou ble-clic
8. Position the cursor to the righ t of the butt on's ID
appe ars at the inse rtion poin t), set the
ton con trol in the Too lbox (a butt on
t property to "Ca lcu late Tip".
property to btnC alcu late, and set its Tex
"Am oun t of tip:",
the butt on, press the Ente r key, type
9. Position the cursor to the righ t of lbox (a text box
k on the Tex tBox con trol in the Too
press the space bar twice, double-clic ip, se t its Rea dOn ly
text box's ID prop erty to txtT
appe ars at the inse rtion poin t), set the scre en now
or to the righ t of the text box. The
prop erty to True, and pos ition the curs
appears as in Fig. 12.2.

ercent tip (such as 15 18 5 or 20):

Ca lcu lat e Tip


............................ ..................... ......................
............................................ ....................................
............................... ,
............................. ............................................
....................................... ,

Ill

Design j Cl Split @I Source

FIGURE 12.2 The Desi gner for our prog ram.


12.1 Programming for th e Web, Part I
• 543

The coLmterpa rt in VWD of a Visua l Ba ic Wind


ows fom1 is referred to as a Web page. Table 12.2
shows even ways in whic h designing a Web page
d iffers from desig ning a Visua l Ba ic fo rm.

lfi':J!IfiJ Web page counterparts to designing a Visual Basic Wind


ows form.
Visual Basic Windows Form VWD Web Page
1. Ther e is no cursor on the form des igner. The page desig ner has a curso r (also referr ed
to as the insertion point).
2. Text to appea r perm anen tly on a form is usual Perm anent text (ca lled static text) can be
ly
placed in a label and formatted with settin gs typed direc tly into th e page at the insertion
from the Properties window. point and fo rmatt ed from the Too lbar in the
same way as text typed into a word proces or.
3 . The most frequently used contr ol (such as Th e most freq uentl y used co ntrols (such as
But-
ton, LisrBox, and TextBox) are found in th e Butto n, ListBox, and TextBox ) are found in
Common Controls group of the Toolb ox . the Standard group of th e Too lbox .
4. Whe n you double-cl ick on a contr o l in the Whe n you doub le-cl ick on a contr ol in the
Tool-
box, the contr ol appea rs eithe r in th e upper-left Toolb ox, the control appea rs at the insertion
corne r of the form or just be low th e most
point .
recently created contro l.
5. The name of a contr o l is specified by settin
g its The name of a control is spec ified by sett ing
Nam e property.
its 10 prope rty.
6. In design mode, contr o ls are place d anywhere
on In des ign mode, text and contr o ls are placed
a form and align ed with the Format menu.
in a top-to- botto m fas hi on, each entered at
the insertion point .
7. The tab for the Designer reads "frmName.vb
Th e tab fo r the Designer reads
[Design]".
"Defa ult.aspx".

Thir d walk th roug h: Codi n g and exec uting


a Web prog ram
Note : This walk throu gh is a cont inuat io n of the
secon d wa lkthr o ugh .

1. Doub le-cl ick on the Calculate butto n. (Th e Code


Edito r wi ll appe ar with a temp la te for the
butto n 's defaul t event proce dure, btnC alcu late_ C lick . In VWD ,
th e code in the Code Ed i-
tor is ca lled the code -beh ind.)
2. Type the fo llow ing three lines of code into
the btnC alcu late_ C lick even t proce d ure:
Dim cost As Doub le = CDbl (txtC ost.T
e xt)
Dim perc ent As Doub le = CDbl (txtP
erce nt.T ext) I 100
txtT ip.T ext = Form atCu rrenc y(pe rcen
t * cost )
3. Press Ctrl + FS to run the progr a m with o ut debu gg ing. (Yo ur Web brow
a few secon ds. Figur e 12.3 shows th e uppe r-left ser wi ll o pen afte r
corn er of the W eb page in the brow ser.)
4. Type 20 in to txtCo st, type 15 into txtPe
rce nt, and click on the butto n . The va lue
will appe a r in txtTi p. $3.00
5. C lick on the brow ser's Close butto n to term
inate the program and retur n to the Code
tor. Noti ce that the tab for the Code Edito Edi-
r reads Default.a spx.vb. (An O utpu t wind
appe ars below the Code Ed itor. Yo u ca n remo ow
ve the O utpu t wind ow by clic king on its C lose
butto n.)
6. At this po int you can a lter the code
in the Code Edito r if desired o r click o
Default.aspx ta b o r retur n to the Des ign e r a nd make n the
fu rther ch anges to the fo rm.
544 • Chap ter 12 Web A pplica ti ons

Tip Calculato r

Cost of meal:

Percent tip (such as 15, 18.5 or 20):

[ Ca lcula te Tip

Amount of tip:
ram is run.
FIGURE 12.3 Con tents of the Web brow ser after the prog

prog ram and then click o n Close Proje


ct in the File
7. C lick o n the Save All butto n to save the VW D, cl ick on
l S tudi o inste ad of
men u to clos e the prog ram . (No te: If you are usin g Visu a
prog ram .)
Close Solution in the File me nu to close the
rs from cod-
ing and exec utin g a W eb prog ram diffe
Tab le 12.3 sh o ws fo ur ways in wh ich cod
ing an d exec ut ing a Visu al Bas ic form.

uting a Visual Basic program.


lf!1:J!Ifll Web program counterparts to coding and exec
Web Prog ram
Visu al Basic Program
e.vb". The tab for the Code Edito r read
1. The tab for the Code Edito r reads "frm Nam
"Defaul t.aspx.vb".
or click- We will usua lly run a prog ram by press ing
2. We u ually run a prog ram by pressing FS
gging button on the Toolbar. Ctrl + FS to start without debugg ing.
ing on the Start Debu
as a Win dows app lica ti on. Prog rams are run in a Web browser inter act-
3. Programs are run
ing with a Web se rve r.
the Prog rams are terminated by closing the
4. Programs are terminated by cl ickin g on
n or press ing A lt + F4. browse r.
for m's Close butto

tent
Using a Table to Lay Out a Web Page's Con
ing as thos e we
seco nd wa lkth ro ugh is n ot as nice look
The layo ut of the page crea ted in the t boxe would be
In o ur Visua l Bas ic d sign , the thre e tex
h ave been crea ting with Visu a l Bas ic. cont ro l can be
e red h o rizon ta lly in the fo rm. A table
left- a lign ed and the button wo uld be cent
ran ce of the W eb page .
used with VW D to improve the appe a plac ed into
ce lls, whe re text and/ or cont ro ls can be
A table cont ro l is a recta ngul a r array of fo llow ing walk -
re used to align text and cont ro ls. The
each cell. The colu mns of the tab le a
d ve rsion of the previo us prog ra m.
thro ugh uses a table to crea te an imp rove
12.1 Progra mm ing for the Web, Par
t1 • 545
A tab le wa lkt hro ugh : Us ing
a table to imp rov e the design
No te: Th is wa lkth rou gh is a of a Web pro gra m
not a con tin u atio n of the pre
same pro gra m, but wit h a mo vio us wa lkt hro ugh s. It produc
re attr act ive page des ign. es the
1. S tart a new We b program
wit h the name Tip Ca lculator,
Co nte nt reg ion as before . and clear the con ten ts of the
Ma in
2. C lick on Ins ert Tab le fro m
the Table me nu to pro duce the
Fig. 12.4. Inse rt Table di alog box sho wn
in

In se rt Tab le
l1t I~
Size
-- -
...
Row s: I~ ... Colu mns: 12 ...
'";"'
Lay out - ----
Alignment: Default
B [{] Spedfy wid th:

Floa t: Default
EJ! 1100 I n pixels
( In per cen t
Cell padding: 11 ...
... 0 Spe dfy heig ht:

Cell spadng: 12 ... In pixels


'";"' jo
In perc ent
Borders -
----
Size:
lo ...
...
Color :

D Collapse table border


TD
Background
-- --
Color:

~ Use background picture


T0
I [
Set
Browse .. .
l PropertJes ..
-- -
D Set as default for new tables

[ l
OK [ Cancel
l
FIGURE 12.4 Th e Insert Table dialog box.

3. Set the num be r of rows


to 5 and th e num ber of co lum
boxes will be placed righ t-ju ns to 2. (Th e labels for the
stified int o the firs t col um n tex t
left -justified int o the seco nd and the tex t boxes will be placed
col um n.)
4. C lick on the first In pixels
radio but ton and cha nge the
box from 100 to 500. (Th e tab num ber in the acco mp any ing
le wi ll be 500 pixels wid e. ) tex t
5. C lick on the OK but ton to
gen erate the fain t 5-by-2 grid
the grid at des ign tim e to alig sho wn in Fig. 12.5 . (We will
n tex t and con tro ls. Th e grid use
will not be vis ible at run tim
e. )
ion s
Ch apt er 12 We b Ap p lica t
546 •

:::::::::::::::::::::::::::::::::::::::::::::::::::::::J l::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::J!......
1l::
..
:::: ..
.... ..
::::: :::
.... ::::: ::::: ::::: ::::: ::::: :::::
...... ::::: ::::: ::::: ::::: :::::
:::: :::: :::: :::: : ::::: ::::!
......
...... ::::::::::::::::::::::::::::::::::::
:!::
..
..
:::: :::: :::: :::::::: :::: :::: :::: :::::::: :::: :::: ::Jl ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::JI......
ll::: :::::::: ..
....
...... ::::: ::::: ::::: ::;;; ;;;:: : :::: :::: :::: :::! :::: :::: :::: :::: ::::
:::: :::: :::: :::: :::: :::: ::::
:::: :::: :::: :::

:!::: ::::: ::::: ::::: :::::


two col um ns.
FIGURE 12.5 A tab le wit h five row s and

w ( l) appears; the n
r the top of the firs t col um n unt il a down-arro
6. H over the mouse ove the Properties
but ton . (T he firs t col um n has now bee n selected. ) In
click on the left mo use ent ries in tha t colu mn to be
ign pro per ty to right. Th is will cause the
window , set the Al the righ t colum n, sin ce
No te: Th ere is no nee d to set the A lign property for
right-justified.
its defau lt alignm ent is left. the cu rso r to the second
o the firs t col umn of the second row. Move
7. Type "C ost of me al:" int Toolbox. (A tex t
row and dou ble -di ck on the Tex tBox con tro l in the
col um n of the sec ond st by set tin g its ID
ins erti on poi nt. ) Giv e the tex t box the name txt Co
box appears at the
property to txt Co st. 5, or 20):" int o the left
sim ila r to Ste p 7 to pla ce "Pe rce nt tip (su ch as 15, 18.
8. Use a process t into the right colu mn.
a tex t box named txt Per cen
col um n of the third row and
the left col um n of the fifth
ces s sim ilar to Ste p 7 to place "A mo unt of tip:" into
9. Use a pro colum n.
named txtTip into the righ t
row and a read-on ly tex t box r Modify in
cel ls in the firs t row to select the row. Th en hov er ove
10. Drag the mouse ove r
the reduced from two cells
nu and clic k on Me rge Ce lls. (Th e first row will now be
the Table me
to one celL) "Tip Ca l-
hli ght ed, set its A lign pro pe rty to center, type the words
11. Wi th the first row stil
l hig
cul ato r" int o the row , and make the words boldface.
lcu late and tex t "C al-
ila r to Ste ps 10 and 11, place a but ton named btn Ca
12. In a ma nne r sim
the fou rth row.
cu late Tip" in the cen ter of
eous space. The best way to
col um ns, row s, and tab le to remove extran
13. Resize the tex t box es, column, hover the mo use
cha nge the val ue of its Wi dth property. To resize a
resize a text box is to ble-arrow ( <J=O )
on the righ t side of the column until a horizontal dou
over the double bar the bottom
To resi ze a row , hov er the mo use over the double bar at
appears; the n drag the arro w.
g the arrow. To resize the table,
tica l dou ble-arrow ( ~ ) appears; the n dra
side of the row unt il a ver cross ( ~ ) appears; the n
upp er-left com er of the tab le Lmtil an arrow
hover the mo use ove r the resized by dragging its
u e but ton . Th e tab le wi ll now be selected, and it can be
dic k the left mo sho uld loo k like Fig. 12.6.
nte nt reg ion of the Web page
sizing handles. The Ma in Co
o the btn Ca lcu late eve nt
l ick on the but ton and ent e r the follow ing cod e int
14. Do ub le-c
pro ced u re:
= CD bl (tx tC ost . Te xt)
Dim co st As Do ubl e Te xt) I 100
e = CD bl (tx tPe rce nt.
Dim pe rce nt As Do ubl
urr enc y(p erc ent * co
st)
txt Tip .Te xt = Fo rm atC
12.1 Progra mmin g for the Web, Part I
• 547

Tip ~alc .':lla~or Tip Ca cu ato


c~·~t of. ~leai:J Cost o.: meal: 4S
Percent t1p 1such as 15 13.5 20)~),....---.. :Jercent np (such as 13. 18.3 . .::'C 1: 2 0

Calcu late Tip J Calcula e Tip ]


Amount of t1p4 r~.mount o.: tip· S9 _00
FIGURE 12.6 Web page in design mode. FIGURE 12.7 Web page in run time.

15. Press Ctrl + FS to run the program, enter value


into the first two text boxes , and click o n
th e butto n . Figur e 12.7 sh ows a poss ible o utput .

Some addit ional fea tures of tables are as follows:

1. In the walkt hrough we used a down -arrow to elect


an entire colu mn. To select an entire row in
an analogous way, hover the mou e over the left side
of the row until a right-a rrow (-+) appea rs;
then click the left mouse butto n.
2. To add a new row to a table, click o n a row of
the table , click o n Insert in the Table menu ,
and click o n Row A bove o r Row Below. A sim ilar
process can be used to add a new colum n.
3. To de lete a row or colum n fro m a table, hove r
ove r Delete in the Table menu , and then click
on Delete Rows o r Delete Columns .
4. To dele te a table, hove r the mo use ove r the
uppe r-left corne r of the table unt il an arrow
cross appea rs, press the left mouse butto n to elec
t the entir e table , and then click o n the
DEL key.
5. Both rows and cells have an Align prope rty.
6. The A li gn prope rty specifies ho rizon tal align
menr . Th valign prope rty peci ies vertica l
align ment.

Accessing a Text File in a Web Program


W ith Visua l Basic, we placed tex t files in th e progr
am's bin \Debug folde r and accessed the file
with a state ment of the form

Dim strAr rayN ame( ) As Strin g= IO.F


ile.R eadA llLin es(fi lespe c)

VWD does not have a bin \ Debug fold er. W ith


VWD , tex t files are usua lly place d in the
App_ Oata fo lde r of the So lution Exp lo rer wind ow
and accessed with a state ment of the fo rm
Dim strAr rayN ame( ) As Strin g =
IO. File . Read AllL ines (Map Path ( "App_
Data \" & filen ame) )
We can then use LINQ with such an array, as we
did ea rlier with Visua l Bas ic programs.
548 • Chapter 12 Web Applications

Binding a Control to a LINQ Query


res ults of a LIN Q qu ery in a list box:
The fo llow ing pair of state men ts displ ay the
lstB ox.D ataS ourc e = quer y
lstB ox . Data Bind ()
fo l-
View cont rol is the Grid View cont ro l. The
In VWD , the co unte rpart of the DataGrid
cont rol to a query:
low ing pair of state men ts bind a Grid View
grvG rid.D ataS ourc e = quer y
grvG rid.D ataB ind( )
size .
tCell prop erty to N othi ng, or to spec ify its
T here is no need to set a G ridV iew's C urren does not use row
By defa ult a Gr idView cont rol
(VW D will auto matically size the cont rol.) . A lso,
isib le property that need s to be set to False
headers, therefore there is no RowHead ersV ers ca n
erty of a list box to N othi ng. Column head
there is no need to set the Se lectedl te m prop
be specified with state men ts such as
head er for firs t colu mn
grvG rid.H eade rRow .Cel ls(O ) . Text
t head er for seco nd colu mn
grvG rid.H eade rRow .Cel ls(l) .Tex

Opening an Existing Web Program


walk -
ebProgram that was crea ted in the first three
The fo llow ing step open the program MyW
th rough :
.
1. C lick on Open Web Site in the File menu
that was crea ted in the walk throu gh.
2. Nav igate to the folde r named MyW ebProgram it. )
curre ntly loaded, you may be prom pted to save
3. Click on the Open butto n. (If a program is
Solu -
le, right -click on the file Defa ult. aspx in the
4. If the Designer or Cod e Edito r is not visib
ner or View Code.
tion Explorer wind ow and click on View Desig

Building on an Existing Web Program


ed pro-
e a new prog ram that exte nds an already creat
Some exerc ises in this text require you to creat nd time:
ng to design the page and ente r the code a seco
gram . The fo llowing steps save you from havi

1. Start the new prog ram, note the path


to its folde r, and close the new program.

2. Lau nch W indo ws Explorer. and


ram, press C trl + A to selec t its cont en ts,
3. Ope n the folde r cont aining the old prog
C lipboa rd .
press Ctrl + to copy the cont ents of the folde r into the
, press
ram, press C trl + A to select its cont ents
4. Ope n the folde r cont aining the new prog of the old
C trl + V to paste the cont ent
the DEL key to dele te the co nten ts, and press
fo lder into the new folde r.
ions in the File menu, and click on the first line
5. In VWD , click on Rece nt Projects and Solut
of the drop-down list that appea rs.
eed to
copy of the old program. You can now proc
You have crea ted a new prog ram that is a
make mod ifica tions.

Comments
Web program, click on New Web Site, not
New
1. Impo rtant remi nder : Whe n start ing a new on Open Web
exist ing Web prog ram, click
Project, fro m the File menu. Whe n open ing an
12.1 Programming for the Web, Part I • 549

Site, not Open Project, from the File menu. H owever, when clos ing a Web program, click on
Close Project.
2. We have been running Web programs by pressing Ctt·l + FS to run without debugg ing.
H owever, if yo u prefer, you can click on the Start Debugging button in the Toolbar instead.
lf so, you might have to click on an OK button in a dialog box to proceed. A lso, the pro-
gram might still b running after you ex it the browse r. If so, you will h ave to click on Stop
Debugging in the Debug menu to terminate the program.
3. Rena ming a Web program is much ea ier than renaming a Wind ows program. Just close the
program and use Windows Exp lo rer to rename the program's folder.
4. In design mode, the bottom of the Des igner conta ins three buttons labe led Design, SjJlit, and
Source . If you click on the Source button, you will see ASP.NET code co rresponding to the
design of the page. This code can be altered directly to change the page des ign. If you press
the SjJlit button, you will see a split screen showing both the page and its ASP.NET code.

EXERCISES 12.1 . · · - . .

In Exercises 1 through 4, write a Web program corresponding to the outcome shown.


1. 2.
First number: 22 Determine Final Cost
Second number: 45 Price of item: 100

Third number: 33 Percent sales tax: 6'

Fin d umber Item


Largest number: 45 Cost: Sl 06.00

3. 4.
E ter an integer: 4 l 1 po·a o •
Enter an integer: 5 ~

2 po a o ••
Display P oem
/!pa a'a ·I Display Trri angle •••
•••• ~
5. If a bond is purchased for n do llars and sold one yea r later for m do llars, then the discount
rate ism ,~ " and the interest rate is m ~ ", where each is expressed as a percent. Write a Web
program to calcu late the discount rate and interest rate for a bo nd. See Fig. 12.8 .

Bond Rates
Purchase price: 950 Current Dividend Yield
Redemp ion value 1 yr. later: 1000 Most recent ull-year dividend: 1.96

Current share price: 62.89

Discount rate: 5.00% [ Calcula e COY ]


Interest rate: 5.26 ,.:Q Current dividend yield: 3.12%
FIGURE 12.8 An outcome of Exercise 5. FIGURE 12.9 An outcome of Exercise 6.
550 • Chapter 2 Web App li cations

with the formula


6. The urrent dividen d yield for comm on stock is calcul ated
most recent full-yea r d tv tdend
curren t d tvide nd yteld = - - - - - - - - - - - -
curren t share price

stock. See Fig. 12.9.


Wri a Web progra m to calcu late the curren t div id end yield for a
as a Web progra m.
In Exer ises 7 throug h 16, rewor k the examp le or exerci se
7. Exat ple 9 of Sectio n 4.2 8. Examp le 3 of Sectio n 5.1
9. Exet ise 35 of Sectio n 5.2 10. Exe rc ise 36 of Sect ion 5.2
11. Exa11ple 3 of Sectio n 5.3 12. Exercis 11 of Sectio n 5.3
13. Exat ple 3 of Sectio n 6.2 14. Exe rcise 30 of Sectio n 6.1
15. Exe cise 48 of Sectio n 7.1 16. Example 9 of Sectio n 7.1
in which they joined the union .
The file States .txt contai ns the 50 U.S. states in the order
U se thi text file in Exerc ises 17 through 20.
When the use r clicks on the
17. Wri e a progra m whose page contai n a bu tton and a list box.
displayed in the list box.
but on, the names of the states that end with " ia" sho uld be
box. When the user clicks on the
18. Wr· e a progra m whose page co ntains a button and a list
of the names of the states and
but on, the progra m should determ ine the greatest length
length.
the d isplay (in the list box ) all states hav ing names of that
, and a list box. When the user
19. Wr te a progra m whose page contains a text box, a button
states beginn ing with that let-
ent rs a lette r into the text box and clicks on the button , the
ter hou ld be disp layed in the li st box.
t box, and a list box. See Fig. 12. 10.
20. Wr tea program whose page contains two button s, a tex
ing with a vowe l o r all states
Th user should be ab le to d isplay a list of a ll states beginn
determ ine th numbe r of such
be inning with a conso nan t (in a lphabe tical o rder) and
ty.
sta es. Note: List boxes in VWD do not have a So rted proper

Alaba ma "I
Displa y States Beginning with a Vowel Alaska
Ariz.ona
Displ ay States Beginning with a Conso nant A rka nsas
Idaho
lllin o i ~;

Numb er of States: 12 l Indiana


Iowa
Ohi o
Okl ahom a
Orego n
Utah

FIG URE 12.10 An outcome of Exercise 20.

12.2 Programming for t he Web, Part II


VWD and some spec ial f atures of
In this sectio n we exp lore orne contro ls that are uniqu e to
Visual Web Develope r.
12.2 Programming fo r the Web, Part ll
• 55 1

Multiple Web Pages


Web app licati ons co mmo nly u e seve ral Web
pages. The pages co ntain links (ca lled
h yperl inks) that allow the user to nav igate betw Video N ote
ee n pages. A h yperlin k usuall y appea rs on a
page as unde rlined text. Addi tiona l Web pages Multip le
and h yperl inks can be eas ily ad ded to Web Web pages
programs.
The following steps add a new Web page to a progr
am.
1. C lick on the curre nt Web page to ensur e that
it has the focus.
2. C lick on Add New Item in the Website menu. (An
Add New Item dialog box will appea r.)
3. C lick on Web Form in the ce nter pane, type a
name into the Name box, and click on the
Add butto n. (The Designer for the new Web page will
appear and the name of the page in
the Solution Exp lorer will have the ex tensio n aspx.
)
To switc h from one Web page to anoth er in Desig
n mode, right- click on the name of the
Web page in the Solu tion Explorer window, and click
on eithe r View Designer or View Code in
the conte xt menu that appea rs.
Ther e are severa l ways to navigate from one page
to anoth er at run time. The most com-
mon way is to use a hype rlink contr ol (found in the
General group of the Toolbox). The fo llow-
ing walk throu gh adds an add itiona l Web page to the
tip-calcu lato r program from Section 12.1.
Hype rlink walk throu gh
1. Follow the steps in the "Buil ding on an Ex isting
Web Program" discus ion at the end of
Sect ion 12.1 to c rea te a program named TipW ithHe
lp that build s on the progr am Tip-
Calcu lator.
2. Add a new page (that is, Web Form) named H elp.as
px to the program via the Add New
Item entry in the Website menu. (The Designer for the
new page wi ll appea r.)
3. Add text to the new Web page as show n in the
fir t four lines of Fig. 12.11.

Tip Guideline

The stand ard resta urant tip is 1: 0 o to 20° o of your


pretax bilL

If you are dissatisfied \Vith your sen1c e, leave i.: 0 o any•;vay


and tell the mana ger why you \Veren't happy.

Return to Tip Calculator

FIGURE 12.11 The Help. aspx page.

4. Press the Enter key and then doub le-click on


the Hype rLink contr ol in the Standard group
of the Toolb ox to place a hype rlink contr ol be low the text.
5. Set the lD prope rty of the h yperlink co ntro l
to lnkReturn and set the Text property to
Return to Tip Calculator. See Fig. 12.11.
6. C lick on the ellips is butto n in the hype rlink's Navi
gateU rl property Settin gs box. (A Se lect
URL dia log box will appear. )
7. Doub le-click on Default.aspx in the righ t pane
of the Selec t URL di alog box to set the
hyperlink's Navi gateU rl prope rty to ~/Defa u lt. aspx
.
552 • Chap ter 12 Web Appli catio ns

tion Expl orer wind ow and then click on


V iew
8. Righ t-clic k o n Default. aspx in the Solu na l Web page .
igne r fo r the origi
Designer in the cont ex t men u to display the Des the
cont a ining the Calculate TiJJ butto n, h over
9. Place the curso r on the line of the table row will be crea ted
on Row Below . (A blan k
mouse ove r Insert in the Table menu, and click
row.)
in the tab le with the insertion poin t in that
l in the
in the Toolbox to place a h yper link cont ro
10. Dou ble-click on the Hyp erLink co ntrol
new row.
teU rl
property to Tipping Help, and set the N aviga
11. Set the ID prop erty to lnkHelp, se t the Text prop erty, click on the
ng for the N av igate Url
property to ~ jHe lfJ .aspx. (To spec ify the setti Se lect U RL
on Help. aspx in the right pane of the
ellipsis in the Setti ngs box and then click
dialog box that appears.)
re 12.12
a in ing the hype r! ink cont ro l to Center. Figu
12. Set the A lign prop erty of the row cont
shows the Des igne r.

Tip Calculator
I
Cost of mea l:

Percent tip (such as 15, 18.5, 20): I.- --

Calculat e Ti p I
T1ppmg He lp
Amo unt of tip: l
FIGURE 12.12 The Default.aspx page.

rlink . (The H elp page appe ars. )


13. Ru n the prog ram and click on the hype to the
14. Afte r you read the advi ce, click on the
Return to TifJ Calculato r h yper link to go back
late the amo unt of a tip.)
Tip Calculato r Web page. (Yo u can now calcu

Validation Controls
inpu t.
fiv e cont rol that can be used to chec k user
The Validation group in the Toolbox cont ains e Valid a tor co ntro l to
lid ato r cont rol and the Rang
In this section we use the RequiredFie ldVa
auth enticate user inpu t. ta in
ed with text boxes to ensure that they con
The RequiredFieldVa lidat or cont rol is u erties
an item has been selec ted. The two key prop
data and is used with list boxes to chec k that you are
Con tralTo Verify and Erro rMessage . Supp ose
of th e Requ iredF ieldValida tor cont rol are txtB ox and a list box
inpu t text box cont ro l nam ed
adding va lid ation for a page conta ining an call the con-
alid ator cont ro ls will be need ed; let's
cont rol named lstBox . Two RequiredFieldV and in
Co ntro iToVerify in rfvTe xt will be txtB ox
trols rfvTe xt and rfvLi st. The setti ng fo r into the
is clicked on befo re data has been ente red
rfvList will be lstBo x. If a butto n on the page the butt on's C lick even t wi ll
has bee n selec ted, then
text box, or befo re an item in the li t box sage prop erty will be
, the setti ng fo r the Erro rMes
not be exec uted. In both of these situa tions
rol.
disp layed in the Requ iredFieldValida to r cont e of
or con t rol chec ks that an entr y in a text box fall with in a set rang
The Range Va lidat rM es-
e Valid ator cont rol are ontr olTo Verify, Erro
va lues. The fi v key propertie of the Rang Type prop erty
Valu e. The poss ible setti ngs for the
sage, Type, Min im um Valu e, and Max imum imum
are String, Integer, Double, Date, and Curr
ency. The se ttings for the Min imum and Max
12.2 Programming for the Web, Part II • 553

properties should be suitab le for the spec ified type, and the se tting for the Minimum property
should be less than or equal to the setting for the Max imum property. Suppose that the se tting
for the ContralTo Verify property is a text box and that data outs ide of the specified range is
typed into the tex t box. Then the error message will be d isplayed in the Range Va lidator contro l
as soon as the tex t box loses focus.

Example 1 The fo llowing program is an extension of the tip-calcu lator program from
Section 12.1. The RequiredFieldValidator contro l is located to the right of the cost tex t box
and the Range Validator control is located to the right of the percent tip tex t box. When the
user clicks on the button, the program checks to see that a cost has been entered and that the
percentage for the tip is reasonable. (The assumption is made that a tip should neve r exceed
100%. ) To be completely protected, an add itional Requ iredFieldValidator control for the
Percent tip text box cou ld have been added. Figure 12.13 shows the contents of the Designer
and Fig. 12.14 shows the settings for the controls. The two red sentences will not appear ini-
t ially in the Web browser when the program is run.

Tip Calculator
Cost of mea l: l You must enter the cost!
Pe rcent t ip (such as 15, 18.5, 20): I Not a valid percentage!
Calcul ate Tip

Amount of t ip : j
I
FIGURE 12 .13 Design for Example 1.

OBJECT PROPERTY SETTING


txtCost
CostReq uiredFieldVa lidator ContralTo Va lidate txtCost
ErrarMessage You must enter the cost!
Font/Bold Tru e
Fo reCo lor Red
txtPercent
PercentRange Validator ContralTo Va lidate txtPercent
Erra rM essage Nor a va lid percentage!
Type Do ub le
Maximum Value 100
Min imum Va lue 0
Font/Bo ld Tru e
Fo reCo lor Red
btnCalcu late Tex t Ca lcu late Tip
txt Tip Read On ly True
FIGURE 12.14 Property settings for Example I.

Protected Sub btnCalculate_ Click( ... ) Handles btnCalculate.Click


Dim cost As Double = CDbl (txtCost.Text)
Dim percent As Double = CDbl (txt Perc ent.Text) 1 100
txtTip . Text = FormatCurrency(percent * cost )
End Sub
554 • Chapter 12 Web App lications

[Run, enter 15 fo r the tip percent, neglect to enter a co t, and click on th Calculate Tip
button.]

T "p Ca cu a tor
Cost o" eal: You must enter the cost!

Percent tip (such as 15. 18.5. 20): 15


C alculate·
!~ ......................... Tin!
..............1':':'.~

A aunt o.r tip:

Postback
the text
Con ider the tip-calculator program. When the use r enters two proper va lues into
in the tex t boxes are se nt back to the server,
boxes and presses the Calculate button, the va lues
se nt to the Web browser.
the tip calculati on is made, and then an updated page is generated and
to have
The page is said to be posted back to the se rve r fo r processing, and a postback is said
occurred.
-no
When a va lidation control is triggered, the matter is h andled entirely by the browser
requests a new page from the
postback occurs. A lso, no postback occurs when the brow er
server.

The Page load Event


They dif-
The page load event is the Web ana log of the form load even t in a Window s program.
once, whereas the page load event occurs
fer chiefly in that the form load event occurs only
to a page. The reason is
when a Web program is first run and also eve ry time there is a postback
postback
that after a Web page is sent to a browser, the program is terminat ed until another
rst time.
occurs. At that point, for all practical purposes the program is being run for the fi
Therefore, the page load eve nt occurs aga in.
e is
There is a way for you to guarantee that the code inside the page load event procedur
lf ... Then block
executed only once whi le wo rking with a single page. Place the code inside an
e is as fol-
whose conditio n uses the IsPostBack property. The general form of the event procedur
lows:

Protect ed Sub Page_ Load( . .. ) Handles Me .Load


If Not Page.IsP ostBack Then
(code to execute just once)
End If
End Sub

Class-level Variables
do not
Local var iab les act the same in Web programs as they do in Window s programs. They
ex ist after the procedur e terminat es. C lass-
ex ist until a procedu re is called , and they cease to
wheneve r a page is sent to
level variables in a Web program, on the other hand , cease to ex ist
the next
the Web browser. Therefore, whateve r va lues were ass igned to them will be gone when
postback occurs.
be
There are ways to have a value persist be tween postbacks. For instance, a value can
values involve the
placed in a HiddenField control. Some more advanced methods for reta ining
use of session variab les and cookies.
Programming for the Web, Part II
12.2
• 555

The RadioButtonlist Control


Figure 12. 15 shows the form used in Exampl e 3 of Sectio n 4.4. The
four rad io button s are inside
a group box contro l with the caption Age.

11 Admission F<:>e

/lv;Je
Determine Fee
child ( <6)
minor (6-1 /
Fee : <1 .
o adutt (18-S4)

FIGURE 12.15 Exampl e 3 from Section 4.4.

Visua l Web Develo per does not have a group box contro l capable
of holding a list of radio
button s. The counte rpart is the radio-b utton list contro l. The follow
ing VWD wa lkthrough
creates an enhan ced Web form of the program in Fig. 12.15 . The
Web program has the add i-
tional feature that a warning message is disp layed if a radio button
has not been se lected when
the Determine Fee button is clicked on.
A RadioButtonList Walkthrough
1. Start a VWD program with the name Admi sionFee and delete
the text in the Main Co n-
tent region.
2. Place a table havi ng 3 row , 2 co lumns, and width 275px onto the
page.
3. Use the Tab le menu to merge the three cells in the left column
of the table.
4. Type two spaces followed by the word Age into the left column.
5. Double-click on the word Age and make it boldface by clickin g on
the Bold button on the
Tool bar.
6. Positio n the cu rsor to the right of the word Age and press the Enter
key.
7. Double-click on RadioButtonList in the Standard Group of the Toolbox to
place a radio-b utton
list contro l on the page.
8. Set the control 's ID property to rblAges.
9. C lick on the contro l's Tasks button and then click on Edit Items.
(The Listlte m Collec tion
Editor in Fig. 12.16 on the next page appea rs.)
10. C lick on the Add button and then type "child ( < 6)" into the
setting for the Text property,
as shown in Fig. 12. 17.
11. C lick on the Add button and type in "minor ( 6- 17 )" for the Tex
t property.
12. Repeat Step 11 for "adult (18-64 )" and for "senior (65+ )".
13. C lick on the OK button to indicat e that all of the rad io button s
have been added to the list.
14. Place a button with the name btnDet ermine and Text setting "Deter
mine Fee" into the first
row of the right column .
15. Type the word "Fee:" into the econd row of the right column,
and then to the right of the
word add a text box. Set it ID property to txtFee and its ReadO nly
property to True.
16. Place a RequiredFieldVa lidator (with name rfvAge ) in the third
row of the right column .
556 • Chapter 12 Web A pp licatio ns

l istltem Collecti o n Editor


l 'Y I~ ·'"J

Memb ers; Prop ertie ;:

+ L•
L-~ '
+

A dd m l___ _
~---o_K_'__-J) [~__c_a_n_ce_l_~

FIGURE 12.16 Listlt em Collec tion Editor .

Listltem Collection Editor

M embers : Listltem properties:

+] .- A! 1.!: -;:
/. .

~ M&
+ Enabled True
Selected False
ch il d ( <6)j
Valu e

~--A-dd_ _~] [~__R_e_m_·_ov_e__~


~--O_K____~) [~__c_a_nc_e_l_~

trol.
FIGURE 12.17 Listlt em Collec tion Editor fo r a R adioB uttonL ist con
12.2 Programming for the Web, Part ll • 557

17. Set the Contro lToValidate property of rfvAge to rbLAges, set the ErrorMes age property to
"You must select an age!", set the ForeColor to Red, and set the Font Bold property to True.
(See Fig. 12. 18.)

Determine Fee
Age
r child (<6)
Fee:
r minor (6-17)
r adult (18-64)

r sentor (65+) You must select an age!

FIGURE 12.18 D esigner from walkthrough.

18. The rad io-button list contro l is simi lar to the Visual Bas ic list box contro l in that the value
of its Tex t property is the selected item represented as a string. Double-cl ick on the button
and enter the fo llowing code:
Protected Sub btnDetermine_ Click{ ... ) Handles btnDetermi ne.Click
Select Case rblAges . Text
Case "child {<6)"
txtFee.Text = FormatCurrency{O)
Case "minor {6-17)"
txtFee . Text = FormatCurrency{S)
Case "adult (18-64)"
txtFee . Text = FormatCurrency{lO)
Case "senior {65+)"
t x tFee . Text = FormatCurrency{7.5 )
End Select
End Sub

The Check Box Control


Figure 12.1 9 shows the forms from Examp les 4 and 5 in Section 4.4 . In Exa mp le 4 the user first
se lects check boxes and then clicks on the Determine button to obta in the total cost. Nothing
happens until the button is clicked on. In Example 5, an event proced ure is declared that is

D Benefits Menu GJI 8 ![ID


[] Prescription Drug Plan (SJ9.15) D.} Benefits
LJ Dental Plan (.S10.81 )
[] Prescription Drug Plan (sJ9 .15)
U Vision Plan ( 2.25)
[J Medical Plan ($55.52)
EJ Dental Plan ( 10.81 )
LJ Vision Plan ( 2.25)
[ Determine Total Monthly Cost
[] Medical Plan (555.52)
Total monthly cost : Total monthly cost :

(a) Example 4 (b) Example 5

FIGURE 12.19 Two programs from Sect ion 4 .4.


558 • Chapter 12 Web App lications

raised whenever one of the ch eck boxes is clicked on. That event proced ure updates the total
cost. The difference betwee n the two examp les is that in Exa mple 5 a computation is made
every t ime the use r cl icks on a check box, wherea in Examp le 4 clicking o n a check box does
not ca use a computation.
Both examples can be converted to Web programs with the sa me co ntrols, se ttings, and
code as in Section 4.4 . The Web vers io n of Example 4 wi ll work just fine, but Example 5 wi ll
not work as expected. This happens beca use computations can be made onl y if there is a pos t-
back to the se rver. C licking o n a button trigge rs a pos tback, but clicking on a check box does
not. The situation in the Web ve rsion of Example 5 is eas ily remedied. The check box contro l
has an A utoPostBack property that is se t to False by default. H owever, if it is changed to True,
then clicking on the check box will trigge r a postback and thus will a llow a co mputat ion to be
made. Therefore, all that is requ ired to make the Web version of Example 5 work as intended is
to change the A utoPostBack etting fo r each of the four check boxes.
By defau lt, clicking on a button causes VWD to check for validation. S uch is not the case
with a ch eck box. H owever, if you change a check box's Causes Validation property to True,
clicking on it wi ll invoke a va lid ation check.

Comments
1. As an alternative to using a hyperlink control, a line of code of the form
Response. Redirect ( "WebPageName. aspx" )

can be u ed to nav igate to another Web page.


2. In Windows programs, a list box's S tring Collection Editor can be used to fill the content
of the list box at desi gn time. In Web programs this task is accomp lish ed with a Listltem
Collection Ed ito r that is ident ical to the one for the radio-button list control.

Practice Problems 12.2

A statement such as

Dim states() As String= IO.File.ReadAllLi nes(MapPath ( "App_ Data/States.txt" ))

cannot be placed in the Declarations section of a Web program as i co mmon ly done in Win -
dows programs.
1. Why did we often avo id plac ing ReadAllLines state ments inside event proced ures in Win-
dows programs?
2. Why is the answe r to Practice Problem 1 not relevant to Web programs?

EXERCISES 12.2

1. Write a program that uses the page des ign in Fig. 12.20. The list box should be populated
with the names of the 50 states in a lphabetical o rd er wh en the page is loaded. (The fi le
States.txt conta ins the names of the U.S. rates in the order in which they joined the
union.) When the user clicks on the button, the selected state should be de leted from the
list box. A va lid ation control should be used to assure that a state h as bee n selected befo re
the button is clicked on . At all times the read-only tex t box should di play th e number of
states remain ing in the list.
12.2 Programming for the W eb, Part II • 559

Un bound

Delete Selected State

You must select a state. f\Jurnber of states m list: I


FIGURE 12.20 Web page design for Exercise 1.

2. Rework Exercise 20 from Section 4.4 (Presidential Eligibility) as a Web program. Add two
va lidat ion controls for the "Date of birth" tex t box. One va lidat ion control should check
that the date entered is 1/21/1978 or ea rlier (to guarantee that the person will be 35 by
inauguration day in 2013) and the other should require that a date has been entered. The
code for the button's C lick event proced ure can be shortened, ince the date would have
already been validated.
3. Rework Exercise 17 of Section 4.4 (Co t of a Computer) as a Web program. U se a
RequiredFieldValidator control to assure that one of the radio buttons is selected. Note 1:
If yo u set the radio-button list's Repea tOirection property to Horizontal, then the radio but-
tons will be d isplayed in a row. Note 2: You must set each check box' CausesValidation
property to True.
4. Rework Exercise 25 of Section 4.4 (Health C lu b Fees ) as a Web program. U se a Required -
FieldValidator contro l to assure that one of the radio button is elected before the fee i
calculated.
5. Rework Example 1 of Section 5.1 (Convert Fahrenheit to Celsius) as a Web program.
Require that the input text box contain a value when the button is clicked on and that the
va lue is in the range from - 459.67 °F (absolute zero ) to 11,000 oF (approx imate tempera-
ture of the urface of the sun).
6. Co nsider the program in the hyperlink wa lkth rough. Replace the h ype rlink co ntro l in the
Help page with a button hav ing the caption "Return to Tip Calcu lator".
7. Rework Exercise 35 of Section 5.2 (Highest Two Grades) as a Web program. Require that
data be entered into each input text box before the button's C lick event i processed and
validate that each grade is between 0 and 100. See Fig. 12.21.

Grades
First grade: j
---
Second grade:jr-- - -

Third grade: I
ine Highest Two Grades

First grade missing! Second grade missing! Third grade missing!


First grade invalid! Second grade invalid! Third grade invalid!
FIGURE 12.21 Page design for Exercise 7.
560 • Chapter 12 Web Applications

8. Rework Example 3 of Section 5. 1 (Weekly Pay) as a Web program. Requ ire that data be
entered into each input text box before the button's C lick event is processed and va lidate
that the number of hours worked is at most 168 (the number of hours in a week).
9. Rework Exercise 37 of Section 5.2 (Alphabetize Two Words) as a Web program with the
additional provision that both words must begin with lower-case letters. Use a Required-
FieldValidator and a Range Va lidato r control with each text box .
10. Rework Examp le 3 of Section 7.3 (Display Countries by Continent and A rea) as a Web
program without using a structure.
11. Rework Exercise 29 of Section 7.3 (Display Justices from a Spec ified State) as a Web pro-
gram without using a structure.
12. Rework Example 1 of Section 7.4 (Intercity Distances) as a Web program. Use a Requ ired-
FieldValidator and a Range Va lida tor control with each input text box.

Solutions to Practice Problems 12.2

1. This was done to avo id read ing a text file from a disk into an array more than once.
2. With a Weh program, any array loses its va lues between postbacks.

12.3 Using Databases in Web Programs


Databases play a prominent ro le in Web app licatio ns. In this section we how how to use LINQ
to manipulate information retrieved fro m databases. The information wi ll be displayed both in
bar charts and in grids. O ur ba r charts wi ll be ge nerated by the C hart control, wh ich is new to
Visua l Web Deve lope r 20 10.
Th is section uses the sa me types of databases as C h apter 10. However, we wi ll use them in
a different format called a Microsoft SQL Se rve r format. (SQL is pronounced sequel.) The data-
bases will have the exte nsion mdf. In order to open these databases when using VWD Express,
you must have Microsoft SQL Server installed o n yo ur comp uter. (M icrosoft SQL Se rve r
Express is contained on the DVD accompanying this book and is usua lly installed wh en you
insta ll Visual Basic Express or Visual Web Develope r Express.)

Creating a Bar Chart from a Database


The following walkthrough uses the Megacities database discu sed in Section 10.2 and displays
a bar chart showing the cities and the ir 2010 popu lations. The cities wi ll be disp layed in
descending orde r of their 2010 popu lations. Note: VWD refers to a bar chart as a column chart.
The walkthrough proceeds in four stages.
Stage 1: Design the Web page.
Stage 2: Add a database co nnection .
Stage 3: Create an object model for the databa e. (The object model is used to enable LINQ
queries to be perfo rmed on data retrieved from relat ional database .)
Stage 4: U e a LinqDataSou rce control to display data in a Chart control.

Stage 1: Design the web page


1. Start a VWD program with the name PopBa rC hart and delete the text in the Main Con-
tent region.
2. Place a button control on the form, set its ID property to btnDisplay, et its W idth property
to 300px, and se t its Text property to "Display C ity Populat ions in Descend ing O rd er" .
12.3 Using Databases in Web Programs • 56 1

3. Place the cursor to the right of the button co ntrol, press the Enter key tw ice, and then
double-click o n the C hart control (in the Data group of the Toolbox ) to place a ch art con -
tro l on the page . The ch art control wi ll di splay a ge neric bar ch art as a placeho lder. (See
Fig. 12.22. )
4. Set the ID property of the ch art control to chtMegacities .

Display City Popul ation s in Des cendin g Order

100

,......&-
80
....-'-- r-1-

60 t--

t--

2.0 - r-"'-
r---

0
1 2 3 4 5 6 7 8
FIGURE 12.22 Default.aspx page in Design view.

Stage 2: Add a database connection


1. Open the Database Explorer window by clicking on its tab. A lternatively, select Other Win-
dows fro m the View menu and click on Database Explorer. Note: In Visual S tudio, Database
ExJ)lorer is ca lled Server Explorer.
2. Right-click on Data Connections in the Database Explorer window and then click on A dd
Connection. (The Add Connection dialog box in Fig. 12. 23 on the next page wi ll appea r.)
3. If the Data so urce is no t se t to "Microsoft SQL Server Database File (SqlC lient)", click on
the C hange button and se lect that data so urce .
4. C lick o n the Browse butto n , nav iga te to the folder Programs \ C h12 \Databases in the
materia ls you downloaded from the Pearson Web site for this boo k, and double-click on the
fil e Megac ities.mdf.
5. C lick on the Test Connection button to ve rify that yo u are conn ected to the database.
6. C lick on the OK button.
Stage 3: Create an object model for the database
1. C lick on the Web page and then click on Add New Item in the Website menu . (An Add
New Item dia log box will appear.)
2. Select LINQ to SQL Classes, change th e name from the defau lt name DataClasses .dbml to
Megacities .dbml, and click on the A dd button. (The window in Fig. 12.24 will appear.)
3. C lick on the Yes button . (A n O bj ect Re lationa l Des igner consisting of two panes separated
by a vertica l scro ll ba r will fill the Document window.)
562 • Chapter 12 Web Appl icati ons

Add Co nnect io n

Enter informat ion to conn ect to th e selected data source or click


"Ch ang e" t o choose a different data sourc e and/ or provid er.

Dat a sourc e:
Mi crosoft SQL Server Database Fil e (SqiCii ent) Chang e ...

Database fil e nam e (new or existing):


Browse...

Log on t o t he server

o Use Win dows. Auth ent icati on

Use SQL Server Auth ent ication

Pas_·,rvord:
Save my passwor d

[ Advance d ...

,.
Test Conn ection OK [ Cancel

FIGURE 12.23 T he Add Connec tion dialog box.

Microsof t Vis ua l We b Deve loper 2010 Express

You are attempti ng to add a spec ial fil e type (LlNQ t o SQL Cl asses.) to
an ASP.N ET Web sit e. In general, to us.e this. type of item in your site,
you should pl ace it in th e 'App_Co de' fold er. Do you want to pl ace th e
fil e in t he 'App_C od e' fold er?

.____v_e_s. _-JJ [~_ _N_o_ _-"] c_a_n c_e_I_ ....J


L[_ _

FIGURE 12.24 Placeme nt dialog box.

box ) to the left of


4. Open Database Explo rer and click on th e righ t-po in ting triangle (or plus
Megac ities. mdf to d isplay a list of folders.
fo lder to display a
5. C lick on the righ t-po inting triangle (or plus box ) to the left of the Tables
list of the two tables in the database.
hould
6. Drag each table ont th l ft p ne f th Object Relational D igner. (The sere n
after the first
look so methi ng like Fig. 12.25. A lso, the dialog box in Fig. 12.26 will appear
table is dragged. C lick on the Yes button in the d ialog box.)
12.3 Us ing Databa es in Web Programs • 563

[:;} PopBarChart - Microsoft Visu-31Web Developer 2010 Express


To o l~ Window Help

Crty Country

Creo:e r"e·hods r.:y


- Properties - Properti e~
oragg.'lg r•e.-, ' c.om
name Da~abase Explorer c~ o th"
courn y desrg'1 $1 ...+ace
pop2010
pop2015

FIGURE 12.25 Obj ect Relational Designer.

Microsoft Visua l Web Develope r 20 0 Expre ss

The connection you selected uses a local data file that is not in the
current project. ould you like to copy the file to your proj ect and
modify the conn ection?

~--
Ye_,___l [~___N_o __~] [~_H_e_lp__~

FIGURE 12.26 Copy File to Project dialog box.

7. C li ck on the Save A ll button in the Too lbar.

Stage 4: Use a LinqDataSo urce control to display data in a chart control


1. C lick on the Defau lt. aspx tab to return to the Designer and place a LinqDataSo urce contro l
(from the Toolbox's Data group) at the botto m of the page . Note: This contro l will not be
visible at run time.
2. C lick on the LinqDataSo urce control's Tasks butto n and click on Configure Data Source to
bring up the Configure Data Source dialog box.
3. elect MegacitiesD ataContex t in the "Choose your context object" combo box and click
on the Next button. (You will now be asked to configure the data selecti on.)
4. The defau lt selections made in the Configure Data Sou rce d ialog box are fine as is. C lick on
the Finish button.
5. Double-cl ick on the Display button to bring up the code-behind ed itor, and then enter the
fo llowing code:
564 • Chapter 12 Web Appli cations

k
Protect ed Sub btnDisp lay_ Click( ... ) Handles btnDisp lay.Clic
Dim mcDC As New Megacit iesDataC ontext
Dim query = From city In mcDC.C ities
Order By city.pop 2010 Descend ing
Select city . name, city.pop 2010
chtMeg acities.D ataBind Table(q uery, "name" )
chtMega cities.C hartAre as{O) .AxisX. Interval = 1
chtMega cities.C hartAre as(O) .AxisX. Title "City"
c htMega cities.C hartAre as(O) .AxisY. Title = "2010 Populat ion in Million s "
End Sub
name
Note: The line following the query statemen t binds the chart to the query and uses the
es that all x-values will be displayed .
fie ld to populate the x-values. The next line guarante
6. Run the program and click on the Display button. Figure 12.27 shows the output.

Display City Popul ations in Descending Order

:.f ·;=
...c:
D t:'
..... I;

J .e
../)
:r

FIGU RE 12.27 Output of walkthrough.

Displaying Database Information in a Grid


con-
A slight va riation of the program deve loped in the walkthro ugh above will fill a G ridView
Video Note
tro l with the sa me info rmat ion . The changes required are as follows:
Disrl ay ing
con-
1. In stage 1 place a G ridView control on the page in tead of a ch art control. N ame the
in fo rm at ion in a
grid
trol grvMegacit ies.
ts
2. In the fifth step of stage 4, replace the chtMegacities statemen ts with the four statemen
grv Megacit ies.Data Source = query
grvMeg acities.D at aB ind()
grvMeg acities.H eaderRo w.Cells( O) .Text = "City"
grvMeg acities .HeaderR ow. Cells(l) .Tex t = "2010 Populat ion in Million s"
on .
3. Figure 12.28 haws the output when the program is run and the button is clicked
12.3 Using Databases in Web Programs • 565

Display City Populations in Desoending Order

City 2010 Population in Millions


ToKyo 36.1
Bor~1bay =:c.1
Sao Paulo 19.6
lr-{ e.( ico Cit) 19.5
New York 19.4
Delhi 17
Shanghai 15.8
Calcutta 15.6
:Jhaka 14.8
8L..enos ~1res 13.1

FIGURE 12.28 O utput of G ridView program.

Comments
1. The chart control can produce cl uste red bar charts. For instance, if the LINQ clause
Select city . name , c ity . pop2010

from the program PopBarChart is changed to


Select ci t y .name, c i t y .pop2010 , city . pop2015

and the string "2010 Popu lation in M illions" is changed to "2010 & 2015 Pop ulation in
Millions", then the clustered bar chart in Fig. 12.29 will be produced.

0
~-
<::

-;;;:
~
30 I--
r=
.:::0
..!;!
;:,
20 t - h:-:- .,-;=
0...
li'

l! J
10 -
II n - f-:
f -

~ ~ u
.Q .,f;
3.
1-
~

~ & E
::J
f. Qi
0 ..:
0
,;e
~ z I;

-- ::!
Q;

C1y
FIGURE 12.29 C lustered bar chart.
566 • C hapter 12 Web App licat ion

2. When LINQ is used to prod uce a ba r chart, one of the ite ms in the Select clause must have
type String and the remaining ite ms must h ave a numeric type. H oweve r, when a LINQ
qu ery is used to prod uce a grid, the items in the Se lect clause can have an y data typ s.

Practice Problem 12.3

1. Wri te a VWD program that use the database Megac it ies.md f to ge nerate a bar chart dis-
play ing the 2010 populat ions of the coun tries whose currency is the peso.

EXERCISES 12.3

In Exercises 1 through 10, write a Web program that uses the database Megacities.mdf to
generate th e bar chart.

1. 2. 25

I:

~ r;
20
c:
s; ~

g
c:
..
:;
""s 15 t---
c:
r-.--- ·- - -
c. ~
;;;
!:.. :;
0 c:.
0 10 1--- 1- r- 1---
0I c...
~
0

0
• 5 t--- 1- r- ~

~
,_ '),
G ~
~
0
," Boo-bay Ca " Delht
CD
Ctt1 m lr a
Ctty

3. 16 4. 25
-= "'~
G
e 1214 2
!;;;
~ 10 -=6 15
3
~ 8
c;
ll.
<.':
..
c
"'
<:
6
4
~
~
0
0 05
"' 2
ll.

0
~
-:3 "' <5
-=c:. ~ -;;

j)
:l"
CD
...~
Ctty
C•l'/
12.3 Using Databases in Web Programs • 567

5. 40 6.

v:
ll c:: 15
c: 30 0
oE oE

~ ~
c:
"' 20 1----.-
!< :- .!;? 10
~ :::1

~
1l.
e-
0 0
c; 10 ----, - '---' - - :- c; 5

0
eXJCO <Ay Sao Paulo Ca leu na !)t,a1.3
Bombily • Yorio: - ory.o Buenoi 1ru Dil 1 Shanghai
City v.1th Above- vera e PopulatJor> City v.1th Popula on ~ 18 1llio

7. 100 8. "' 35
{/"
c:
1200 III Q

~30
e.- I I
-
5 1000 -
e-
ll.
{/"
25
~ lL
c
;:: -~ 20 I-
800

~ ~ ~I
8 :::1
0
600 u 15 I -
0
ci
0 400 ~
[
0
200 - - - - e.- - -
~ ... -
-r
0 0 ~-

~
-
z8 ~
... ....
~
~

~ ..r;
&
..r;
Ol
c;
3
.);l
g f
.... g ~
u
~
8 0 i5
..2
a &"' ~ I 8..r;;;
8
_j
3
..r;
cr
~
0 1- c;
lSc:: 0 ~
en
co J § :z: ~ m ~
c; :z: en
::;;
CD "' ::::
Qj

c. ' c.

9. 1400 10. 1400000000


C/1 1200 f-
I 1200000000 I
8
~ 1000 - 1000000000 -
~ ~
c:: 800 - - .5I
800000000 -
Q I ~
.s - -
0
a.
a
0
600 I 0 600000000
0
0 400 f- - 400000000
~
r
200
0
WM n'nl1 1
200000000
I
f-1 f-

0
-e <
I!) e .:; c
c
.&.
fJ)
1'i
9 "
-; ~
8 c
c;)

.E ::> -~
(.J
0
(0
~ ..,Ill ::;;
] &. g l
CD

Country Country
568 • Chapter 12 Web Applica ti ons

In Exercises 11 th rough 16, wri te a Web program that uses the database Megacities.mdf to
generate the grid.
11. 12. City Population Increase
City Population Increase
Dhaka 14.86'3-o Dhaka .2 200 000
Deihl 10.00% Bombay 1900 000
Bombay 9.45 °6 Delhi 1700000
Calcutta 8.97?o Calcutta 1400 000
Shanghai 3.36% Shanghai 1400,000
rl1ex:ico C1t· 359QD t 1E:
1 ICO (It 700,000
r Je 'I fork 3.09'0o ~.Je •r York 600 000
S'lo Paulo 2.55°'0 cao Paulo 500 000
Buenos A1res 2.29% Buenos ~1res 300,000
Tokyo 0.83% Tok·yo :::ooooo

13. 14. 2010 Pop. 2015 Pop.


Country Population in 2010 City
Chma 1.379 700,000 ac Tiba~' 20.100.00 0 .:.:.ooo.oo:
Ind1a 11 '36 300.000 3uenos Aires B.loo.:;::c 13400.00 0
U:lA 310 100 000 Calcutta 15.600,C0 S 17.000.CCC
258 500.000
17 OOO,COC 13 ;oo.oc:
Indonesia
Je,nl
Brazil 195,200 000
:J ~aka 14.800,00 C 17 JOO,C~C
Pa~ 1stan 184 200,000
ltv'; ex:ico Cit/ 19.500.00 0 .28.200 cc:
Banglades h 152.600,00 0
Japan 129 000 000 Nev,, York 19.400,0C C 20 OOO,C8C
t'•1eXICO 11' 400 000 Sao 0 at...lo 19.600,0CO ~0 100 oc :.
..... gentma 41900 000 Shang'1ai 15soo o~.-: 17.200 0(':.
To<yo 36100,00 C 36 4oo c::·:

15. City Country Currency 16. City Country % of Country's Pop.


Bombay Ind1a rupee Bt enos A1res Argent1'1a 31.3~·v

Buenos Atrec Argertina peso TC{jO Japan ~8 0~·~


Calcutta Ind1a rupee '/exico 16.6%
/exico Cit 1
Delhi Ind1a rupee
Sao 0 aulc 3-azil 10.09;:
Dhaka Banglades h raka
~·llexico peso
::'I aKa 6a'1glades'1 9.79d
l'v1ex1co C1t;
eN Vork ~S.~ 6.3~c
New York USA dollar
Sao Paulo Brazil real 3c"'bay Irdia 17%
Shanghai Chma uan Jelhi l!1dia .... .4%
Tokyo Japan /E:n Calcutta Ind1a 1.3%
ShaflghaJ C'11na 1.1%
12.3 Us ing Databases in Web Programs
• 569

The database Pizza.mdf has a single table Pizzerias that contains data for th e eight leading
pizza chains. The fields for the table are name, sales2007 , sales2008, numStores200 7, and
numStores200 8 . (Sales are given in thousands of dollars.) Two records in the table are

Pizza Hut 5100000 5300000 7466 7564

Domino's Pizza 3194485 3037703 5136 5047

In Exercises 17 through 22, write a Web program that uses the database Pizza.mdf to gener-
ate the bar chart.

18. 3000

00
8 6000
~.

;;
.r
(5
.:;; 4000
0

~ 2000
z"'

.:::

Przzena Przzem;

19. 300 20. 15


•.

0
250
])~ 200
50
t ·._
~
"'
.f)
10 I-'
I

;;
00 - -
.,"""
c;
5 f--i
50
14 T-: - .r;

II
-I-

I
_,r!"l I
0~---o- 0
I
50
·100
rl .., ·5
-
'......."' -• -g~
~

j - -"'• !!.·..., 2 ..,


0::
·a"',<:;
s" ...,-s '.
c:
::c' C'E_ u.. -·
"' :J:)
i
-! :;
... £
3 df. ...
; ..."" ~
.:;
a:
.. i;n ~

'-' ;:!:!:
::: t; g
c. :>
~ 3. u
c ::2 t:: 2. ~
&
Przzen Przzen a
570 • Chapt er 12 Web App licatio ns

21. 6 22. 8000


co
8
t:
r ol!
..... 6000
~ 0
5 d ~ ~

f/" 5
4000
"'
en
00
r 5
u;
g
..... 2 0
ol! t 2000 r- r-
......
8

0
rl r•I
w·"'
-"
.J
...c::
N
~
C
- tr
...
N
r~
.3
..,t:! ..
c:

~
!r .I r•
8. ·~
c:;..o::
j ...
1
j
en
~
z
0
r1
_,_~

~~
il :O
:lu .J
I
.:!:
. o/1
·a
T 1rI
§.::~
~ "
::'!...
~
...l
-s -~b
"'
'c:
....,
a
11
3 -;;
::
r

~
j
;n

.Ei ~
0
_j
~ u
2. !!: .J £
u &
Pizzena
Pizzena

the datab ase Pizza .mdf to gener ate


In Exerc ises 23 and 24, write a Web progr am that uses
the grid.

23. Pizze ria 2007 Sales 2008 Sales Change

Pizza Hut 55.100 .000,0 00 S5.300.000.00C 3.92~o


DoMino's Pizza 53.194 .485.0 00 53 037.70 3 000 -4.91%
Papa Johr's 51.969 ,258,0 00 52.033 255.0 00 3.25°/o
c.~ttle Caesars 5930, 000.0 00 51.05 5,000 ,000 13.44%
C1Cis Pizza 5570, 000,0 00 5585. 000.0 00 2.63%
Chuck E. Cheese's S575,000,00C 5569, 500,0 00 -0.96%
Papa Murphy's S504,000.00C S544.000.00C 7.94°o
5503, 500,0 00 5500, 000.0 00 -0.70%
Sbarro

24. Pizze ria # Sto res in 2007 # Stores in 2008 Chang e


7.466 7 564 0.19%
P1zza Hut
5.136 5.047 -0.28%
Domino's Pizza
2 760 2.792 0.16%
Papa John's
Caesars 2 241 2.500 2.78%
~1ttle
1057 11.18 1.21%
Papa Murp hys
795 775 -0.40%
Sbarro
619 634 0.26%
CiCi's Pizza
Chuck E. Chees e's 509 515 0.10%

the datab ase Pizza .mdf and displays


In Exerc ises 25 throu gh 28 write a progr am that uses
text box or in a list box.
the stated inform ation for the year 2008 in a read-o nly
s.
25. The tota l numb er of stores for the top eight pizza chain
26. The names of the top three pizza chains in sales.
er of store of any of the top eight.
27. The name of the pi zza chain hav ing the least numb
se in sales of an y of the top eight.
28. The name of the pizza chain hav ing the greate st increa
Summ ary • 57 1

Solution to Practice Problems 12.3

1. There is no need to ca rry our rhe fo ur stages from the wa lkth ro ugh , since we have already c rea ted an objec t
mode l and LinqDaraSource conr ro l fo r thi s database. The fo llowing steps crea te th e new program, and
Fig. 12.30 shows rhe ba r chart rhar is produ ced :

(a) Starr a new Web progra m with rhe name Pract iceProb and then c lose rhe program.
(b) Use rhe process fo r buil d ing on an ex ist ing Web program d iscussed ar rhe end of Secti on 12. 1 to make
Pract iceProb a c lone of rhe program created in rh e wa lkth ro ugh .

.
20

0
I ~

-
"<:; c

6
c
0.
.::::;. 0 ·- -
"
-I
20 J

r <>ntm e , JC
c -.- Curre r ~ ..

FIGURE 12.30 O utput of Prac tice Problem.

(c) Open PracriceProb in VWD and change rhe q uery to rhe fo ll ow ing:

Dim query = From country In mcDC.Countries


Where country.monetaryU ni t = "peso"
Select country.name, country.pop2010

(d) C hange the string in rhe next to last line of rh c code fro m "City" ro "Country with Peso as C urre ncy".

CHAPTER 12 SUMMARY
1. V isual Web Developer (VWD) is used to crea te programs that res ide on a erver and run in
the W eb browse r of a client co mputer.

2. There are man y imilari t ie betwee n crea ting a Web program with VWD and crea ting a
Visual Basic Windows program. H oweve r, there are so me important d ifference . Fo r o n
thing, tex t can be typed and form atted d irectly into We b pages. A lso, not as man y co ntro ls
are ava ilab le in VWD as in Visual Bas ic, and contro ls that are commo n to both have fewer
properties and eve n ts in VWD than in Visua l Bas ic.
3. The table control is he lpful for aligning tex t and contro l in VWD.
4. Validation controls a llow the brow er to check input befo re it is ent to the se rve r.
5. The hyf)erlinl< control is used to request different pages fro m the se rve r.
572 • Chap ter 12 Web App licatio ns

uest co ntain ing data back to the se rver for


6. A postbaci< occ urs when the browse r se nds a req
processing.
r receiv es a page req ues t.
7. The page load event is raised each time the se rve
sa me functi onali ty as their coun terpa rts in
8. Radio~button list and checi< box contr ols have the
often used to ve rify that a radio butto n
Visua l Bas ic. A req uired fie ld va lidati on contro l is
has been se lec ted.
nces the programm er's abil ity to graph i-
9. The chart contro l, along with LI NQ to SQL, enha
cally disp lay da ta retrieved from a da taba e.

CHAPTER 12 PROGRAMMING PROJECTS


a perso n is from New Engla nd. Peop le
1. W rite a program that deter mines whet her or not
be able to get help in the form of a list
who do not know their state's abbrev iation shou ld
e 12.3 1 shows the in itial Web page at
box show ing th e states and their abbreviatio ns. Figur
butto n, the page co ntain s a h yperl ink
des ign time. In addit ion to two tex t boxes and a
and a requi red fi eld va lidati on contro l
contr o l that nav iga tes to the help page in Fig. 12.32
is loaded, the file USSt ates.txt should
th at verifies the top tex t box. (Whe n the help page
infor matio n abou t each of the 50 states .
be used to pop ulate the list box. This fi le conta ins
me, abbrev iation , land area (in squ are
Each record of the file conta ins four fields-na
d s are ordered by the states ' dates of
miles), and pop ulat ion in the year 2000 . The recor
is typed into the input tex t box and the
entry into the union.) After a state abbre viat ion
be displayed in the Answer text box.
butto n is clicked on, the wo rd YES or NO shou ld

Are You From New England? A labam a - A L


Alas ka -AK
Ent~r you r stat e abbr evia tion
.
:. I Arizona -AZ
.. .. . . .. . Arka nsas - AR
California - CA
Get List of Stat e Abb revi atio ns Color ado -CO
Get Answer to Quest ion ,. Conne cticut - CT
Delaw are -D E

Answer: I Florid a - FL
Geor gia- GA

State Abb revi atio n Required Return to Hom e Page


FIGURE 12.32 Help page du ring run time.
FIGURE 12.31 I nitial page in design mode .

. mdf database and displays the interface


2. Write a Web program that uses the Megacities
tion from each list of radio butto ns and
VideoN ote show n in Fig. 12.33. After the use r makes a selec
d bar chart shou ld be displayed. Use two
Web ba;,cd cl icks on the Displa y Bar Char t butto n, the req ueste
tions are made fro m both lists.
Richard 's ca tering Requ iredF ieldValida tor contr ol to ensur e that selec
(Home work)
Programming Projects • 573

egacif es Popu at io Ba Cha ts


Year Order

Asce'lding
Display Bar Clh a
2C 15 ' Descendir g

~
~ ·r J
..t::
-s
..... '= a:. r
,:
a ~
-=
t::I
~
'
~ ..e
(o';
I
'-
~
./) -;:

i:l:i

I '

FIGURE 12.33 Poss ible outcome of Programming Project 2.


AP PE ND IX A
AN SI VAL UES

ANSI ANSI ANSI


Value Chara cter Value Chara cter Value Chara cter

000 (null) 046 092 \


001 0 047 I 093 ]
002 0 048 0 094 A
003 0 049 1 095
004 0 050 2 096
005 0 051 3 097 a
006 0 052 4 098 b
007 0 053 5 099 c
008 0 054 6 100 d
009 (tab) 055 7 101 e
010 (line feed) 056 8 102 f
011 0 057 9 103 g
012 0 058 104 h
013 (carria ge return) 059 105
014 0 060 < 106 J
015 0 061 107 k
016 0 062 > 108 l
017 D 063 109 m
018 0 064 @ 110 n
019 0 065 A 111 0
020 0 066 B 112 p
021 0 067 c 113 q
022 0 068 D 114 r
023 0 069 E 115 s
024 0 070 F 116 t
025 0 071 G 117 u
026 0 on H 11 8 v
027 0 073 I 119 w
028 0 074 J 120 X
029 0 075 K 121 y
030 0 076 L 122 z
031 0 077 M 123
032 (space) 078 N 124
033 ! 079 0 125
034 080 p 126
035 # 081 Q 127 0
036 $ 082 R 128 0
037 % 083 s 129 0
038 & 084 T 130
039 085 u 131 '
f
040 086 v 132 "
041 087 w 133
042 * 088 X 134 t
043 + 089 y 135 t
044 090 z 136
045 09 1 [ 137 %o
575
576 • Appendix A ANSI Va lues

ANSI ANSI ANSI


Value Chara cter Value Chara cter Value Chara cter

138 s 190 3/4 242


243
0
6
139 < 191 z
140 CE 192 A 244 6
141 0 193 A 245 6
142 z 194
195
A
A
246
247
6
143 0
144 0 196 A 248 ¢

145 197 A 249 i:1

146 198 IE 250 u


147 " 199 ~ 25 1 Q
, 200 E 252 u
148 tT
149 • 201 E. 253
202 E 254 p
150
151 203 E 255 y
152 204 l
153 TM 205 f
206 y
154
155 > 207 1
156 ce 208 -f)
157 0 209 N
158 z 210 6
159 y 211 6
160 (no-brea k space ) 212 6
161 213 0
162 ¢ 21 4 0
163 £ 21 5 X
164 0 216 0
165 ¥ 21 7 u
166 218 (J
167 § 219 0
168 220 0
169 © 221 y
170 l! 222 p
171 ((
223 f3
172 -, 224 a
173 225 a
174 ® 226 a
175 22 7 a
176 0 228 a
177 ± 229 a
178 2 230 a:
179 23 1 9
180 232 e
181 IL
233 e
182 qr 234 e
183 235 e
184 )
236
185 l 23 7
186 0 238 l
187 ))
29
188 l/4 240 0
189 1/2 241 fi
AP PE ND IX B
How To
Note: These How To's app ly to Visua l Bas ic. Many, howeve r, are also relevan
t
to Visual Web Deve loper.

Laun ch and Exit Visua l Basic


Note: Visual Basic is part of a suite of programs called Visual Studio, which
also contain the C# (pronou nced "C-shar p") programming language.

A. Invoke Visual Basic Express Edition


1. C lick the Start button.
2. Hover over A ll Programs.
3. C lick on Micro oft Visual Basic 20 10 Express Edition.

B. Exit Visual Bas ic


1. C lick on Exit in the File menu, or click on the red Close button loca ted
at
the upper-ri ght co rner of the window. Note: If the current program ha not
bee n aved, Visual Bas ic will prompt you abo ut sav ing it.

Mana ge Visua l Basic Progr ams


A. Create a new program .

1. C lick on New Project in the File menu, or click on the New Project butto
n
( ..::iJ ) on the Too lbar, or press Ctrl + N. Note: If the current progra m
has not been saved, Visual Bas ic wi ll prompt you about sav ing it.
2. Check that Windows Forms App lication is highligh ted.
3. Option ally, type a name for the progra m into the Name box.
4. C lick on the OK button.

B. Run the current program.

1. C lick on the Start Debugging button ( ) in the Toolbar, or press FS, or


click on Start Debugging in the Debug menu.

C. Save the current program.

1. C lick the Save All button ( ) on the Toolbar, or click on Save All in the
File menu.
2. If the program has not been saved prev iously, give it a na me and then click
on the Save button. Importa nt: If the "Create directo ry for solution
"
check box is checked, then cl ick on the check box to unchec k it. (You

577
578 • Appendix B How To

unch ecked fo r all


only have to unch eck th is check box once; it will stay
future progr ams.)

D. Clo e the curren t program.


cu rren t progr am has not
1. C lick o n Close Project in the File menu . Note: If the
sav ing it.
been saved , Visua l Basic will prom pt you about

E. Ope n a rece ntly saved program .


in the File men u. (A
1. H ove r the mouse over Recent Projects and Soluti ons
)
numb ered list of recen t programs will appea r on the right.
the co rrespo nding numb er.
2. C lick on a recen t progra m, o r press

F. Open a program sto red on a disk.


1. C lick on Open Project in the File menu, or press Ctrl
+ 0. Note: If the cur-
t you about saving it.
rent progra m has not been saved, Vi ual Basic wil l promp
2. Navig ate to the program's folder.
and click on Open.
3. Doub le-clic k on the fo lder, or highli ght the folder
(Seve ral subfold ers and files wi ll be di played. )
4. Doub le-clic k on the file with exten sion sln.
r for the progr am appea rs,
5. If neithe r the Form Designer nor the Code Edito
window.
doub le-clic k on formName.v b in the Soluti on Explo rer

G. C hange the n ame of a program.


1. Open the program if it is not already open.
of t he Solu tion Exp lorer,
2. R ight-click on the name of the program at the top
provid e a new name
click on Rename in the drop- down conte xt menu , and
fo r the progra m.
the top of the Soluti on
3. Right -click on the new name of the program at
, se lect Application
Exp lorer, click on Properties in the drop-d own conte xt menu
, and change the con-
on the large tab at th e left side of the windo w that opens
tents of the "A sembly name :" text box to the new name.
4. Save and close the program.
, ch ange the name of
5. In Wind ows Explorer, navigate to the program's folder
the base name of
the fo lder to the new name, open the folder, and ch ange
the fi le with exten sion sln to the new name.
Code Edito r or the Form
H. Use the Solut ion Exp lorer windo w to view the
Desig ner.
e, click on Soluti on
Note: If the Solution Exp lorer window is not visibl
Explorer in the View menu.
me. vb.
1. In the Solution Exp lorer window, right- click on fileNa
2. C lick on e ither View Code o r View Designer.

Tex t Man ipul atio n


A. Selec t (or highli ght ) a block of text.
1. Move the cursor to the beg inning or end of the text.
ght a block of text,
2. H old down a Shift key, u e the direction keys to highli
and release the Shift key.
Appe ndix B How To
• 579

or
1. Mov e the mouse to the begin ning or end of
the text .
2. H old down the left mouse butto n, move the
mouse to the othe r end of the
text, and release the left mouse butto n.

Note 1: To desel ect tex t, press the Esc key or


click outside the text.
Note 2: To selec t a word, double-click on
it. To selec t a line, move the
mou e poin ter just far enough into the left
marg in so that the poin ter
ch anges to an arrow, and then single-cli ck there
.
B. Mov e tex t.
1. Selec t the text as a block , and drag it to
the new locat ion with the mouse.
C. Use the C lipbo ard to move or duplicate text.
1. Selec t the text as a block .
2. Press C trl + X to delet e the block and place
it int the C lipbo ard, or press
Ctrl + C to place a copy of the block into the
C lipbo ard .
3. Mov e the curso r to the location where you
desire to place the block.
4. Press C trl + V to place a copy of the tex
t from the C lipbo ard at the curso r
pos it ion .

D. U ndo a chan ge.


1. C lick on Undo in the Edit menu or press C
trl + Z to undo the Ia t chan ge
made.

Note : A n und one chan ge can be redon


e by press ing Shift + A lt +
Backspace.

E. Increa e or decrease size of tex t.


1. Ho ld down the C trl key and move the mous
e scroll whee l forwa rd to in-
crease the size of the tex t and backward to decre
a e the size.

Ma nag e Vis ual Bas ic Con trols


A. Res ize a cont ro l.
1. Selec t the cont ro l and drag one of its sizing
hand les. O r, selec t the cont rol,
hold down the C trl key, and press the arrow keys.
Or, chan ge the settin g of
the cont rol's Size property. Or, use the M ake Same
Size optio n in the Format
menu to give the cont ro l the same widt h and/o
r lengt h a anot her cont ro l.
B. Move a cont ro l.
1. Se lect the cont ro l and drag it to a new locat
ion. O r, se lect the cont rol, ho ld
down the Shift key, and press the arrow key . O
r, use the Align optio n in the
Format menu to line up the cont rol with anot
her control.
C. Ce nter a cont rol in a form .
1. Selec t the cont ro l.
2. Use the Center in Form op tion of the Form at
menu.
580 • App endix B How To

D. Select multiple cont rols.


1. C lick on a control.
on addi tion al cont rols.
2. Hold down the C trl key wh ile clicking
or
r outs ide of the co ntro ls and start
1. C lick on a place in the Form Des igne
ar.)
dragg ing. (A dott ed recta ngle will appe
nd a grou p of cont rols.
2. Drag the recta ngle arou
3. Release the mouse butt on.
moved and resized as a group with
Note : Mu ltip le selec ted cont rols can be mon to
the arro w keys as in part s A and B. A lso, any property that is com
imul taneously.
all of the cont ro ls in the group can be set
rols.
E. Crea te uniform spac ing in a group of cont
al Spac ing or Vertical Spac ing opti ons of
1. Select Make Equa l from the Hori zont
the Format menu.

Note : Afte r un iform pac ing has been


achi eved, you can click on Increase
of th e
or Decrease from the Hori zontal Spacing or Vertical Spac ing op tion s
ing.
Format menu to wide n or narrow the spac
line .
F. Let a labe l caption u e more than one
setti ng to False and increase its he igh t.
1. C hange the labe l's Au toS ize property
mmo date the enti re capt ion on one
(lf the labe l is not wide enough to acco
ition al lines. lf the labe l heig ht is
line, part of the capt ion will wrap to add
l lines will not be visib le.)
too sma ll, then part or all of these add it iona

line.
G. Let a text box disp lay more than one
True . (lf the text box is not wide
1. Set the tex t box's Mul tiline prop erty to
red by the user, the text will wrap
enough to acco mmo date the text ente
tall enough, lines will scro ll out of
down to new lines . lf the text box is not
up or dow n keys. )
view but can be displaye d with the cursor

be activated by a press of the En te r key.


H. A llow a part icula r butt on co ntro l to
1. Set the fo rm's A ccep tBut ton prop
erty to the parti cula r butt on con trol.

icula r butt on cont ro l.


I. A llow the press ing of Esc to activ ate a part
part icula r butt on cont ro l.
1. et the fo rm's Can celB utto n property to the
the scree n whe n the prog ram executes.
J. H ave the form appear in the cent er of
1. Set the fo rm's Star tPos ition prop
erty to Cen terS cree n.

l to frmElse.
K. C hange the Na me prope rty of Form
ck on the fi le Form 1.vb.
1. ln the Solution Exp lore r wind ow, righ t-cli
that appears.
2. C lick on Rename in the cont ext menu et
3. C hange the name of the file Form
l. vb to frmE lse.vb. (Cau tion : Don 't forg
to reta in the exte nsio n vb.)
Appendix B How To • 581

L. Specify a custo m background or foregro und color for a contro l.


1.In the Prope rties window, select the BackColor or ForeCo lor property.
2. C lick on the down arrow in the right part of the Settings box.
3. C lick on the C ustom tab to di splay a grid of colors.
4. Righ t-click on one of the sixteen white boxes at the bottom of th e grid to
disp lay the Define Color dialog box . (The dialog box theoretically allows
yo u to crea te over 16 million custom colors. The large variega ted squ are is
called the color fi eld and the narrow rectangle the color slider.)
5. To select a custom color, click on any point in the color field and then use the
arrow head to move along the color slider. (At any time, the rectangle labeled
"Color iSolid" displays the current color.)
6. C lick on the Add Color button .

M. Remove the blank column on the left side of a DataGridView contro l.


1. Set the control's RowHeadersVisible property to False.

N. O ptimal sizing of a DataGridView control.

1. If you suspect that some cells will be too narrow to accommodate their con-
tents, se t the contro l's AutoS izeColumn property to AllCells.
O therwise,

1. Set the first parameter of the control 's S ize property to 100 · [number of
columns] + 3. If there will be a sc roll bar on the right side of the grid, add 17
to the se tting of the parameter.
2. Set the second parameter of the control's S ize property to 22 · [number of
rows] + 1. If an y column head er will occupy more than one line, add 13 to
the pa rameter for each additional line.

0. O btain a description of a property of a control.

1. If the Desc ription pane is not visible, right-click on the Properties wind ow
and then click on Description in the drop-d own contex t menu.
2. Highlight the property in the Properties window. Its purpose will appea r in
the Description pane below.

P. Specify the contro l that will have the focus when the program executes.
1. Set the contro l's Tabindex property to 0.

Q. Make the Properties wind ow eas ier to use.

1. Double-click on the Properties window's title bar. (The Properties window


will beco me und ocked, and it will be large r and eas ier to use. )
2. After you have finished using the window, right-click on its title bar and
click on Docie

Working with Code


A. Rename all instances of a variable, control, Sub procedure, or Function.
1. Select the name.
2. Right-click on the name and click on Rename in the drop-down contex t
menu. (A Rename dialog box will appear.)
582 • Appendix B How To

3. Type the n w name into the "New Name" tex t box.


4. C lick on the OK button to carry out the changes.

Note: This process is known a symboli c rename. If the name of


a local (or
proce-
block- level) variab le is change d, the change will be limited to the
dure (or block) contai ning the variab le.

B. Hide a long proced ure.


1. Scroll to th e top of the proced ure.
heade r of
2. C lick on the box with a minus sign in it that is to the left of the
plus sign and that the
the procedure. (Notice that the box now contain s a
to how
entire procedure is hidd en on the one line. C lick on the box aga in
the procedure.)

C. Add a collapsib le region.


d in
1. Type #Regio n "regionName" on the line before the code to be include
the region.
region.
2. Type #End Region on the line after the last line of code in the
ed by clickin g on the minus box and
3. The region of code can then be collaps
restored by clickin g on the plus box .

Note: A region cannot be defined within an event, Functi on,


or Sub pro-
cedure.

Setti ng Optio ns
A. Turn off lntelliS ense.
1. C lick on Options in the Tools menu .
it.
2. lf the check box to the left of "Show all settings" is unchec ked, check
3. In the left pane, expand "Text Editor".
4. Expand the subheading "Basic".
5. C lick on the subtopic "Gener al".
headin g
6. Ensure that all the check boxes und er the "Statem ent comple tion"
are unchec ked, then click on OK.
a horizon tal
B. Wrap words to the nex t line in the Code Editor rather than hav ing
scroll bar.
1. Follow reps 1 through 5 of part A above.
wrap".
2. In the righ t pane, place a check mark in the check box labeled "Word

C. Instru ct the Code Editor to indent by two spaces.


1. Follow steps 1 through. 4 of part A.
2. C lick on the subtopic "Tabs".
box to 2.
3. ln the right pane, change the numbe r in the "Inden t size:" tex t

Man age Text Files


Note: If the olution Exp lorer window i not vi ible, click on Solution
Explorer
lorer win-
in the View menu. lf the bin folder does not show in the Solutio n Exp
n Explor er toolbar.
dow, click on the Show A ll Files button in the Solutio
Appendix B How To
• 583

A. Display a tex t file assoc iated with an


ope n program.
1. In the Solution Exp lore r wind ow, open
the bin fold er by double-clicking on it.
2. Ope n the Debug subfolde r of the
bin folder by double- cli cking on it. (Th
text file should appea r in a list of seve e
ral fi les. If the fil e is not listed in the
Debug subfolde r, clic k the Refresh butt on
in the Solu tion Exp lore r.)
3. Dou ble- clic k on the tex t file
to ope n it. (Th e con tent s of the fil e
d isplayed in a tabbed Tex t Edit or in will be
the Doc ume nts wind ow, and the fil e-
n ame will appe ar in the tab.)

B. Sav e the file that is displaye d in the


Tex t Editor.
1. Rig ht-c lick on the tab and then click
on Save filename in the drop -down
con text menu. Or, press Ctrl + S. Or,
click on Save filename in the File
menu.

C. C lose an ope n Tex t Editor.


1. C lick on the close butt on ( X ) on the
tab. Or, righ t-cli ck on the tab con-
tain ing the filen ame at the top of the
Doc ume nt wind ow and click on Close
in the drop -dow n con text menu. Not
e: If the text file has not been save
Visual Bas ic wi ll prom pt you abo ut sav d,
ing it.
D. Imp ort an ex isting tex t file into an
ope n program .
Not e: Thi ta k i esp cia lly useful
whe n imp orti ng a file from a "Text_Fi
for_Exe rcises" fold er. les_

1. U e Win d ows Exp lore r to loca te the


file.
2. Righ t-cli ck on the file, and click
on Copy in the drop -dow n con text men
O r, click on the file and press C trl + u.
C.
3. In the Solution Explore r window,
righ t-cli ck on the Debug ubfo lder of
bin folder and click on Paste in the drop the
-down con text menu . O r, click on
the Debug subfolde r and press C trl +
V.
E. Cre ate a new text file in an ope n
program.
1. C lick on the nam e of the prog ram
at the top of the So lutio n Explore
wind ow. r
2. C lick on Add New ltem in the Proj
ect menu. (An "Ad d N ew Item" inpu t di-
alog box wi ll appear.) Alte rnat e ly, click
on the Add New ltem button in the
Too lbar.
3. Se lec t the Tex t File icon in the inpu
t dialog box, and ente r a base name for
the file in the "Na me" tex t box . (Visual
Bas ic will auto matically add the ex-
tens ion ".tx t" to the nam e. )
4. C lick on the Add butt on. (A tabbed
Tex t Editor will appear in the Doc ume
window.) nt
5. Type the con tent s of the file into
the Tex t Editor.
6. Righ t-cli ck on the tab and click
on Save filename in the drop -down con
menu. text
7. Righ t-cl ick on the tab and click on
Close in the drop -down con text menu.
8. Loc a te the tex t fil e at the bott
om of the Solution Explore r window.
9. Move the tex t fi le to the Debug subf
olde r of bin. (Th e move can be acco m-
plished eith er by drag-and -dro p or by
C ut and Paste.)
584 • Appendix B How To

text file in an ope n prog ram .


F. Modify the con tent s of an existing
d ow, loca te the tex t fil e in the
bin \ Debug
1. In the Sol utio n Exp lore r win
sub fo lde r. a tabbed
disp lay the con ten ts of the file in
2. Double- clic k on the filen ame to
Tex t Edi tor.
using the Tex t Editor.
3. Alt er the con ten ts of the file
t Edi tor.
4. Sav e the file and close the Tex
an ope n program.
G. Delete an ex isting text fil e from
dow, loca te the tex t file in the
bin \Debug
1. In the So luti on Explore r win
sub fold er. own con tex t
and clic k on Delete in the drop-d
2. Right-click on the filen ame
menu.
me age box tha t app ears.
3. C lick on the OK but ton in the

on me nt
Co nfi gu rin g the Wi nd ow s En vir
sett ing for the mon ito r.
A. Det erm ine and /or cha nge the DPl
Windows XP
p to disp lay a con tex t menu.
1. Right-click on the Win dows des kto perties" d i-
menu to brin g up the "Display Pro
2. C lick Properties in the con tex t
alog box .
"Display Properties" dialog box.
3. C lick the Set tings tab on the og box. The
disp lay the mon itor properties dial
4. C lick the Advanced but ton to
in the "DPI sett ing" box.
curr ent DPI sett ing will be sho wn etti ng in
the sett ing, se lect a diff eren t DPI
5. If you wou ld like to cha nge t ures in this boo k
. [Note: The scre en cap
the "DP I se ttin g" dro p -do wn box t sett ing,
rma l Size (96 DPI )." Wi th tha
we re don e with a DPI se ttin g of "No
will appea r like those in the book.]
the form s you see on your scree n er before app ly-
6. If you cha nge d the DPI sett
ing, click on "Restar t the com put
ing the new disp lay sett ings ." not hin g will
did not cha nge the DPI se ttin g,
7. C lick the OK but ton . (If you you
"Display Properties" dialog box, and
hap pen . You wi ll be retu rned to the
to the desktop. )
can press the OK but ton to retu rn d. C lick the
8. If you cha nged the DPI sett
ing, a message box wi ll be displaye
questio n posed, clic k the Clo se but ton
OK but ton twice, answe r "Yes" to the k on the Yes
per ties" dialog box, and clic
at the bot to m of the "Display Pro
allow the cha nges to take effect.
but ton to re tart your com put er and
Win dows Vista
p to disp lay a con tex t menu.
1. Right-c lick on the Win dows deskto e appear-
t menu to disp lay the "Personaliz
2. C lick Personalize on the con tex
anc e and sounds" window. ed for an
fon t size (DPI)". (If you are pro mpt
3. In the left pane, click "Adj ust d or pro vide con -
atio n, type the passwor
ad ministr ato r password or con firm ing will be
firmation by press ing the Continu
e but ton.) The cur ren t DPI sett
indi cated. te: The
oth er DP I etti ng, clic k on it. [No
4. If yo u would like to select the "De faul t scale
don e wit h a DPI se ttin g of
scree n cap tures in this boo k were
Appendix B How To • 585

(96 OPI)". With that setting, the forms you see on your screen will look like
those in the book.]
5. C lick on the OK button. (If you did not change the DPl setting, nothing
will happen. You will be returned to the Personali ze window, and you can
close the window to return to the desktop.)
6. If you changed the DPl setting, restart your computer to allow the changes
to take effect.

Windows 7
1. Right-clic k on the Wind ows desktop to display a context menu .
2. C lick Personalize on the context menu to display the Personalization window.
3. C lick on Display near the bottom of the left pane. Three radio buttons (la-
beled Smaller - 100%, Medium - 125%, and Large r - 150% ) wi ll appear
with the current setting selected. Note: The screen ca ptures in thi book
were made with a setting of"S maller - 100%". With that setting, the forms
you see on your screen wi ll look like those in the book.
4. If yo u do not want to change the setting, clos the window.
5. Othe rwise, select a different setting and click on the A jJply button. (You will
be instructed to log off yo ur computer in order to allow the change to take
effect. Note: You wi ll not have to restart your computer. )

B. Co nfigure Wind ows to display fil ename ex tensions.

Windows XP
1. C li ck on Folder OjJtions in th Tools menu. (A Fo ld e rs Options dialog
box will appear.)
2. C lick on the View tab in the dia log box.
3. If there is a check mark in the box next to "Hide ex tensions for known file
type ",cl ick on the box to remove the check mark.
4. C lick on the OK button to close the Folders Options dia log box.

Windows Vista and Windows 7


1. C lick on the Start button.
2. Windows Vista Type "Folder Options" into the "Start Search" box and press
the Enter key. (A Folders Option dialog box will appea r.)
Windows 7 Type "Fold r Options" into the "Search programs and fi le " box.
(A Control Panel box will ap pear.) Cl ick on Folder Options. (A Folders
Options dialog box will appea r.)
3. C lick on the View tab in the Folder Options dia log box.
4. If there is a check mark in the box nex t to "Hide extension s for known file
types", click on the box to remove the check mark.
5. C lick on the OK button to close the Folders Options dia log box.

Use a Printer
A. Obtain a printout of a program.
1. Invoke the Code Editor.
2. C lick on Print in the File menu. Or, press C trl + P.
3. C lick on the OK button.
586 • Appendix B How To

8. Pr int the curren t form.


Double-click on the PrintFo rm contro l in the Visual Basic PowerP
aci<s group
1.
with the defa ul t name PrintFo rml
of the Too lbox. (The co ntrol will appear
in the compo nent tray at the bottom part of the Form Des igner.)
2. Exec ute the follow ing code:

Pr i n tFo rml.Pr intAc ti on Pri n ting . PrintA ction . PrintT oPri nter
Pr in tFo rml . Prin t()

C. Print the conten t of a DataG ridView con tro l.


following
1. After a PrintD ocume nt contro l h as been addeJ to the form , the
lleges wh en btnPri nt is
code prints the DataG ridView co ntrol named dgvCo
clicked:
Cl ick
Privat e Sub btn Print_ Click( ... ) Handle s btnPr int.
Pr intDo cumen t l . Print ()
End Sub
s
Privat e Sub PrintD ocume ntl _ PrintP age ( ... ) Handle
PrintD ocume ntl.Pri ntPage
Dim bm As Bitmap = New Bitmap (dgvC ollege s . Wi dth,
dgvCol leges. He i ght)
ay Rec t ang le)
dgv Col l eges. DrawTo Bitmap (bm, dgvCo lleges .Displ
Point (75, 100 ))
e .Grap hi cs . Dr a wimage Unscal ed(bm, New
End Sub
one inch
The argume nt New Point (7 s , 100 l causes the table to be printed
fro m the top of the page. In genera l, New
from the left side and one inch
Po int (x, yl causes the tab le to be printed about (1/4 + x/100) inches
from the left sid e and y/100 inches fro m the top of the page.

D. Pr int the conten ts of a list box .


box. Just
1. The code in part C above also can be used to print the conten ts of a list
control with the name of the list box.
replace the name of the DataG ridView

Misc ellan eous


A. Enlarge the Docum ent window to fi ll the entire sc reen .
screen , click
1. C lick on Full Screen in the View menu . (To return to the regular
the menu bar.)
on the newly created Full Screen butto n at the right ide of

8. Return the IDE to its ori ginal layout.


1. C lick on Reset Window Layout in the Window menu.

C. Store frequently used code for easy inclus io n into other programs.
1. Select the code as a block.
the code in
2. Drag the block of code into the Toolbox. (Yo u wi ll now h ave
both the Code Editor and the Toolbox.)
the Code
Note: The block of code will be visible in the Toolbo x wh enever
a copy of the code into the Code
Ed ito r is open. At any time you can drag
Ed itor.
Appendix B How To • 587

D. O pen Windows Exp lorer.


1. Right-click on the Start button and click on Explore (XP or Vista) or
Open Windows Explorer (Windows 7) in the contex t menu.

E. Display all the characters in a font.


1. C lick on the Windows Start button .
2. Hover over A ll Programs.
3. lick on A ccessories.
4. C lick on Sys tem Tools.
5. C lick on C haracter Map.
6. C lick on the dow n-arrow at the right end of the Font box.
7. Select the des ired font.
AP PE ND IX C
fiLES AND fOLD ERS

W e .use the word disk to refer to either the h ard disk, a diskette, a USB fl
drive, a CD, or a DVD. Each dnve IS td ennfted by a letter. Normally,
hard drive is identifie d by C, the diskette drive by A, and the CD (or DVD)
ash
the
drive by
D or E. Disk manage ment is h andled by Window s.
Disks hold not only programs, but also collections of data stored in file
. The
te rm file refers to either a program fi le, a text fil e, or some other kind of
data file.
Each file has a name consisti ng of a base name fo llowed by an optio na
l extensio n
consisti ng of a period and one or more charact ers. The term filenam e refers
to the
combin ation of the base name, the period, and t he extensio n. A fil ename
ca n co n-
tain up to 215 characte rs, typica lly consisti ng of lette rs, digits, spaces, periods,
and
other assorted characte rs. (The only charact er that cannot be used in filenam
es are
\ , / , : , *, ?, < , > , ", and I.) Extens ions are norma lly used to id entify t he
type of
file. For example, spreads heets created with Exce l have the ex tension
xlsx o r xls
(eXceL Spreads heet), docume nts created with Wo rd have the extensio n
docx or doc
(DOCu ment), and files created with Notepa d have the ex tension txt (TeXT
docu-
ment). Some exampl es of filename are "Annu al Sales.xlsx", "Letter to Mom.do
cx",
and "Phone .txt".
Because a d isk is capable of holding tho usands of fi les, locating a specific file
can
be qu ite time consum ing. Therefore, re lated files are grouped into collecti
o ns ca lled
folders . For instance, one fo ld er might hold all your Visual Basic program
s, and
anothe r the docume nts crea ted with your wo rd processo r.
Think of a d isk as a large fo lder, called the root folder , that contai ns
several
sma ller folders, each with its own name. (The nam ing of fold ers follows
the sa me
rules as the naming of fi les.) Each of these smaller fo lders can conta in
ye t o ther
named folders. Any folder contain ed inside another fold er is said to be a subfold
er of
that fo lder. Each fo lder is identified by listing its name precede d by the names
of the
successively larger fo lders that contain it, with each folder name precede d
by a back-
slash. S uch a sequenc e i called a path . For instance, the path \Sales\
NY08 \ ] uly
iden tifies th e fo lde r] uly, contained in the fo lder NY08, which in turn is
co ntained
in the folder Sales. Think of a file, along with its name, as wr itten on a slip
of pape r
that can be placed into e ither the root fold er or o ne of the smaller folders.
The com-
binatio n of a drive letter fo llowed by a colo n, a path, and a fi lename
is called a
filespec , an abbrev iat ion of "file specific ation." Some exampl es of filespec
s are
C: \ VBOI \ VB.exe and E: \Person a l \ Income09. txt.
Neither Window s nor Vi ual Bas ic distinguishes be tween upperca se and
lowe r-
case letters in fo lder names and filenames. Fo r instance, the names COST
S02.T XT,
Costs02 .T xt, and costs02 .txt are equiva lent.
In many cases fo lders are referred to as directo ries. Many Vi ual Bas ic
o bj ects
and comma nds still refer to fo lders as director ies. The terms "root fo
lder" and
"path" are a referenc e to the "tree" metaph o r co mmonly used to describe
the o rga-
nization of files. In this metaph o r, the large fold er at the lowes t leve l of
the disk is

589
590 • Appendix C Files and Folders

t of as
the roo t folder. The smaller folders contain ed in the root folder can be though
branche ,
branches that emanat e fro m the roo t. Each branch may have smaller
e in one
which in turn may have their own smaller branche s, and o on. Finall y, a fil
leaf on a branch. The leaf is reached by start-
of the e fo lders can be though t of as a
ing at the root and followin g a path through the branche s.
APPE NDIX D
VISUAL BASIC DEBUG GING TOOLS

rrors in progra ms. are called bugs, and the process of finding and correcting them
E is called debuggmg. S nl.Ce Vtsual Baste does not dtscover e rrors due to fau lty
logic, these errors present th e mos t difficulties in debugging. O ne method of discov-
ering a logic error is by desk checking- that is, tracing the va lues of variables on
paper by writing down their expected value afte r "mentally exec uting" each line in
the program. Desk checking is rudimentary and highly impractical except for small
programs.
A nother method of debugging involves plac ing MessageBox . how statements at
strategic points in the program and display ing the va lues of selected variables or
express ions until the error is detected. After correcting the error, you can remove the
MessageBox.Show statements. For older programmin g environmen ts, desk checking
and MessageBox.Show statements we re the only debugging methods ava ilable to the
programmer.
The Visual Bas ic debugger offers an alternative to desk checking and to inserting
MessageBox.Show statements. It allows you to pause during the execution of your
program in order to view and alter va lues of variables. The e values can be accessed
through the Immed iate, Watch, and Loca l windows, known as debugging windows.

The Three Program Modes


At any time, a program is in one of three modes-desi gn mode , run mode, or debug
mode. (Debug mode is al o known as break mode.) When the current mode i "run"

~ WindowsApplica ionl - Microsoft Visua l Basic 2010 Express

Fi le Edit View Project Debug Data Format Tools Win dow Help

Title bar, Menu ba r, and Toolba r d uring design mode.

[iJ WindowsApplicationl (Running) -


File Edit View Project Debug Data Format Tool> indow

Title bar, Menu bar, and Too lbar during run mode.

[iJ WindowsApplica ionl (Debugging) - Microsoft Visu al Basic 2010 Express


File Ed it View Project Debug Too ls Win dow Help

Title bar, Men u bar, and Too lbar during debug mode.

591
592 • Appendix D Visua l Bas ic Debuggin g Tools

o r "debug," the words "Runnin g" o r "Debugg ing" are displayed (in parenthe es ) in
the Visual Bas ic title bar. The abse nce of these wo rds indica tes that the curren t
mode is "des ign. "
W ith the program in des ign mode, you place contro ls on a form, set their initial
properties, and write code. Run mode is initiated by press ing FS or the Start Debugging
button. Debug mode is invoked automati cally when a run-time error occurs. You can use
Debug options to break the program at specified places. While the program is in debug
mode, you can hover the cursor over an y variable to obta in its current value. Also, you
can usc the debugging windows, such as the Immediate, Watch , and Locals windows, to
examine values of expressio ns. When you enter debug mode, the Too lbar contains a
Continue button. You can click on it to continue with the executio n of the program.

Steppi ng throug h a Progra m


T he program can be execu ted one statemen t at a time, with each press of an appro-
priate function key executin g a statemen t. This process is call d stepping . After each
step, va lu es of variables, express ions, and conditio ns can be displayed in the debug-
ging windows , and the va lues of variables can be changed .
W hen a proced ure is ca lled, the lines of the procedur e can be executed one at a
t ime, refe rred to as stepping into the procedur e, or the entire procedur e can be exe-
cuted at once, referred to as stepping over a procedur e. A step ove r a procedur e i
called a procedu re step. In addi tion , yo u can execute th remainde r of the curren t
proced ure at once, referred to as stepping out of the proced ure. The three too lbar
bu ttons hown in Figure D.l can be used fo r stepping.

FIGURE 0.1 The Toolbar buttons used to Step Into, Step Over, and Step Out.

As another debugg ing too l, Visual Bas ic allows the program mer to specify ce r-
ta in lines as breakpo ints. Then , when the program is run, ex cution will stop at the
first breakpo int reached . T he programm er can then either step through the program
or continue execut ion to the next breakpoi nt. Also, the program mer ca n place the
curso r o n any line in th e program and have executio n stop at that line with a "Run
to Cu rso r" command . Program executio n norm ally proceeds in ord er th ro ugh the
stateme nts in a procedur e. How ve r, at an y time the program mer can spec ify the
next statemen t to be executed.
T he task discussed prev iously are summari zed next, along with a mean to carry out
each task. The tasks invoked with function k ys also can be produced from the menu
bar, the context menu (produced by clicking the right mouse button) , or the Toolbar.

Ru n to cursor Press Ctrl + F8


Step Into Pres F8
Step Over Press Shift + F8
S tep O ut Press C trl + Shift + F8
Set a breakpoi nt Move cursor to line, press F9
Remove a breakpoi nt Move curso r to line containi ng
breakpoi nt, pre s F9
C lea r all breakpo in ts Press C trl + S hift + F9
Con tinue execut ion of the program Press FS
Stop debugg ing C trl + A lt + Break
Appe ndix D Visua l Basic Debugging Tool
• 593

The Immediate Window


Whil e in break mode, you ca n set the foc us to the
Imme diate wind ow by click ing on
it (if visibl e), by pressing C trl + Alt + 1, or by hove
ring the curso r over Windows in
the Debug menu and click ing on Immediate. Whe
n you type a state ment into the
Immediate window and press the Enter key, the
statem ent is execu ted at once. A
state ment of the form

? expr essio n

displays the va lue of the expression on the next line


of the Immed iate window. (The
quest ion mark is short hand for Oebu g. Print .) A state
ment of the form
var = value

a signs a value to a variab le. In Figur e 0.2, the varia


ble numVar had the va lue 10
when the program was interrupted.

Imme diate \11/inclo w


? 2 * nu Va r
28
.
nuRVa r = 188
? 2 * numVa r
288
Ill

FIGURE D.2 Three statem ents execu ted in the Imme diate windo
w.

The Watch Window


The Watc h wind ow, wh ich ca n be viewed only in
break mode, perm it yo u to view
the values of va riables and express ions. The Watc
h wind ow in Figur e 0.3 shows the
va lues of one var iab le and two exp ress ions. If you
don't see a Watc h window when
you enter break mode, hov r the curso r over Wind
ows in th e Debug menu, and then
click on Watch.

\ 1\ atch
·~X
Name Valu e Type ....
1 num 100 Integer
1 5 "'num 500 Int.eger f=J
1 num >90 True Boolean

FIGURE D.3 A typica l Watc h windo w.

A lthough yo u can type direc tly into the Watc h wind


ow, the easies t way to add
an express ion to the wind ow is to right- click on
a variab le in the Code Edito r and
then click on Add Watch in the conte xt menu. You
can th en alter the ex pre ion in
the N ame colum n of the Watc h wind ow. To delet
e an ex press ion from the Watc h
window, right- click on the express ion and then click
on Delete W atch. Also, you can
directly chan ge the va lue of any variab le in the Watc
h window and have the va lues
of the other express ions chan ge accord ingly.
s
594 • Appe ndix D Visual Bas ic Debu gging Tool

Th e Locals Wi ndo w
ls wind ow from the Debug menu by pos i-
Whi le in brea k mod e, you can open the Loca
ing on Locals. Th is wind ow auto mati -
tioni ng the curso r over Wind ows and then click
of all varia bles in scope. ee Figure 0.4.
ca lly displays th e nam es, va lues, and types
of va riables at any time .
You can use the wind ow to alter the valu es

Loca l;.
Type
Nam e Valu e
:+J 1 l\1e
[+J ; e
Integer
; num 1 3
Integer
1 num2 4
·-4 .. String
; phrase "Hello world.•
-- -- -- --
FIGURE 0.4 A typical Loca ls wind ow.

Six Wa lkth rou ghs


gg ing too ls with the prog ramm ing struc-
The follo wing vvalk thro ughs use the debu
tures cove red in C hapt ers 3, 4, 5, and 6.

m: Cha pte r 3
Ste ppi ng thr oug h an Ele men tar y Progra
ral capa biliti es of the debu gge r:
The follo wing walk throu gh demonstrates seve
and a text box (txtBox).
1. C reate a form with a butto n (btn Push )
follo wing even t proc edure:
2. Double-click on the butto n and ente r the
Han dles btnP ush. Clic k
Priv ate Sub btnP ush_ Clic k( ... )
Dim num As Inte ger
ber: "))
num = Cin t(In pu tBox ("En ter a num
num += 1
num += 2
txtB ox.T ext CStr (num )
End Sub

te Sub, press th e right mouse butt on,


3. Place the curso r on the line begi nning Priva
exec ute, and th e form will appear.
and click on Run to Cursor. The prog ram will
appe ars and a yello w arrow po int to the
4. C lick on the butto n . The Cod e Ed itor
Priva te Sub state ment.
to the state men t cont ainin g Inpu tBox to
5. Press F8. T he ye llow arrow now poin ts
sing F8 is referred to as stepping into.
indic ate that it is to be exec uted next . (Pres
a program with the Step lnto optio n
You can al o step to the next state men t of
icon in the Toolbar.)
from th e Debug menu or with the Step Into
6. Press F8. The state men t co ntain ing
InputBox is exec uted, and an inpu t di alog
to the requ es t by typing 5 and click -
box requ est ing a num ber appea rs. Respond
ing the OK butto n.
t num += 1.
7. Press F8 aga in to exec ute the state men
Appendix D Visual Basic Debugging Tools
• 595

8. Let the mouse hover ove r any occ urrence of the va ria ble num fo r a seco nd
or so. The current va lue of th e variable will be di splayed in a small box . See
Figure 0.5.

frmEiementa ry.vb X frmEiementary.vb [Design] •


.., l' btnPu!;h · I Click ·
Pr ivate Sub btnPu s h_Clic k(ByVal sende r As System. 0bject , ByVal i.
'T
Dim num As Intege r
num = Cint ( InputBo x( "Enter a nurrber:" ))
nurr. += 1 I=
hurr += 2
t xtB ox . Te xt CSt r ( nu '
End Sub ; num 6::.1
100% Ill

FIGURE 0.5 Obtaining the value of a variable.

9. Press the Stop Debugging button on the Toolbar. (You also can stop debugg ing by
clicking on StoJJ Debugging in th e Debug menu.)
10. Move the cursor to th e line

num += 2

and then press F9. A red dot appea rs on the gray bord er to the left of the line.
This indica tes that the line is a brea kpo int. Press ing F9 is referred to as toggling a
breai<JJoint.
11. Press F5 and click on the button. Respond to the request by entering 5 and click-
ing on OK. The program executes the first three lines inside the procedure and
stops at th e brea kpoint. At this po int, the breakpo int line has not ye t exec uted.
12. Open the Immediate wind ow by press ing C trl + Alt + I. If neces ary, clea r th e
contents of the window by press ing the right mouse button and selecting "Clea r
A ll". Type the statement

? num

into th e Immediate window, and then press Enter to execute the statement. The
appea rance of "6" on the nex t line of the Immediate wind ow co nfirms that the
breakpoint line was not executed.
13. C li ck on the Code Editor.

14. Move the cursor to the line num += 1 , cli ck the right mouse button, and th en
click on "Set next Statement".
15. Press F8 to execute th e se lected line.
16. Return to the Immediate wind ow by clicking on it. Type th e statement" ? num"
and pres Enter to confirm that the va lue of num i now 7. Then return to the
Code Editor.
17. Move the cursor to the brea kpo int line and pres F9 to deselec t the line as a
brea kpoint.
596 • Appe ndix D Visua l Bas ic Debu gging Tools

the program. O bse rve that the valu e


18. Press FS to exec ute the rema in ing lines of
displayed in the tex t box is 9.

ctio n
Step pin g thro ugh Programs Con tain ing Sele
Structures: Cha pter 4
If Blo cks
the cond it ion of an If state ment is
The follo wing wa lkthrough demo nstra tes how
n:
evaluated to deter mine whet her to take an actio
1. C rea te a form with a butto n (btnP ush)
, a text box (txtB ox ), and the fo llowi ng
code:
les b t nPus h . Clic k
Priv ate Sub btnP ush_ Clic k( .. . ) Hand
Dim wage As Doub l e
wag e= CDb l(Inp utBo x("W age : "))
If wage < 7 .2 5 Then
txtB ox.T ext "Belo w minim um wage ."
Else
txtB ox. Text "Wag e Ok."
End If
End Sub
Sub", pres the right mouse but-
2. Place the curso r on the line beg inn ing "Private
am will exec ute and the form will
ton, and click on "Run to ursor". The progr
appear.
ye llow arrow poin ts to the state -
3. C lick on the butto n, and then press F8. The
ment cont a ining Inpu tBox .
aining lnpu tBox. Type a wage of
4. Press F8 once to exec ute the state ment cont
is highl ighte d but h as not been
6.25, and press the Ente r key. T he If state ment
exec uted.
has jump ed to the tatem ent
5. Pres F8 once, and notice that the ye llow arrow
. " Beca use the cond ition "wage < 7.25"
txtB ox . Text = "Belo w minim um wage
en .
is true, the actio n assoc iated with Then was chos
. N otice that Else is skipp ed and
6. Press F8 to exec ute the txtBox.Tex t state ment
the ye llow arrow poin ts to End If.
, and the state ment follo wing
7. Press F8 aga in. We are through with the If block
the If block , End Sub, is high ligh ted.
8. Pre s C trl + A lt + Brea k to term inate debu gg ing.
in with 7. 75 ente red as the wage.
9. If des ired, try stepping thro ugh the program aga
false, the Else actio n will be exe-
S ince the cond ition "wage < 7 .25" will be
cuted inste ad of the Then actio n.

Sele ct Cas e Blo cks


Selec t Case block uses the se lecto r to
The follo wing wa lkthrough illust rates how a
choose from amon g several act ions.
a tex t box (txtB ox ). Do ub le-cli ck on
1. C reate a form with a butto n (btnPush ) and
th e butto n and ente r the follo wing proced ure:
Appendix D Vi ual Basic Debugging Too ls • 597

Private Sub btnPush_ Click( ... ) Handles btnPush.Click


Dim age , price As Double
age= CDbl ( InputBox("Age:"))
Select Case age
Case Is < 12
price 0
Case Is < 18
pr i ce 3.5
Case Is >= 65
price 4
Case Else
price = 5 . 5
End Select
txtBox . Text "Your ticket price is " & FormatCurrency(p rice)
End Sub

2. Place the cursor on the line beginn ing "age =", press the righ t mouse button, and
click on "Run to C ursor". T he program will execute, and the form will appear.
3. C lick on the button. The arrow will point to the statement beginning "age=".
4. Press F8 once to execute the statement begin ning "age=". Type an age of 8, and
press the Enter key. T he arrow points to the Select Ca e statement, but the
statement has not been executed.
5. Press F8 twice, and observe that the arrow points to the act ion as oc iated with
"Case Is < 12".
6. Press F8 once to exec ute the ass ignme n t sta tement. Not ice that the a rrow now
po ints to End Select. Th is demon trates that when more than one Ca e clause is
true, only the first is acted upon.
7. Press C trl + A lt + Break to terminate debugg ing.
8. If des ired , step through the program aga in, entering a different age and predict-
ing which Ca e clause will be acted upon. (Some poss ible ages to try are 12, 14,
18, 33, and 67.)

Stepping through a Program Containing a General


Procedure: Chapter 5
The fo llowing wa lkth ro ugh uses the single-s tepping feature of the debugge r to trace
the fl ow th ro ugh a Sub procedu re.
1. C reate a form with a button (btnPush) and a text box (txtBox). Then enter the
following two proced ures:

Private Sub btnPush_ Click( ... ) Handles btnPush.Click


Dim p, b As Double
p = 1000 'Principal
UpdateBalance(p, b )
txtBox.Text = "The balance is " & FormatCurrency(b )
End Sub

Sub UpdateBalance(By Val prin As Double, By Ref bal As Doubl e)


' Calculate the balance at 5% interest rate
Dim interest As Double
598 • Appendix D Visua l Basic Debugging Too ls

interest = 0.05 * prin


bal = prin + interest
End Sub

2. Place the cursor on the line beginning "Private Sub", press the right mouse
button, and click on "Run to C ursor". The program will execute, and the form
wil l appear.
3. C lick on the button. In the Code Editor, a ye llow arrow points to the Private
Sub statement.
4. Press F8 once, and obse rve that the ye llow arrow now po ints to the tatement
p = lOOO . This statement will be executed when F8 is next pressed.

5. Press F8 aga in. The state ment p = 1000 was executed, and the ye llow arrow
now points to the statement calling the Sub procedure GetBalance .
6. Press F8, and obse rve that the ye llow arrow is now po inting to the header of the
Sub procedure.
7. Press F8 three times to execute the ass ignment tatements. The ye llow arrow
now po ints to the End Sub statement. (Notice that the Dim and comment tate-
ments were skipped.)
8. Press F8, and notice that the ye llow arrow has moved back to the btnPush_Cl ick
event procedure and is pointing to the calling statement. By hovering the cu rsor
over the va riab le b, yo u ca n ver ify that the Sub procedure was executed.
9. Press the Sto jJ Debugging button to terminate debugg ing.
+ F8 to ste jJ over the Sub proce-
10. Repeat Steps 2 through 5, and then press Shift
dure GetBalance. The Sub procedure has been executed in it en tirety.

11. Press C trl + A lt + Break to terminate deb ugg ing.

Commun icating between Argumen ts


and Paramet ers: Chapter 5
The fol lowing walkthrough uses the Loca ls window to monitor the values of argu-
ments and pa rame ters during the execu tion of a program.
1. If you have not already done so, type the preceding program into the Code Editor.
2. Place the cursor on the line beginning "Private Sub", press the right mouse button,
and click on "Run to C ursor". The program will execute, and the form will appear.
3. C lick on the button.
4. C lick on the Debug menu, hove r the cur or ove r Windows, and then click on
Locals. Notice that the variables b and p from the btnPush_Click event proce-
dure appea r in the Locals window. The other var iab les in the list (Me, se nd er,
and e) needn 't conce rn us.
5. Press F8 twice to point to the calling statement. Notice that the value of the
variable /J has changed .
6. Press F8 to call the Sub procedure. Notice that the variables disp layed in the
Locals window are now those of the procedure GetBalance .
7. Pre s F8 three times to execute the procedure.
Appe ndix D Visua l Bas ic Debugg ing Too ls
• 599

8. Press F8 to return to the btnPu sh_C lick even t


proced ure. Not ice that the value
of the va riab le b has inherited the value of the varia
b le bal.
9. Press Ctrl + A lt + Break to termi nate debugg
ing.

Step ping thro ugh a Pro gram Con tain ing a Do


Loop:
Cha pter 6
The fo llow ing walk throu gh demo ns trates the use
of the Watc h window to mon itor
the va lue of a co nditio n in a Do loop that searc hes
for a name:
1. Creat e a form with a list box (lstNames), a butto
n (btnPush), and a text box
(txtBox). Then doub le-click on the butto n and enter
the follow ing event procedure:
Priv ate Sub btnP ush Click ( . .. ) Hand
les btnP ush.C lick
'Look for a spec ific name
Dim searc hNam e As Strin g, name = ""
Dim i As Integ er = 0
Dim numN ames As Integ er = lstNa mes
. Item s.Co unt
searc hNam e = Input Box ("Nam e:") 'Name to searc h for in list
Do Whil e (name <> searc hNam e) And
(i < numN ames)
name CStr (lstN ames . Item s(i))
i += 1
Loop
If name = searc hNam e Then
txtBo x.Te xt name
Else
txtBo x.Te xt "Name not found "
End If
End Sub

2. Fill the list box's Strin g Colle ction Ed ito r with


four line conta ining the name s
Bert, Ernie, Grover, and Oscar.
3. Place the curso r on the line beginning "Private Sub",
press the righ t mouse butto n,
and click on "Run to C ursor". The program wi ll execu
te, and the form will appea r.
4. Click on the button. The ye llow arrow points to
the heade r of the event procedure.
5. Righ t-clic k on the variab le search Name, and click
on "Add Watc h". The var i-
ab le searchName has been add ed to a window titled
Watc h .
6. Repeat Step 5 for th e va riab le name.
7. Drag the mouse across the words name <> searc
hNam e to highl ight them. Then
click the right mouse butto n, and click on "Add
Watc h". The Boolea n expres-
sion has been added to the Watc h window.
8. Press F8 five times to execu te the statement
conta ining InputBox. Enter the
name "Erni e" in the input dia log box, and then click
OK.
9. Pres F8 repeated ly until the entir e even t proce
dure has been executed. Pause
afte r each keypress, and not ice how th e va lues of
the expressions in the Watc h
window change.
10. Press the Close butto n on the form to termi nate
debugging.
AN SW ER S
To Sel ect ed Od d-N um ber ed
Exercises

CHAP TER 2
EXERCISES 2.2
1. After a button is clicked, it has a blue bo rd er.
3. C lick on the fo rm to make it the selected object.
C lick on the Prope rties window or Press F4 to act ivate the
Prope rties window.
Select the Text property.
Type "CHE CKIN G ACCO UNT" .
5. Double-click the TextBox icon in the Toolbox.
Act ivate the Properties window.
Select the BackC olor property.
C lick on the down- arrow to the right of the Settin gs box.
C lick on the C ustom tab, and then click on the desired ye llow
in the palette.
C lick on the form to see the empty ye llow text box.
7. Double-click on the Label icon in the Toolbox.
Activ ate the Prope rti es window, and elec t the AutoS ize prope
rty.
Set the AutoS ize property to False.
Select the Text property and type the req uested se ntence.
Select the TextA lign property.
C lick on the down-arrow button to the right of the Settin gs box,
and click on one of the center rectangles.
Resize the label so th at the senten ce occupi es three lines.
9. Double-click on the TextBox icon in the Toolbox.
Act ivate the Properties window.
Set the Name property to txtLanguage.
Select the Text property and type "Visua l Basic 2010".
Select the Font prope rty and cl ick on the ellipsis to the right
of the Settin gs box.
Scroll up the Font list box, and click on Couri er New in the
Font box.
C lick OK.
Widen the text box to acco mmod ate its text.
11. Double-click on the Button icon in the Toolbox.
Act ivate the Properties window, and select the BackC olor proper
ty.
C lick on the down- arrow button to the right of the Settin gs
box.
C lick on the Custo m tab, and then click on the wh ite sq uare
in upper-left corner of the palette .
Se lect the Text proper ty and type "PUSH ".
Select the Font prope rty, and click on the ellipsis.
C lick on Iralic (with XP or Vista) or Oblique (with Windows
7) in the "Font style" li t.
C lick on 24 in the S ize box and click OK.
Res ize the butto n.

601
602 • Answ ers To Se lected O ud -N umbcred Exercises

13. Doub le-click on the Butto n ico n in the Too lbox.


Activ ate the Properties window.
Se lect the Text property and type "PUS &H".
C lick on the fo rm to see the resul ting butto n.
15. Double-click on the Labe l icon in the Toolbox.
Activ ate the Prope rties window.
Selec t the Nam e property and type ''lblA KA".
Selec t the Tex t property and type "ALI AS".
Selec t the AutoSize property and set it to Fal e.
Se lect the Font property and click on the ellips is.
Wind ows 7) in the "Fon t style" list.
C lick on Italic (w ith XP or Vista ) or Oblique (with
C lick OK.
box to the right of the Settings box,
Selec t the Tex tAlign prope rty, click on the down -arrow
and click on one of the cente r recta ngles.
17. Double-click on the Labe l icon in the Toolb ox.
tAlign property.
Act ivate the Prope rties window, and selec t the Tex
ngs box, and cl ick on one of the
C lick on the down -arro w box to the right of the Setti
recta ngles on the right .
Se lect the AutoSize property and set it to False.
and press Enter.
Selec t the Text prope rty, type "VIS UAL BASIC",
the labe l until the words occup y two
If the word s "VIS UAL BAS IC" are on one line, resize
lines.
19. Double-click on the Label icon in the Toolb ox.
prope rty.
Activ ate the Prope rties wind ow, and selec t the Font
C lick on the ellipsis to the right of the Settin gs box.
C lick on Wingd ings in the Font box.
box.
C lick on the largest size ava ilab le (72) in the Size
C lick OK.
a less than sign ( < ).
Selec t the Text property and chang e the setting to
C lick on the labe l.
(Note: If you didn' t know that the less than symb
ol corre spond ed to a diske tte in the
tte chara cter in the C h aract er Map,
Wingdings font, you could double-click on the diske
press C trl + V. The less than chara cter
click the Copy butto n, select the Text property, and
will appear in the Text settin gs box.)
ox.
21. Double-click on the ListB ox icon in the Toolb
Activate the Prope rties wind ow, and selec t the Back Colo r property.
Settings box .
Click on the down-arrow butto n to the right of the
ye llow square in the pa lette.
C lick on the C ustom tab and click on the desired
C lick on the form to see the ye llow list box.
"Form l.vb" and se lect Rename from the
23. In the Solution Explorer wind ow, right click on
conte xt menu.
Type "frmYellow.vb".
selec t Prope rties from the conte xt menu.
Right-click on the form in the Form Designer, and
ow.
C lick on Back Colo r property in the Prope rties wind
of the Setti ngs box, click on the C ustom
Click on the down-arrow butto n in the right part
tab, and click on a ye llow square.
25. Begin a new proje ct.
Duo".
Chan ge the text in the form 's title ba r to "Dyn amic
Answers To Selected Odd-Nu mbered Exercises
• 60

Place two buttons on the form and pos it ion and resize as shown.
Enter "Batman" as the text of the first button , and enter "Robin" as the text of the second
button.
Increase the font size for both buttons to 14.
27. Begin a new project.
C hange the text in the form's title bar to "Fill the Blank".
Place a labe l, a text box, and another label on the form at appropriat e locations.
C hange the Text setting of the first label to "I'm the king of the" and the Tex t setting of
the second labe l to "A Quote by Leona rd o DiCaprio".
29. Begin a new project.
C hange the text in the form's title bar to "Uncle's Advice".
Place five labe ls and three buttons on the form.
C hange the Text setting of each labe l as indicated.
C hange the settings of the buttons' Tex t prop rti es to "1", "2", and "3 ".
Resize and position the labe ls and buttons.
33. 1 35. Each arrow key moves the text box in the indicated direction.
37. Pressing the right and left arrow keys widens and narrows the text boxes, buttons, and list
boxes in the group of se lected contro ls. The up and down arrow key shorten and lengthen
the buttons and list boxes in the group. The arrow keys have no effect on the labels, and
only the left and right arrow keys affect the text boxes.
39. Drag a labe l and a list box onto the form.
C lick on the label.
Hold down the Ctrl key and click on the list box. (You have now selected a group of two
controls.)
ln th Properties window, cl ick on the plus sign (in XP) or the right-poin ting tri angle
(Vista or W indows 7) to the left of the Font property.
C lick on the Size property, change the se tting to 12, and press the Enter key.
(Alternat ive: Replace the last three lines with th e fo llowing steps. )
In the Properties window, se lect the Font prope rty.
C lick on the ellipsis button to the right of the Settings box.
C lick on 12 in the S ize list and click O K.
41. The labe l is po itioned just to the left of the text box, and the midd les of the two contro ls
are aligned.
43. Center refers to the midpoint horizontally, whereas middle refers to the midpo int vert ica
lly.
45. First blue snap line: tops of the two control are aligned
Purple snap line: middles of the two controls are aligned
Second blue snap line: bottoms of the two controls are aligned
47. The setting is cycl ing through th e d ifferent ava ilab le co lors.

EXERCISES 2.3
1. The word "Hello" 3. The word "Hello" on an orange-co lored background
5. The text box vanishes. 7. The word "Hello" in gree n letters
9. The word "Hello" on a go ld background . 11 . Forml .Text should be Me.Text.
13. Red should be replaced with Color. Red.
604 • An swers To Se lected Odd-N um be red Exercises

ut. Text = txtBox . Font. Size is


15. Fon t. S ize is a read -onl y prope rty. The s t a te m e nt txtoutp
r, txtBox .Font.S ize = 20
va lid s ince it is reading th e va lue of t x tBox. Fo nt. S ize . H o w eve
is n ot va lid since it is se tting the va lu e of tx tBox .Fo nt. S ize.

17. lb1Two .Text = "E . T. phone home."

19. txtBox .ForeC olor = Color.R ed


txtBox .Text = "The stuff tha t dreams are made of."

21. txtBox .Enable d =False 23. lblTwo .Visibl e =False

25. btn0utc ome.En abled =True 27. txtBoxT wo.Foc us()

29. The E n te r event occurs whe n a co n tro l ge ts the foc us.

31. Private Sub Labell Click( .. . ) Handle s Labell .Click


lstOutp ut.Item s.Add( "Click ")
End Sub
Double Click
Private Sub Labell _ Double Click( ... ) Handle s Labell.
lstOutp ut . Items .Add ("Doub le Click")
End Sub
a lso ra ised .
Whe n ever the D o ubleC lic k eve nt is ra ised, the C lic k e v e nt is

33. Private Sub btnLef t_ Click( ... ) Handle s btnLef t.Click


txtBox .Text = "Left Justify "
txtBox .TextA lign = Horizo ntalAli gnmen t.Left
End Sub
ck
Private Sub btnCen ter Click( ... ) Handle s btnCen ter.Cli
txtBox .Text = "Cente r"
txtBox .TextA lign = Horizo ntalAli gnment . Center
End Sub
k
Private Sub btnRig ht_ Click( . .. ) Handle s btnRig ht.Clic
txtBox .Text = "Right Justify "
txtBox .TextA lign = Horizo ntalAli gnmen t.Right
End Sub

35. Private Sub btnRed_ Click( ... ) Handle s btnRed .Click


txtBox .BackC olor = Color.R ed
End Sub
Private Sub btnBlu e_ Click( ... ) Handle s btnBlu e.Click
txtBox .BackC olor = Color.B lue
End Sub
k
Priv ate Sub btnWhi te_ Click( ... ) Handle s btnWh ite.Clic
txtBox .ForeC olor = Color.W hite
End Sub
ick
Priv ate Sub btnYell ow_ Click( ... ) Handle s btnYel low.Cl
txtBox .ForeC olor = Color.Y ellow
End Sub

37. Private Sub txtLife _ Enter( ... ) Handle s txtLife .Enter


txtQuo te.Text = "I like life, it's someth ing to do."
End Sub
er
Priva t e Sub txtFutu re_ Enter( ... ) Handle s txtFutu re.Ent
isn't what it used to be."
txtQuo te.Text = "The future
End Sub
r
Private Sub txtTru th_ Enter ( ... ) Handle s txtTru th.Ente
txtQuo te.Text = "Tell the truth and run."
End Sub
Answ ers To Selected O dd-N um bered Exer
ci es • 605

39. Priv ate Sub btnO ne_ Clic k(


.. . ) Han dles btnO ne.C lick
btnO ne.V isib le = Fals e
btnT wo. Visi ble = True
btnT hree .Vis ible = True
btnF our .Vis ible = True
End Sub
Priv ate Sub btnT wo_ Clic k( ...
) Han dles btnT wo. Clic k
btnO ne.V isib le = True
btnT wo. Visi ble = Fals e
btnT hree . Vis ible = True
btnF our .Vis ible = True
End Sub
Priv ate Sub btnT hree _ Clic k( ...
) Han dles btnT hree .Cli ck
btnO ne.V isib le = True
btnT wo. Visi ble = True
btnT hree .Vis ible = Fals e
btnF our . Vis ible = True
End Sub

Priv ate Sub btnF our_ Clic k( . ..


) Han dles btnF our. Clic k
btnO ne.V isib le = True
btnT wo . Vis ible = True
btnT hree .Vis ible = True
btnF our . Vis ible = Fals e
End Sub

41. Priv ate Sub btnV anis h_ Clic


k( ... ) Han dles btnV anis h.C lick
lblF ace .Vis ible = Fals e
End Sub
Priv ate Sub btnR eapp ear_ Clic
k( ... ) Han dles btnR eap pea r.Cl
lblF ace .Vis ible = True ick
End Sub

43. Priv ate Sub btnA ny_ Clic k(


... ) Han dles btnO ne . Clic k , btnT
txtO utpu t.Te xt = "You just clic wo. Clic k
ked on a butt on."
End Sub

CHA PTE R 3
EXER CISES 3.1

1. 12 3. . 125 5. 8 7. 2 9. 1 11. N o t va lid


13. Valid 15 . N ot va lid 17. 10 19. 16 21. 9
23. Priv ate Sub btnC omp ute_ Clic
k( ... ) Han dles btnC omp ute. Clic
lst0 utpu t.Ite ms. Add ((7 * 8) k
+ 5)
End Sub

25. Priv ate Sub btnC omp ute_ Clic


k( ... ) Han dles btnC omp ute. Clic
lstO utpu t . Item s.Ad d(O. OSS * k
20)
End Sub

27. Priv ate Sub btnC omp ute_ Clic


k( ... ) Han dles btnC omp ute. Clic
ls t 0utp ut . Item s . Add (l7 * (3 k
+ 162 ))
End Sub
Exercises
606 • Ans wers To Se lected Odd -N um bered

X y
29
( ... ) Han dles btn Eva luat e.C lick
Priv ate Sub btnE valu a t e Clic k 0 0
Dim x, y As Dou ble 2 0
X = 2 2 6
y = 3 * X 11 6
X = y + 5 11 6
lstR esu lts. Item s.C lear () 11 6
lstR esu lts. Item s.A dd( x + 4) 11 7
y = y + 1
End Sub

35. 1 37 . 2
31. 6 33. 1
64 15
8
9

39. The thir d line should read c = a


+ b
ass ignm ent stat e-
ld not con tain a co mm a. The seco nd
41. The first as ignm ent statemen t shou
.
men t should not con tain a doll ar sign
43. 9W is not a valid variable nam e.
45. Dim qua ntit y As Inte ger
= 12
55. 0 57 . 6
51. 3 .128 53. -3
47. 10 49. 6
Clic k
k ( ... ) Han dles btnC omp ute.
59. Priv ate Sub btnC omp ute_ Clic ble
As Dou
Dim reve nue , cos ts, pro fit
reve nue = 9845 6
cos ts = 4500 0
pro fit = reve nue - cos ts
lstO u tpu t.Ite ms. Add (pro fit)
End Sub
ute. Clic k
Clic k( .. . ) Han dles btnC omp
61. Priv ate Sub btnC omp ute_ Dou ble
mark dow n As
Dim pric e, disc oun tPe rcen t,
pric e = 19.9 5
disc oun tPe rcen t = 30
mark dow n = (dis cou ntP erce nt
I 100) * pric e
pric e = pric e - mark dow n
oun d(pr ice, 2))
lstO utp ut . Item s . Add (Ma th.R
End Sub
ute. Clic k
Clic k( ... ) Han dles btnC omp
63. Pr iva te Sub btnC omp ute
Dim bala nce As Dou ble
bala nce = 100
bal ance += 0.05 * bala nce
bala nce += 0.05 * bala nce
bala nce += 0.05 * bala nce
nd(b alan ce, 2))
lstO utp ut.I tem s . Add (Ma th . Rou
End Sub
ute . Clic k
Clic k( .. . ) Han dles btnC omp
65. Priv ate Sub btnC omp ute_
Dim bala nce As Dou ble
bala nce = 100
10)
bala nce = bala nce * (1.0 5
A

rns. Add (Ma th.R oun d(b alan ce, 2))


lstO utpu t.Ite
End Sub
Answers To Se lected O dd -N umbered Exercises • 607

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


Dim acres, yieldPerAcre, corn As Double
acres = 30
y ieldPerAcre = 18
corn = y ieldPerAcre * acres
l s tOutput.Items . Add(corn)
End Sub

69. Priv ate Sub btnCompute Click ( .. . ) Handles btnCompute.Click


Dim distance , elapsedTime, averageSpeed As Double
di s tanc e = 2 3 3
elapsedTime = 7 - 2
a v erageSpeed = distance I elapsedTime
l s tOutput.Items.Add(averageSpeed)
End Sub

71. Pri v ate Sub btnCompute_ Click( . . . ) Hand les btnCompute.Click


Dim waterPe r PersonPerDay , people, days, waterUsed As Double
water PerPersonPerDay = 1600
peop l e = 31 5 000000
days = 365
waterUsed = waterPerPersonPerDay * people * days
lstOu t put . Items.Add (waterUsed)
End Sub

EXERCISES 3.2
1. Visual Basic 3. Ernie 5. flute 7. 123 9. Your age is 21.
11. A ROSE I S A ROSE IS A ROSE 13. 5. 5 15. goodbye 17. WALLAWALLA
19. ABC 21. 12 23. 8 ( 0 through 7) 25. True
2 MUNICIPALITY
4 city
55 mph 6
STU

27. The variable phoneNumber should be declared as type String, not Double.
29. End is a keyword and cannot be used as a variable name.

31. The Ind exOf method can not be applied to a number, only a string.
33. Private Sub btnDisplay_ Clic k ( . . . ) Handles btnDisplay.Click
Dim firstName, middleName, lastName As Str ing
Di m y earOfBirth As Integer
firstName = "Thomas"
middleName = "Alv a"
lastName = "Edison"
y earOfBirth = 184 7
txtOutput . Text firstName & " " & middleName & " " & lastName &
", " & yearOfBirth
End Sub

35. Pri v at e Sub btnDisplay_ Click( . .. ) Handles btnDisplay.Click


Dim publisher As String
publ i sher= "Prenti c e Hall , Inc . "
t x tOutput . Text = "(c) " & publisher
End Sub
608 • Answe rs To Selected O dd-N um bered Exe rcises

m
37. Dim str As String 'Place in the Decla ration s sectio n of the progra

mpute .Click
39. Privat e Sub btnCom pute_ Click( ... ) Handle s btnCo
Dim distan ce As Doub l e
distan ce= CDbl(t xtNum Sec.Te xt) I 5
distan ce = Math.R ound(d istance , 2)
" & distan ce & "mile s."
txtOu tput.T ext = "The distan ce of the storm is
End Sub

mpute .Click
41. Privat e Sub btnCom pute Click( ... ) Handle s btnCo
Dim cyclin g, runnin g , swimm ing, pounds As Double
cyclin g= CDbl( txtCyc le.Tex t)
runnin g = CDbl(t xtRun . Text)
swimm ing= CDbl(t xtSwim .Text)
pounds = (200 * cyclin g + 475 * runnin g + 275
* swimm ing) I 3500
pounds = Math.R ound(p ounds, 1)
txtWtL oss.Te xt =poun ds & "poun ds were lost . "
End Sub

mpute .Click
43. Privat e Sub btnCom pute_ Click( ... ) Handle s btnCo
Dim revenu e , expens es, income As Double
revenu e = CDbl( txtRev enue.T ext)
expen ses= CDbl( txtExp enses. Text)
income = revenu e - expens es
txtNet incom e.Text = CStr(in come)
End Sub

a~ 3.2 Exercise 43 c.. o 3.2 Exercise 45 l = l@] ~ d


Revenue : 5 Amount of bill :

Expenses: 15
Percentage t ip :

Compute Net Income


Compute Tip

Net Income : Tip : 3

mpute .Click
45. Privat e Sub btnCom pute_ Click( ... ) Handle s btnCo
Dim amoun t, percen tage, tip As Double
amoun t = CDbl(t xtAmo unt.Te xt)
percen tage = CDbl( txtPer centag e.Text )
tip = amoun t * (perce ntage I 100)
txtTip .Text = CStr(M ath . Round (tip, 2))
End Sub

47. Dim numbe r As Intege r = 100 'in Decla ration s sectio n


'Note: the Text prope rty of txtOut put was set to 100 at design time

ssMe. Click
Privat e Sub btnPre ssMe Click( ... ) Handle s btnPre
numbe r = numbe r - 1 'decre ase numbe r by 1
txtOu tput.T ext = CStr(n umber )
End Sub
Answ e rs To Se lected Odd-N umbered Exerc ises
• 609

a~ 3.2 Exe rcise 47

Press Me

100

49. Priva te Sub btnM odify Sente nce_ Click


( ... ) Hand les btnM odify Sente nce.C lick
Dim sente nc e, oldW ord , newW ord As Strin
g
Dim posit ion As Integ er
sente nce = txtSe ntenc e . Text
oldW ord = txtOr igina lWor d . Text
newW ord = txtRe place mentW ord.T ext
posit ion = sente nce.I ndexO f(old Word )
txtOu tput . Text sente nce.S ubstr ing(O , posit ion) & newW
ord &
sente nc e . Subs tring (posi tion + oldW ord .
Lengt h)
End Sub

a_. 3.2 Exercise 49 l = I @) :... ,;z I

Sentence : What you donl know wonl hurt you .

lN ord in Sentence : know

Replacement word : owe

[ Modify Sentence ]
What you donl owe wonl hurt you . -

51. Pr i va t e Sub btnD ispla y _ Click ( .. . ) Hand


les btnD ispla y . Click
Dim speed , di s tance As Doub le
dista nc e = CDbl ( txtDi stanc eSkid ded.T ext)
speed = Math . Sqrt (24 * dista nce)
speed = Math . Round ( speed , 2)
t x tEst i mated Speed . Text = speed & " mph"
End Sub

a';} 3.2 Exerc.is.e 51 -[ = 1@) 1~.-l

Distance skidded : 54

Display Estimat ed Speed

Estimated speed : J6 mph

53. Dim sum As Doub le 'sum of the score s enter ed


Dim num As Integ e r 'numb er of score s enter ed
610 • Answers To Selected Odd-Numbered Exercises

Hand les btnR ecor d.Cl ick


Priv ate Sub btnR ecor d_ Clic k( ... )
num += 1
sum+ = CDb l(txt Scor e.Te xt)
txtS core .Cle ar()
txtS core .Foc us()
End Sub

) Hand les btnC alcu late. Clic k


Priv ate Sub btnC alcu late_ Clic k( ...
txtA vera ge.T ext = CStr (sum I num)
End Sub
les btnC omp ute.C lick
55. Priv ate Sub btnC ompu te_ Clic k( ... ) Hand
Dim numl , num2 , sum As Doub le
numl = CDb l(txt First Nurn .Tex t)
nurn2 = CDb l(txtS econ dNum .Tex t)
sum = numl + nurn2
txtSu rn.T ext = CStr (surn )
End Sub

ged( ... ) Hand les


Priv ate Sub txtE ither Num_ Text Chan
txtFi rstN urn.T extC hang ed, txtSe cond Nurn .Tex tCha nged
txtSu rn. Clea r ()
End Sub

EXERCISES 3.3
5. 0.0 7. -0.6 7 9. 12,3 46.0 00 11. 12
1. 1,23 5 3. 1,23 4.0
15. ($0.2 3) 17. $0.8 0 19. 7.50 % 21. 100.0 0%
13. $12, 346

23. 66.67 % 25. Pay to Fran ce $27, 267, 622. 00


s.
25+ year s old are coll ege grad uate
27. 25.6 % of the U.S. popu latio n
1012 3120 10
29. The like liho od of Head s is 50 % 31.
33. Thur sday , Nove mber 25, 2010
35. 1012 1201 1 37. 4151 2013 39. 29
43. Hell o John Jone s 45. $106 . 00
41. You migh t win 360 doll ars.
oint bo ld Cour ier N ew font in blu e lette rs 2
47. Prints the words H ello W orld using a 10-p
s from the top of the page.
inch es from the left ide of the page and 2 inche
49. The state ment n += 1 is not va lid ince
the value of a cons ta nt cann ot be chan ged.
the right -hand ide to type Do uble.
51. The secon d line should use CDb l to conv ert
fore cann ot be ass igned to a num eric variab le.
53. Form atNu mber (123 456) is a strin g and there
ageB ox.
55. You mu st inser t . Show , after the word Mess
57. 000 59. LLLOOO 61 . 0-00 -000 000- &
.",
the prob lem. Then writ e the code
63. Mess ageB ox.S how( "Firs t solv e
"Goo d Advi ce")
... ) Hand les btnD ispla y.Cl ick
65. Priv ate Sub btnD ispla y_ Clic k(
As Doub le
Dim begO fYea rCos t , endO fYea rCos t
Dim perc enti ncre ase As Doub le
begO fYea rCos t = 200
nter cost at the end of the year :"))
endO fYea rCos t = CDb l(Inp utBo x("E t
- begO fYea rCos t) I begO fYea rCos
perc enti ncre ase = (end OfYe arCo st is " &
"The incr ease in cost for the year
txtO utpu t.Te xt " "
Forr natP erce nt(p erce ntinc reas e) &
End Sub
Answ ers To Selected Odd-N umb ered Exer
cises • 611

67. Priv ate Sub btnD ispl ay_ Clic


k( ... ) Han dles btnD ispl ay.C
Dim first Day OfY r, first Day OfN lick
extY r As Date
Dim num Days As Dou ble
first Day OfY r = CDa te(" l/1/ "
& mtb Yea r.Te xt)
first Day OfN extY r = first Day OfY
r.Ad dYe ars( 1)
num Days = Dat eDi ff(D atei nter
val. Day , first Day OfY r, first Day
txtN umD ays. Tex t = CStr (num Day OfN extY r)
s)
End Sub

11 ._~ 3.3 Ex:erciS<e 67

Year: Date: 12/ 1

Display Number of Da;rs Determine Day of Neek

Number of da;'S : 365 Day of week : Fridcrl

69. Priv ate Sub Dete rmin e_ Clic


k( ... ) Han dles btnD eter min e.Cl
Dim dt As Date = CDa te(m tbD ick
ate.T ext)
Dim full Dat e As Stri ng = Form
atDa teTi me( dt, Date Form at.L ongD
Dim pos itio n As Inte ger = fu11 ate)
Dat e.In dex 0f(" ,")
Dim dayO fWe ek As Stri ng = full
Dat e.Su bstr ing( O, pos itio n)
txtD ayO fWe ek.T ext = dayO fWe ek
End Sub

71. Priv ate Sub Dete rmin e Clic


k( ... ) Han dles btnD eter min e.Cl
Dim mon th, yr As Inte ger ick
'mon th give n as 1 thro ugh 12
Dim dt, dt2 As Date
Dim num Days As Dou ble
mon th= Cin t(tx tMo nth . Tex t)
yr = Cin t(mt bYe ar.T ext)
dt = CDa te(m onth & "/1/ " & yr)
dt2 = dt.A ddM onth s(1)
num Days = Dat eDi ff(D atei nter
val. Day , dt, dt2)
txtN umD ays. Tex t = CStr (num Day
s)
End Sub

Month (1 - 12): 2

Year: 2: 11

Determine Number of Da)'S

Number of days : 8

73. Priv ate Sub txtP hone Num ber_


Ent er( ... ) Han dles txtP hon eNu
Mes sage Box .Sho w("B e sure to mbe r.En ter
incl ude the area cod e!", "Rem
End Sub inde r")

75. Priv ate Sub btnC omp ute_ Clic


k( . . . ) Han dles btnC omp ute. Clic
Dim prin cipa l, intR ate, yrs, k
amt As Dou ble
Exe rcises
612 • An swer s To Se lected Odd -N um bered

lstO utp ut.I tem s.C lear ()


.Te xt)
pri nci pal = CD bl(t xtP rinc ipal
ate = CD bl(t xtin tRa te . Tex t)
intR
yrs = 10
ate) A yrs
amt = prin cip al * (1 + intR ) & " is")
Add ("W hen " & For mat Cur renc y(p rinc ipal
lstO utpu t.Ite ms. mat Per cen t(in tRa te))
d at" & For
lstO utp ut . Item s.A dd( "inv este
& yrs & " yea rs, the ")
lstO utp ut . Item s.A dd( "for " & ".")
e is " & Form atCu rren cy(a mt)
lstO utp ut.I tem s.A dd( "ba lanc
End Sub

e ind er

D 3.3 Exe rcis.e 73 = Be su re to inc lude the area code!

Name : Gabriel
OK
Phon e number:

= 100 'num ber of poi nts in an inch


77. Con st ONE INCH As Inte ger 'one -qu arte r of an inch
st LINE HEIGHT As Inte ger = 20
Con

... ) Han dles btn Prin t.C1 ick


Priv ate Sub btn Prin t_ Clic k(
Prin tDo cum ent1 .Pri nt()
End Sub
tDo cum ent1 .Pri ntP age
_ Prin tPag e( ... ) Han dles Prin
Priv ate Sub Prin tDo cum ent1
ics
Dim gr As Gra phic s = e.G raph gin
ONE INCH 'use one inch bey ond lef t mar
Dim x1 As Inte ger 'off set for seco nd colu mn
5 * ONE_ INCH)
Dim x2 As Inte ger = Cin t(1. 'off set for thir d colu mn
25 * ONE_ INCH)
Dim x3 As Inte ger = Cin t(2. one inch top mar gin
'use
Dim y As Inte ger = ONE INCH rlin e)
ier New ", 10, Fon tSty le.U nde
Di m fon t1 As New Fon t("C our Fon tSty le.R egu lar)
ier New ", 10,
Di m font 2 As New Fon t("C our
ring (" % of" , fon t2, Bru she s.Bl ack , x3, y)
g r .Dra wSt
y += LINE _ HEIGHT
Bru she s.Bl ack , x1, y)
gr.D raw Stri ng( "Ra nk" , fon t1,
t1, Bru she s.Bl ack , x2, y)
gr . Dra wSt ring ("C oun try" , fon y)
fon t1, Bru she s.Bl ack , x3,
gr . Draw Strin g("W W Use rs",
y += LINE _ HEIGHT
Bru shes .B1 a ck, x1, y)
gr.D raw Stri ng( "1" , fon t2,
Bru she s.Bl ack , x2, y)
gr.D raw Stri ng(" USA ", fon t2, lack , x3, y)
t(0. 16, 1), fon t2, Bru she s.B
g r.D raw Stri ng( For mat Per cen
y += LINE _ HEIGHT
Bru shes .B1 ack , x1, y)
gr . Dra wSt ring ("2" , fon t2,
t2, Bru shes .B1 ack , x2, y)
gr . Dra wSt ring ("C hina " , fon .B1 ack , x3, y)
t(0. 119 , 1), fon t2, Bru shes
gr . Dra wSt ring (Fo rma tPer cen
y += LINE _ HEIGHT
Bru she s.Bl ack , x1, y)
gr . Dra wSt ring ("3" , fon t2,
t2, Bru she s.Bl ack , x2, y)
gr . Dra wSt ring ("Ja pan ", fon s.B lack , x3, y)
cen t(0 . 065 , 1), fon t2, Bru she
gr.D raw Stri ng( For mat Per
End Sub
ck
k( ... ) Han dles btn Pre view .Cli
Priv ate Sub btnP revi ew_ Clic
= Prin tDo cum ent1
Prin tPre view Dia log1 .Do cum ent
wD ialo g()
Prin tPre view Dia log1 .Sho
End Sub
A nswers To Selected Odd-N umbered Exe rcises
• 613

CHAP TER 4
EXERCISES 4.1
1. hi 3. The letter before G is F

5. "We're all in this alone . " - Lily Tomlin


7. True 9. Tru e 11. True 13. T r u e 15. Fa lse 17. Fa lse 19. Tru e 21. T ru e
23. Fa lse 25. F a lse 27. Fa lse 29 . Tr u e 31. Equiva le nt 33. N o t Eq u iva le nt
35. Equiva lent 37. Not Equiva le nt 39. Eq ui va le nt 41. a <= b

43. (a >= b) Or (c = d ) 45. (a = "") Or (a >= b) Or (a.Len gth >= 5)

[In Exercis es 46 throug h 49, exec ute a s t a t e m e nt o f the fo rm txtout put. Text = Boolea n
expres s ion.]

47 . True 49. Fa lse 51. F a lse 53. T r u e 55. Tru e 57. Fa lse 59. T ru e

EXERCISES 4.2
1. Less than ten. 3. tomorr ow is ano t her day. 5. 10
7. To be, or not to be . 9. Hi 11. You are old enough to vote in 7 days .
13. Syntax e rror. T h ird line sh o uld be If ( (1 < num) And (num < 3)) Then
15. Syntax e rro r. Fo urth line sh o u ld be If ( (major = "Busin ess") Or (major "Comp uter
Scienc e" ) ) Then

17. a = 5

19. messag e = "Is Alaska bigger than Texas and


Califo rnia combin ed?"
answer = InputB ox(me ssage)
If (answ er.Sub string (O, 1) .ToUpp er = "Y") Then
txtOu tput.T ext "Corre ct"
Else
t x t Output .Tex t 11
Wrong"
End If

21. Priv ate Sub btnCom pute_ Click( .. . ) Handle s


btnCom pute . Click
Di m cost , t i p As Double
cost= CDbl ( InputB ox("En ter cost of meal:" ) )
t i p = cos t * 0 . 1 5
If tip < 1 Then
tip = 1
End If
t xtOu tput . Text " Leav e " & Forma tCurre ncy(ti p) & " for the tip
."
End Sub

Compute Tip Compute Cost of 1/llidgets

Leave S1. for the tip. The cost is 't1.25.


614 • Answe rs To Se lected O dd-Nu m be red Exercises

es btnCo mpute .Click


23. Priva te Sub btnCo mpute _ Click ( .. . ) Handl
Dim num, cost As Doubl e
num = CDbl (Input Box (" Numbe r of widge ts:"))
If num < 100 Then
cost 0.25 * num '25 cents each
Else
cost 0. 2 * num '20 cents each
End If
ncy (cost) &
txtOu tput .Text = "The cost is " & Forma tCurre
End Sub

Handl es btnAs kQue stion. Click


25. Priva te Sub btnAsk Que st ion_ Click ( ... )
Dim name As Strin g
d McDo nald?" )) .ToUp per
name = (Input Box(" Who was the first Ronal
I f name = "WILLARD SCOTT" Then
txtOu tput.T ext "Corr ect."
Els e
txtOu tput.T ext "Nice try."
End If
End Sub

I = I @] L ..i"i. .I
a... 4.2 Exerci_ e 25 l = I @] ~~ •J 11_. 4.2 Exercise 27

Ask Question Comput e Average of Two Highest Scores

Average : &5
Correct .

es btnCo mpute .Click


27. Priva te Sub btnCo mpute Click ( ... ) Handl
Dim sl, s2, s3 As Doubl e '3 score s
Dim a vg As Doubl e 'avera ge of the two highe st score s
score s."))
sl CDbl( InputB ox ( "Ente r the first of the three
r the secon d of the three score s."))
s2 = CDbl( InputB ox ( "Ente
InputB ox("E nter the third of the three score s."))
s3 = CDbl(
If (sl <= s2) And (sl <= s3) Then 'sl is small est numbe r
avg = (s2 + s3) I 2
Elsei f (s2 <= sl) And (s2 <= s3) Then 's2 is small est numbe r
avg (sl + s3) I 2
Else 's3 is small est numbe r
avg (sl + s2) I 2
End If
txtAv erage .Text CStr(a vg)
End Sub
es btnCo mpute .Click
29. Pr ivate Sub btnCo mpute _ Click ( ... ) Handl
t, chang e As Doubl e
Dim weigh t, cost, amoun
weigh t= CDbl( txtWe ight.T ext)
amoun t = CDbl( txtAm ount.T ext)
cost =wei ght * 1.7
If (amou nt >= cost) Then
chang e = amoun t - cost
& "."
txtOu tput.T ext "Your chang e is " & Forma tCurre ncy (chang e)
Else
"I need " & Forma tCurre ncy(c ost amoun t) & "mor e ."
txtOu tput.T ext
End If
End Sub
Answers To Selec ted Odd -N umbe red Exerc
ises • 615

[I .2 Exercise 29 •2 Exercise 31

Weig ht : li

Amount : Hours worke d : 2

Compute Chan ge Compute Gross Pay

Your chang e is S9.&0 . Gross pay : ~!i6EI. ~

31 . Priv ate Sub btnC omp ute_ Clic


k( ... ) Han dles btnC omp ute.C lick
Dim wage , hou rs, gros sPay As Dou
ble
wag e= CDb l(txt Hou rlyW age. Text
) 'Hou rly pay
hou rs= CDb l(txt Hou rsW orke d . Text
) 'Hou rs work ed
If hour s <= 40 Then
gros s Pay wage * hour s
Else
gros sPay (wag e* 40) + (1.5 *wa ge* (ho
urs - 40))
End If
txtG ross Pay . Text Form atCu rren cy(g ross Pay)
End Sub

33. Dim num Line s As Inte ger = 0


' In Dec lara tion s sect ion of Code
' num Line s tell s the num ber of Edit or
line s that have been disp laye d.
Priv ate Sub btnB ogar t_ Cli c k ( ...
) Han dles btnB ogar t.Cl ick
If num Line s = 0 The n
ls t Out put. Item s . Add ( "I came to
Casa blan ca fo r the wate rs . ")
numL ines += 1
Else if num Line s = 2 Then
lstO utpu t.Ite ms.A dd(" I was misi
nfor med .")
numL i nes += 1
End If
End Sub

Priv ate Sub btnR aine s_ Clic k( .


.. ) Han dles btnR aine s. Clic k
If num Line s = 1 Then
lstO utpu t.Ite ms.A dd ( "But we'r e
in the midd le of the dese rt.")
num Line s += 1
End If
End Sub

a ~
4.2 Exercise 33 l = I @) l...tJ "l!J
( Bogart
I[ Raines
l
I came to Casablanca for the waters .
But we're in the middle of the desert .
I was misinformed .
-
d Exe rcises
616 • Ans wers To Selected Odd -Num bere

35. Dim num Gue sses As Inte ger = 0


.C lick
k( ... ) Han dles btn Eva luat e
Priv ate Sub btnE valu ate Clic umb erO fGu esse s
ty of txtN
'Ass ume tha t the Tex t pro per
to 0 in the Form Des igne r
'was set
num Gue sses += 1
CSt r(nu mG uess es)
txtN umb erO fGu esse s.Te xt =
Dim msg As Stri ng
n
exO f("C OOL IDG E") <> -1 The
If txtA nsw er.T ext. ToU pper .Ind on July 4, 187 2.",
lidg e was born
Mes sage Box .Sho w(" Calv in Coo
"Co rrec t")
Me. Clo se()
Els eif Cin t(nu mG uess es) =
10 The n
= "Ca lvin Coo lidg e was bor n on July 4, 187 2."
msg
"Yo u've Run Out of Gue sses ")
Mes sage Box .Sho w(m sg,
Me. Clo se ()
Else
If Cin t(nu mG uess es) = 3 The
n
don 't say any thin g," &
msg = "He onc e said , 'If you
to rep eat it.' "
"yo u won 't be call ed upo n
Els eif Cint (num Gue s ses) = 7 The n
"His nick nam e was 'Sil ent Cal .'"
msg
Else
msg = "So rry! "
End If
rect ")
Mes sage Box .Sho w(m sg, "In cor
End If
txtA nsw er.C lear ()
txtA nsw er.F ocu s()
End Sub
ay . Clic k
Clic k( ... ) Han dles btnD ispl
37. Priv ate Sub btnD ispl ay_
n
If lblL ang uag e.V isib le The
lblL ang uag e.V isib le = Fal se
e of Lan guag e"
btn Dis play .Te xt = "Sho w Nam
Else
lblL ang uag e.V isib le = Tru e
e of Lan guag e"
btn Dis play .Te xt = "Hid e Nam
End If
End Sub

a_. 4.2 Exe rcise 39 l = I @] 1...-.gj "j


Year : 2[)[)B

Detennine if Year is a Leap Year

Leap year? YES

min e . Clic k
Clic k( ... ) Han dles lblD eter
39. Priv ate Sub btnC omp ute_
Dim day As Stri ng
Dim day l, day2 As Dat e
Dim num Day s As Dou ble
t
day = "1/1 /" & txtY ear. Tex
day l = CDa te(d ay)
day2 = day l.Ad dYe ars( l)
val. Day , day l, day2 )
num Day s = Dat eDi ff(D atei nter
Answ ers To Select ed Odd -N umbered Exerc ises
• 617

If numD ays = 366 Then


txtLe apYe ar.Te xt "YES"
Else
txtLe apYe ar.Te xt "NO"
End If
End Sub
41. Priva te Sub Deter mine_ Click ( ... ) Hand
les btnD eterm ine.C l i ck
Dim dt, dt2 As Date
Dim appro ximat eAge As Doub le
dt = CDat e(mtb Date. Text)
appro ximat eAge = Date Diff( Date inter val.Y
ear, dt, Today )
dt2 = dt.Ad dYea rs(Ci nt(ap proxi mateA ge))
If Today < dt2 Then
txtAg e.Tex t CStr( appro ximat eAge - 1)
Else
txtAg e.Tex t CStr( appro ximat eAge )
End If
End Sub

ll ... 4.2 Exercise 41 l = I@] I C¥:1 I

Date of birth : 1 23/ 1989

[ Detenn ine AI;Je ) Detennine Honors

AI;Je : 20 You graduated magna cum laude .

43. Priva te Sub btnD eterm ine_ Click ( ...


) Hand l es btnDe termi ne .C lick
Dim gpa As Doub le = CDbl (txtG PA. Text)
Dim hono rs As Strin g =
If gpa >= 3.9 Then
hono rs= "sum ma cum laude . "
End I f
If (3.6 <= gpa) And (gpa < 3.9) Then
hono rs= "mag na cum laude ."
End If
If (3.3 <= gpa) And (gpa < 3.6) Then
hono rs " cum laude ."
End If
If (2 <= gpa) And (gpa < 3.3) Then
hono rs= "."
End If
txtOu tput. Text "You gradu ated" & hono rs
End Sub

EXERCISES 4.3
1. The price is $3.75
3. Meso zoic Era
The price is $3.75 Paleo zoic Era
?
5. The equa tion has no real solut ions.
The equa tion has two solut ions.
The equa tion has exac tly one solut ion.

7. Should have a Case clause befo re the 4th line.


618 • A nswer s To Se lected O dd-N um bered Exe rci es

"
9. Case nom = "Bob" sh o uld be Case "Bob
"PEACH" .
11. Logic e rror: >= "Peac h" sh o uld b e >=
be " ORANGE" To "PEA CH".
Synta x e rro r: " ORANGE TO PEACH" sh o uld

13. Va lid 15. Inva lid 17. V a l id

19. Se l ect Case a


Case 1
txtO utpu t.Tex t "o n e 11

Case Is > 5
txtOu tpu t.Tex t "t wo "
En d Sele ct

21. Se lect Cas e a


Case 2
txtOu tpu t .Tex t "y es"
Case Is < 5
txtOu tpu t . Text "no"
End Sele ct
) Hand les btnD escri be .C l i ck
23. Priv ate Sub btnD escri be Cl i ck ( ...
Dim p e r c ent As Doub l e
e of cloud cove r:" ))
p ercen t= CDbl (Inpu tBox ( "Perc entag
Sele ct Case perc ent
Case 0 To 30
txtOu tput . Text "Cle ar"
Case 31 To 70
tx t Ou tput. Text " Pa r tly cloud y"
Case 7 1 To 99
tx t Outp ut . Text " Cloud y"
Ca s e 100
tx t Outp ut.Te xt "Ov erca st"
Ca s e Els e
t xtOu tput. Text "Perc en t age must be betw een 0 and 100."
End Se l ec t
End Sub

a:. 4.3 Exercise 25 l = I @) lc . ~. _I

Select one of the shapes below . Z

4.3 Exercis.e 23 l =·I @) ~~ J.


1. Orcle 2. Parallelogram .3. Kite
................ ... """"]
Descri be Sky Conditions Compute the f!.rea of the Shape
............... .................!'
I.....................................................
Partly cloudy Area : 30

) Hand les btnCo mpu t e .C lic k


25. Priva te Sub btnCo mpu t e _ Cl i ck( ...
Dim shap eNum As In t eger
Doub le
Dim radi us, leng th, he i ght , widt h As
and its dime nsion s
'Inpu t c hoice of shape
2 . Para llelo gram 3. Kite
'1 . Circ le
'Mask is 0
shap eNum = Cint (mtb Sele ction .Tex t)
Sele ct Case shape Num
Ca se 1
s of the circ le : " ) )
radi us= CDbl (Inpu t Box( "Inpu t the radiu
s A 2)
txtA rea . Text = CSt r (3 . 14159 3 * radiu
Answers To Selected Odd -N umbered Exe rcises • 6 19

Case 2
length= CDbl(InputBox("Input the length of the parallelogram: "))
height= CDbl(InputBox("Input the height of the parallelogram: "))
txtArea.Text = CStr(length * height)
Case 3
length= CDbl(InputBox("Input the length of the kite: "))
width= CDbl(InputBox("Input the width of the kite: "))
txtArea.Text = CStr((length *width) I 2)
Case Else
MessageBox.Show("Your choice is not valid.", "Try Again.")
mtbSelection.Clear()
End Select
mtbSelection.Focus()
End Sub

27 . Private Sub btnAssign_ Click( .. . ) Handles btnAssign.Click


Dim score As Integer, letterGrade As String
score= Cint(InputBox("What is the score?"))
Select Case score
Case 90 To 100
letterGrade "A"
Case 80 To 89
letterGrade "B"
Case 70 To 79
letterGrade "C"
Case 60 To 69
letterGrade "D"
Case 0 To 59
letterGrade "F"
Case Else
letterGrade "Invalid"
End Select
txtOutput . Text = "The letter grade is " & letterGrade & " "
End Sub

Assign Letter Grade Detennine Reward

The letter grade is B. The amount given as reward is

29. Private Sub btnDescribe_ Click( . . . ) Handles btnDetermine.Click


Dim amountRecovered, payment As Double
amountRecovered = CDbl(InputBox("How much was recovered?"))
Select Case amountRecovered
Case Is <= 75000
payment = 0.1 * amountRecovered
Case Is <= 100000
payment = 7500 + 0.05 * (amountRecovered 75000)
Case Is > 100000
payment = 8750 + 0.01 * (amountRecovered 100000)
If payment > 50000 Then
payment = 50000
End If
End Select
620 • Answe rs To Se lected Odd-N um bered Exe rci es

txtOu tput.T ext "The amoun t given as reward is " &


Forma tCurre ncy(pa yment) & "."
End Sub
splay. Click
31. Privat e Sub btnDis play_ Click( ... ) Handle s btnDi
Dim pres, state, trivia , whichB ush As String
pres = txtLas tName .Text
Se lect Case pres.T oUppe r
Ca se "CARTER"
s tate = "Georg ia"
" &
trivia = "The only soft drink served in the Carter
"White House was Coca-C ola."
Case "REAGAN"
state = "Calif ornia"
de."
trivia = "His secret servic e code name was Rawhi
Case "BUSH"
state = "Texas "
HW or W?")
whichB ush = InputB ox("Ar e his middle initia ls
Select Case whichB ush.To Upper
Case "HW"
" &
trivia "He celebr ated his 85th birthd ay by parach uting
"out of an airpla ne."
Case "W"
t rivia "He once owned the Texas Range rs baseb all team."
End Select
Case "CLINTON"
state = "Arkan sas"
Elvis Presle y . "
trivia = "In colleg e he did a good imitat ion of
Case "OBAMA"
state = "Illin ois"
ent."
trivia = "He was the eighth left-h anded presid
Case Else
state = ""
trivia = ""
End Select
If state <> "" Then
lstOut put.Ite ms.Cl ear()
&
lstOu tput.I tems.A dd ( "Pres ident" & pres & "'s"
" home state was " & state & ".")
lstOut put.Ite ms.Ad d ( trivia )
End If
End Sub

a 4.3 Exercise 31 l = I @J j...,.tJ .1

Last name of one of the last six presidents : Reagan

Display lnfonnation

President Reagan s home state was Califomia .


His secret service code name was Rawhide .

EXERCISES 4.4
Group Box 1.
1. The word "Income" becomes the caption embedded in the top of
3. The CheckB oxl check box becomes (or remain s) unchecked.
Answers To Se lected O dd-N umbered Exercises • 621

5. T he rad io button becomes (or remains) unselected.

7. T he rad io button's caption beco mes "Clear A ll".

9. RadioButtonl.Text = "Yes" 11. CheckBoxl.Checked True

13. RadioButton2 is on and RadioButtonl is off. 15. Yes

17. Private Sub CheckedChanged( ... ) Handles


radDeluxe.CheckedChanged , radSuper.CheckedChanged,
chkUpgradedVideo.Checked Changed, chkModem.CheckedChanged,
chkMemory.CheckedChanged
If radDeluxe . Checked Or radSuper.Checked Then
Dim cost As Double = 0
'Add amounts to the cost based upon selections.
If radDeluxe.Checked Then
cost += 1000
Else 'Super model
cost += 1500
End If
If chkUpgradedVideo.Checked Then
cost += 200
End If
If chkModem.Checked Then
cost += 30
End If
If chkMemory . Checked Then
cost += 120
End If
txtTotalCost.Text = FormatCurrency(cost)
Else
MessageBox . Show("You must first select a model!")
End If
End Sub

19. Private Sub btnVote_ Click( . .. ) Handles btnVote.Click


If radCandidatel.Checked Then
txtVote . Text = "You voted for Kennedy."
Elseif radCandidate 2 .Checked Then
txtVote . Text "You voted for Nixon."
Else
txtVote.Text "You voted for neither . "
End If
End Sub

Private Sub btnClear_ Click( .. . ) Handles btnClear.Click


radCandidatel.Checked False
radCandidate2.Checked = False
End Sub

21. Priv ate Sub btnRecord_ Click( ... ) Handles btnRecord.Click


Dim majorSelected As Boolean
Dim yearSelected As Boolean
If lstMajors.Text = "" Then
majorSelected False
Else
majorSelected True
End If
622 • Answe rs To Selected Odd -Num bered Exe rcises

ior.Ch ecked Or
If (radFr osh.Ch ecked Or radSop h.Chec ked Or radJun
radSen ior.Ch ecked) Then
yearS electe d True
Else
yearS electe d False
End If
If major Select ed And yearS electe d Then
Messa geBox .Show ("Infor mation Proces sed")
Elseif Not major Select ed Then
If Not yearS electe d Then
Year." )
Messag eBox.S how("Y ou must select a Major and a
Else
Messag eBox.S how("Y ou must select a Major .")
End If
Else
Messag eBox.S how("Y ou must select a Year." )
End If
End Sub

23. Privat e Sub Checke dChang ed( ... ) Handle s


,
chkSen ior.Ch eckedC hanged , chkBli nd.Che ckedC hanged
eckedC hanged , chkSpo useBli nd.Che ckedC hanged
chkSpo use.Ch
Dim count As Intege r = 0
If chkSe nior.C hecked Then
count += 1
End If
If chkBli nd.Che cked Then
count += 1
End If
If chkSpo use.Ch ecked Then
count += 1
End If
If chkSp ouseB lind.C hecked Then
count += 1
End If
txtOu tput.T ext CStr (count )
End Sub
btnCa lculat e.Clic k
25. Privat e Sub btnCa lculat e_ Click( ... ) Handle s
Dim fee As Double = 0
If radAd ult.Ch ecked Or radSen ior.Ch ecked Then
Dim numEx tras As Intege r = 0
If chkTe nnis.C hecked Then
numEx tras += 1
End If
If chkLo cker.C hecked Then
numEx tras += 1
End If
I f chkLau ndry.C hecked Then
numEx tras += 1
End If
If radAd ult.Ch ecked Then
fee 100 + numEx tras * 25
Else
fee = 75 + numEx tras * 25
End If
txtFee .Text = Forma tCurre ncy(fe e)
Else
catego ry.")
Messag eBox.S how("Y ou must select a membe rship
End If
End Sub
Answers To Selected Odd -N umbered Exerci es • 623

CHAPTER 5
EXERCISES 5.1
1. 203 3. The population will double in 24 years.
5. 27 is an odd nwnber. 7. Your state income tax is $150 . 00.
9. age before beauty
11. The function header should end with "As String", not "As Integer".

13. Private Sub btnDetermi ne_ Click( .. . ) Handles btnDeterm ine.Click


Dim radius, height As Double
lstOutput . Items . Clear ( )
radius = CDbl ( InputBox(" Enter radius of can (in centimete rs):"))
height= CDb l( InputBox ("Enter height of can (in cen t imeters):" ))
lstOutput . I t ems . Add ( "A can of radius " & radius & " and height " &
height)
lstOutput. I tems. Add("requ i re s " & Ti nAr ea(radius, h e i ght) &
" square centimeter s")
lstOutput. Items . Add (" of tin . " )
End Sub

Function TinArea(By Val radiu s As Double , ByVal ht As Double) As Double


' Calculate surfac e area of a cylindrica l can.
Return 6. 28 3 * (radius A 2 + radi us * h t)
End Func t ion

a_. 5. Exerci~e 13 a:;; 5. Exercise 15

Determine Amount of Material Weight in pounds : 165


Needed to Make a Can
Height in inches: 7

A can of radius 5 and height 10


Calculate BMI
requires 471.225 square centimeters
of tin .
BMI : 2

15. Privat e Sub b t n Cal c ulate_ Click ( . .. ) Handles btnCalcula t e.Click


Di m weigh t As Double= CDbl(txtWe i ght . Text)
Dim h eight As Double= CDbl(txtH eight . Text )
txtBMI.Tex t CSt r (BMI(weigh t, he i ght))
End Sub

Function BMI(ByVal w As Double , ByVal hAs Double) As Double


Return Math . Round( ( 703 * w) I (h A 2))
End Function

17. Private Sub btnDetermi ne Click( . . . ) Handles btnDeterm ine.Click


Dim popcorn, butte r , bucket, price As Double ' amount in dollars
popcorn= CDbl(Input Box("What is the cost of the popcorn kernels?") )
butter= CDbl(Input Box("What is the c ost of the butte r substitute ?"))
bucket= CDbl(Input Box("What is the cost of the bucket?"))
price= CDbl(Input Box("What is the sale price?"))
txtProfit.T ext = FormatCur rency(Prof it(popcorn , butter , bucket, price))
End Sub
624 • Answers To e lected Odd-N um bered Exercises

,
Functio n Profit(B yVal popcorn As Double, ByVa l butter As Double
ByVal bucket As Double, ByVal price As Double) As Double
'Calcul ate the profit on a bucket of popcorn
Return price - (popcorn + butter + bucket)
End Functio n

o_. 5.1 Exe rcise 19 l l @) I..


CJ ~--J
o~ 5.1 Exercise 17 l = I [§] ~~ ~·J
Weight of letter (ounces): 4

Determine Profit ( Compute Airmail Cost )


Profit : S4.68 Cost : S0.35

ck
19. Pr ivat e Sub btnComp ute_ Click( ... ) Handles btnCom pute.Cli
Dim weight As Double
weight = CDbl(tx tWeight .Text)
txtOutp ut.Text "The cost of mailing the letter was " &
FormatC urrency( Cost(we ight)) & "·"
End Sub

Functio n Ceil(By Val x As Double) As Double


Return -Int(-x )
End Functio n

Functio n Cost(By Val weight As Double) As Double


Return 0 . 0 5 + 0.1 * Ceil(we ight - 1)
End Functio n
et.Click
21. Private Sub btnAddr essNGre et_ Click( ... ) Handles btnAddr essNGre
Dim name As String
name = InputBo x ("Enter the senator 's name:")
lstOutpu t.Items. Add("T he Honorab le " & name)
lstOutp ut. Items .Add ("United States Senate" )
lstOutpu t.Items. Add("W ashingto n, DC 20001")
1st0utp ut.Items .Add("" )
lstOutp ut.Items .Add("D ear Senator " & LastNam e(name) & ",")
End Sub

Functio n LastNam e(ByVal name As String) As String


Dim spacePo s As Integer
spacePo s = name . IndexOf ( " ")
Return name.Su bstring( spacePo s + 1)
End Functio n

a 1 5.1 Exercise 21 l = I @) I,....JJ l a~ 5.1 Exe rcise 23

( Address Letter to a Senator


I Year: 20 12

~' Hooo~bl• Robffi SmHh Determine if Year is a Leap Year


nited States Senate
ashington , DC 2 01
2012 is a leap year.
IDear Senator Smith .
Answer s To Selected Odd-N umbered Exercises
• 625

23. Privat e Sub btnDete rrnine_ Click( ... ) Handle s btnDet errnine .Click
If IsLeap Year(C int(mtb Year.T ext)) Then 'mask is 0000
txtOut put.Te xt mtbYea r.Text & " is a leap ye ar."
Else
txtOut put.Te xt mtbYea r.Text & " is not a leap year."
End If
End Sub

Functio n IsLeapY ear(ByV al yr As Intege r) As Boolea n


Dim datel As Date = CDate( "#l/1/" & yr & "#")
Dim date2 As Date = CDate( "#l/1/" & (yr + 1) & "#")
If DateD iff(Dat einterv al.Day , datel, date2) = 366 Then
Return True
Else
Return False
End If
End Functio n

EXERCISES 5.2
1. 88 keys on a piano 3. You look dashing in blue.
5. 1440 minute s in a day 7. Why do clocks run clockw ise?
Becaus e they were invente d in the northe rn
hemisp here where sundia ls go clockw ise.
9. It was the best of times. 11. divorce d 13. 24 blackb i rds
It was the worst of times. behead ed baked in
died a pie.
divorce d
behead ed
survive d
15. The first 6 letters are Visual . 17. cost: $250.00
Shippin g cost: $15.00
Total cost: $265.00
19. You passed with a grade of 92.

21. There is a parame ter in the S ub proced ure, but no argume nt in the stateme
n t ca lling the
Sub proced ure.
23. S ince Handle s is a keyword , it cannot be used as the name of a S ub procedu
re.
25. Privat e Sub btnDis play_ Click( ... ) Handle s btnDis
play.C lick
Dim num As Intege r = 7
Lucky(n um)
End Sub

Sub Lucky(B yVal num As Intege r)


txtOut put.Te xt = num & " is a lucky number ."
End Sub

27 . Private Sub btnDis play_ Click( . .. ) Handle s btnDis


play.C lick
Talles t ( "redwo od", 362)
Talles t("pine ", 223)
End Sub

Sub Tallest (ByVa l tree As String , ByVal ht As Double


)
lstBox . Items.A dd("Th e talles t " & tree &
" tree in the U.S. is " & ht & " feet.")
End Sub
626 • Answe rs To Se lected Odd -N umbered Exercises

es btnDi splay .Click


29. Priva te Sub btnDi splay_ Click ( ... ) Handl
Displ aySou rce()
Major s ( 16. 7, "busi ness" )
Majo rs(l.O , "comp uter scien ce")
End Sub

Sub Displ aySou rce()


Dim phras e As Strin g
e freshm en" &
phras e = "Acco rding to a 2008 surve y of colleg
" taken by"
lstOu tput . Items .Add( phras e)
Resea rch Insti tute: ")
lstOu tput.I tems. Add( "the Highe r Educa tion
End Sub
e, ByVal field As String )
Sub Major s(ByV al perce ntOfS tuden ts As Doubl
lstOu tput.I tems. Add(p ercen tOfSt udent s &
field & ".")
"perc ent said they inten d to major in" &
End Sub

a • 5.2 Exercise 29

Display Information .About Majorn

According to a 2008 survey of college freshmen taken by


the Higher Education Research Institute :
16.7 percent said they intend to major in business .
1 percent said they intend to major in comput er science .

es btnDi splay .Click


31. Priva te Sub btnDi splay_ Click ( ... ) Handl
Dim num As Doubl e
num = CDbl( txtBo x.Tex t)
Sum (num)
Produ ct(num )
End Sub

Sub Sum(B yVal num As Doubl e)


Dim phras e As Strin g
with itsel f is "
phras e = "The sum of your favor ite numbe r
& (num + num) & ".")
lstOu tput.I tems. Add(p hrase
End Sub

Sub Produ ct(By Val num As Doubl e)


Dim phras e As Strin g
r with itsel f is "
phras e = "The produ ct of your favor ite numbe
lstOu tput.I tems. Add(p hrase & (num * num) & ".")
End Sub

D.,. 5.2 Exerci:;e 31


l = I@) j..,.a ..,J

'1/llhat is yourfavorite number? 7

The sum of your favorite number with itse~ is 14.


!The product of your favorite number with itseW is 49. I
Answe rs To Selected Odd-N umbered Exercises
• 627

33. Priva te Sub btnDi splay _ Click ( . .. ) Handl


es btnDi splay .Click
ShowV erse ("lamb " , "baa" )
ShowV erse ("duck " , "quac k")
ShowV erse ("fire fly", "blink ")
End Sub

Sub ShowV erse(B yVal anima l As Strin g, ByVal


sound As String )
'Disp lay a verse from Old McDo nald Had a Farm
lstOu tput.I tems. Add(" Old McDo nald had a farm.
Eyi eyi oh.")
lstOu tput.I tems. Add(" And on his farm he had
a " & anima l &
Eyi eyi oh . ")
lstOu tput.I tems. Add(" With a " & sound & & sound & " here, and a " &
sound & " " & sound & " there . ")
lstOu tput.I tems. Add(" Here a " & sound & ",
there a " & sound &
", e v erywh ere a " & sound & " " & sound &
".")
lstOu tput.I tems. Add(" Old McDo nald had a farm.
Eyi eyi oh.")
lstOu tput.I tems. Add(" ")
End Sub

..
gW 5.2 Exercise 33 l = I @) l;._.n_l
( Display Verses of Old McDon ald Had a Farm
)
Old McDonald had a farm . Eyi eyi oh .
Arid on his farm he had a lamb . Eyi eyi oh .
With a baa baa here . and a baa baa there .
Here a baa . there a baa . everywhere a baa baa .
Old McDonald had a farm . Eyi eyi oh .

Old McDon ald had a farm . Eyi eyi oh .


Arid on h1s farm he had a duck. Eyi eyi oh .
With a quack quack here. and a quack quack there .
Here a quack . there a quack. everywh ere a quack quack .
Old Me Donald had a farm . Eyi eyi oh .

Old McDon ald had a farm . Eyi eyi oh .


Arid on his farm he had a firefly. Eyi eyi oh .
With a blink blink here. and a blink blink there .
Here a blink. there a blink . everywh ere a blink blink .
Old McDon ald had a farm . Eyi eyi oh .

35 . Pri v at e Sub btnDe termin e_ Click ( .. . ) Handl


es btnDe termi ne.Cl ick
Dim grade l As Doubl e CDbl (txtG radel. Text)
Dim grade 2 As Doubl e = CDbl( txtGra de2.T ext)
Dim grade 3 As Doub le= CDbl( txtGra de3.T ext)
Displ ay Highe stTwo (grade l , grade 2, grade 3)
End Sub

Sub Displ ay Highe stTwo (ByVa l grade l As Doubl


e, ByVal grade 2 As Doubl e,
ByVal grade 3 As Doubl e)
Di m first , secon d As Doubl e
first = Max (grade l , grade 2)
If first grade l Then
secon d Max (grade 2, grade 3)
Else
secon d Max(g radel, grade 3)
End If
628 • Answ ers To Selec ted Odd -Num bered Exe rcises

&
txtO utpu t . Text "The h i ghes t two grad es are " & first
" and " & secon d & " "
End Sub

ByVa l num2 As Doub le) As Doub le


Func tion Max( ByVa l numl As Doub le,
If numl <= num2 Then
Retu rn num2
Else
Retu rn numl
End If
End Func tion
( ... ) Hand les btnA lpha betiz e.Cli ck
37. Priv ate Sub btnA lpha betiz e_ Click
Dim word l = txtW ordl . Text
Dim word2 = txtW ord2 .Text
Disp layWo rds(w ordl, word 2)
End Sub

g, ByVa l word2 As Strin g)


Sub Displ ayWo rds(B yVal word l As Strin
Dim first , secon d As Strin g
If word l <= word2 Then
first = word l
secon d = word2
Else
first = word2
secon d = word l
End If
lstO utpu t.Ite ms.A dd(f irst)
lstOu tput. Item s.Ad d(sec ond)
End Sub

EXERCISES 5.3
.
1. Gabr iel was born in the year 1980
Forg et Me Not.
3. The state flow er of Alas ka is the
EDU.
5. The first 3 lette rs of EDUCATION are

7. curr ent inve ntory : 2 is displa yed both


times the butto n is clicked. The secon d click
purch ase cance lled.")
also produ ces the message "Insufficient inventory,
9. sum = 4
diffe renc e = 2
) Hand les btnD ispla y.Cl ick
11. Priva te Sub btnD ispla y_ Click ( ...
Dim firstN ame As Strin g = ""
Dim lastN ame As Strin g = ""
Dim salar y, newS alary As Doub le
y)
Inpu tDat a(fir stNa me, lastN ame, salar
newS alary = Rais edSa lary( salar y)
newS alary )
Disp layO utpu t(firs tNam e, lastN ame,
End Sub

g, ByRe f lastN ame As Strin g,


Sub Input Data (ByR ef firstN ame As Strin
ByRe f salar y As Doub le)
first Name = txtFi rstNa me.T ext
lastN ame = txtLa stNa me.T ext
sala ry= CDb l(txtC urren tSala ry.Te xt)
End Sub
Answers To Selected O dd-N umbered Exercises • 629

Function RaisedSala ry(ByVal salary As Double) As Double


If salary <= 40000 Then
Return 1.05 * salary
Else
Return salary + 2000 + 0.02 * (salary - 40000)
End If
End Function

Sub DisplayOut put(ByVal firstName As String, ByVal lastName As String,


ByVal newSalary As Double)
txtOutput. Text "New salary for " & firstName & " " & lastName &
" is " & FormatCurr ency(newSa lary) & " "
End Sub

13. Private Sub btnCalcula te_ Click( ... ) Handles btnCalcula te.Click
Dim annualRat eOfinteres t, monthlyPay ment, begBalance As Double
Dim intForMont h, redOfPrinc ipal, endBalance As Double
InputData( annualRate Ofinterest, monthlyPay ment, begBalance )
Calculate( annualRat eOfinteres t, monthlyPay ment, begBalance ,
intForMont h, redOfPrinc ipal, endBalance )
DisplayDat a(intForMo nth, redOfPrinc ipal, endBalance )
End Sub

Sub InputData(B yRef annualRat eOfinteres t As Double,


ByRef monthlyPay ment As Double,
ByRef begBalance As Double)
annualRat eOfinteres t = CDbl(txtA nnualRateO finterest.T ext)
monthlyPay ment = CDbl(txtMo nthlyPayme nt.Text)
begBalance = CDbl(txtBe gBalance.T ext)
End Sub

Sub Calculate(B yVal annualRat eOfinteres t As Double,


ByVal monthlyPay ment As Double,
ByVal begBalance As Double, ByRef intForMont h As Double,
ByRef redOfPrinc ipal As Double, ByRef endBalance As Double)
Dim monthlyRa teOfinteres t As Double = annualRat eOfinteres t I 12
intForMont h = (monthlyR ateOfintere st I 100) * begBalance
redOfPrinc ipal = monthlyPay ment - intForMont h
endBalance = begBalance - redOfPrinc ipal
End Sub

Sub DisplayDat a(ByVal intForMont h, ByVal redOfPrinc ipal,


ByVal endBalance )
txtintForM onth.Text = FormatCurr ency(intFor Month)
txtRedOfP rincipal.Te xt = FormatCur rency(redO fPrincipal)
txtEndBala nce . Text = FormatCurr ency(endBa lance)
End Sub

CHAPTER 6
EXERCISES 6.1
1. 18 3. 10 5. Maximum number: 7
7. Infinite loop. (To end the program, click on the Stop Debugging button on the Too lbar.)
9. Do and Loop are interchange d 11. While num >= 7 13. Until response< > "Y"
630 • Answers To Se lec ted O dd-N um bered Exercises

15. Until name= "" 17. until (a<= 1) Or (a >= 3) 19. While n 0

k
21. Private Sub btnDisp lay_ Click( ... ) Handles btnDisp lay.Clic
'Reques t and display three names.
Dim name As String, num As Integer = 0
Do While num < 3
name = Inpu tBox ("Enter a name: ")
lstOutpu t.Items. Add(nam e)
num +=1 'Add 1 to value of num.
Loop
End Sub

23. Private Sub btnDisp lay_ Click( ... ) Handles btnDisp lay . Click
Dim celsius As Double = 10
lstOutp ut.Items .Add("C elsius Fahrenh eit")
Do While celsius <= 95
" & celsiu s & " II &
lstOutp ut.Items .Add("
Fahrenh eit(cels ius))
celsius += 5
Loop
End Sub

Functio n Fahrenh eit(ByV al celsius As Double) As Double


'Conver t Celsius to Fahrenh eit
Return (9 I 5) * celsius + 32
End Functio n

D 6.1 Exerc ise 23 l = I@) IL .n. .I

I Display Conversion Table )


Celsius Fahrenh eit
10 ;;o
1i:. 59
20 68
25 77
30 86
3i:. 9i:.
40 104
45 113
i:.O 122
i:.S 131
I 60 140
65 149 a.. 6.1 Exerc is.e 25
70 158
5 167
80 176 Locate Letters r flfld n
95 185
90 194 TI-1e letter r is first.
95 203

25. Private Sub btnLoca te_ Click( ... ) Handles btnLoca te.Click
Dim word As String = ""
Dim rPlace, nPlace As Integer
Do
InputWo rd(word)
rPlace word. IndexOf ( "r")
nPlace = word. IndexOf ( "n")
Answers To Selected Odd-N umbered Exercises • 631

If (rPlace = -1) Or (nPlace = -1) Then


MessageBo x.Show("Th at word does not contain both rand n.", "")
End If
Loop Until (rPlace > -1) And (nPlace > -1)
ShowFirst( rPlace , nPlace)
End Sub

Sub InputWord( ByRef word As String)


Dim prompt As String
prompt= "Enter a word containing the letters 'r' and 'n' . "
word = InputBox(p rompt, "Enter Word")
End Sub

Sub ShowFirst(B yVal rPlace As Integer, ByVal nPlace As Integer)


'Tell which letter, r or n, comes first.
If nPlace > rPlace Then
txtOutput . Text "The letter r is first."
Else
txtOutput. Text "The letter n is first . "
End If
End Sub

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


Dim num, max, min As Double
Dim count As Double = 0
Dim prompt As String = "Enter a nonnegativ e number. • &
"Enter -1 to terminate entering numbers."
num CDbl(Input Box(promp t))
max num
min num
Do While num >= 0
count += 1
num = CDbl(Input Box(promp t))
If (num <> -1) Then
If num < min Then
min = num
End If
If num > max Then
max = num
End If
End If
Loop
If count > 0 Then
txtRange.T ext = CStr(max - min)
Else
MessageBox . Show ("No numbers were entered.")
End If
End Sub

... 6.1 Exercise 29 [


g .J = I @) T ~ ?1
a;) 6: Exercise 27 l = I @) 1-·fJ ·•I
M: JO N: 35

Find Range of Numbers


[ Find Greatest Common Divisor J
Range : 7
GCD: 5
632 • Answer s To Se lected Odd-Nu mbered Exerc ise

29. Private Sub btnFin d_ Click ( ... ) Handle s btnFin d.Click


Dim m, n, t As Intege r
Inputin tegers (m, n)
Do While n <> 0
t n
n = m Mod n 'Remain der after m is divided by n
m = t
Loop
txtOut put.Te xt CStr(m )
End Sub

r)
Sub Inputin tegers( ByRef mAs Intege r, ByRef n As Intege
m = Cint(tx tM.Tex t)
n = Cint(tx tN . Text)
End Sub
pute.Cl ick
31. Private Sub btnCom pute_ Click( . .. ) Handle s btnCom
Dim age As Intege r = 1
Do While 1980 + age <> age A 2
age += 1
Loop
txtOu tput.Te xt age & " years old"
End Sub

a.. 6. _ Exercise 31 D 6. Exercise 33

Compute ~e Determine Decay Time

5years old 1So6years

ermine .Click
33. Private Sub btnDet ermine _ Click( ... ) Handle s btnDet
Dim amount As Double 100
Dim yrs As Intege r = 0
Do Until amount < 1
amount = 0.5 * amount
yrs += 28
Loop
txtOut put. Text yrs & " years"
End Sub
ermine .Click
35. Private Sub btnDete rmine_ Click( ... ) Handle s btnDet
Const INTEREST PER MONTH As Double = 0 . 005
Dim loanAm ount As Double = 15000
Dim months As Intege r = 0
Dim balanc e As Doubl e = loanAm ount
Do Until balanc e < loanAm ount I 2
balanc e = (1 + INTEREST_ PER_ MONTH) * balanc e - 290
months += 1
Loop
txtOut put.Te xt months & " months "
End Sub
ermine .Click
37. Private Sub btnDete rmine_ Click( ... ) Handle s btnDet
Dim months As Integer = 0
Dim balanc e As Double = 10000
Do Until balanc e < 600
balanc e = 1.003 * balanc e - 600
An swers To Selec ted O dd -N umbe red Exerc ises
• 633

mont hs += 1
Loop
txtO utpu t . Text mont hs & 11 mont hs; 11
& Form atCu rrenc y(bal ance )
End Sub

11_. 6. Exercise 35 l = I @) l•-l3 ·I ll';} 6. Exercise 37 l=l @J L . ~. I

( Determine Vll'hen Loan is Ha~ Paid Off ) ( Determine ,,'ll'hen Balanc e Is Less Than ~ 1
nmon ths 17 months ; "-73.91

EXERCISES 6.2
1. Pass #1 3. 2 5. 5 7. ••••• ••••• 9. 4
Pass #2 4 6
Pass #3 6
7
Pass #4 8
Who do we appr eciat e ?
11. The loop is neve r execu ted since 25 is great e r th an 1
and th e step is negat ive.
13. T h e Fo r ... Next loop will not execute since
20 is grea ter than 0. You mu st add step -1 to
the end of the For state ment .
15. Priv ate Sub btnD ispla y_ Click ( ...
) Hand les btnD ispla y.Cl ick
For num As Integ er = 1 To 9 Step
2
lstBo x.Ite ms.A dd(n um)
Next
End Sub

17. Priv ate Sub btnd ispla y_ Click ( ...


) Hand les btnd ispla y.Cl ick
For i As Integ er = 2 To 100 Step
2
lstO utpu t.Item s.Ad d(i)
Next
End Sub

ll _. 6.2 Exerci:;.e 17 l= @) I~ -~J

[ Display Even Numbers


l
2 ;.

4
f.) lJ 11,} 6.2 Exe rcise 19
8
10 Rnd Average of Rve Numbers
12
14
15 ~
85:'1

19. Priv ate Sub btnF ind_ Click ( . .. )


Hand les btnF ind.C lick
Dim sum As Doub le = 0, num as Doub
le 0
For i As Integ er = 1 To 5
num = CDbl (Inpu tBox ( 11 Ente r # 11 & i))
sum += num
Next
txtAv erag e.Te xt Form atNum ber(s um / 5, 2)
End Sub
ises
634 • Answ ers To Se lected Odd -N um bered Exerc

... ) Han dles btnC omp ute.C lick


21. Priv ate Sub btnC omp ute_ Cl i ck(
Dim sum As Dou ble = 0
To 100
For deno mina tor As Doub l e = 1
sum += 1 I deno mina to r
Next
, 5)
txtO utpu t . Text = Form atNu mber (sum
End Sub

l = I §) I. S2 ~J
D~ 6.2 Exercise 23

Calculate Depreciated Value of Car


in Succ essive Years
a 6.2 Exercise 21 l = I §) l,...tJ ..,~J
1: 517.000.00
2: 514.450.
Compute Sum of 1+1/2 ...+ 1/ 100 3: 512.282.50
4: 510.440.13
5.18738 5: 58.874.11

ck
k( ... ) Han dles btnC alcu late .Cli
23. Priv ate Sub btnC alcu late _ Clic
Dim valu e As Dou ble = 2000 0
For i As Inte ger = 1 To 5
valu e = 0.85 * valu e
lstO utpu t.Ite ms.A dd(i & :
11 11 & Form atCu rren cy(v alue ))
Next
End Sub
k( ... ) Han dles btnC omp ute.C lick
25. Priv ate Sub btnC omp ute_ Clic
0.05
Di m PERCENT RAISE As Dou ble =
As Inte ger, sala ry As Dou ble
Dim name As Stri ng, age
Di m earn ings As Dou ble = 0
name = txtN ame .Tex t
age = Cint (txtA ge.T ext)
sala ry= CDb l(txt Sala ry.T ext)
For i As Inte ger = age To 64
earn ings += sala ry
E * sala ry)
sala ry = sala ry + (PERCENT_ RAIS
Nex t
name & 11 will earn abou t
11 &
txtO utpu t.Te xt
Form atCu rren cy(e arni ngs, 0) & 11 11

End Sub

g:.. 6.2 Exercise 25 l = I §) l......tJ ··~

Name : Helen Af,Je: 25

Starting salary : 20000

( Compute E.amings

Helen will eam about 52.415.995 .


Answers To Selec ted Odd-N umbe red Exerc i es
• 635

27. Priv ate Sub btnC omp uteid ealW


eigh ts_ Clic k( ... ) Hand les
btnC omp uteid ealW eigh ts.Cl ick
Dim lowe r, uppe r As Inte ger
lstW eigh tTab le.It ems .Cle ar()
Inpu tBou nds( lowe r, uppe r)
Show Weig hts(l ower , uppe r)
End Sub

Func tion Ideal Man (ByV al heig ht As


Inte ger) As Doub le
'Com pute the idea l weig ht of a man
give n his heig ht
Retu rn 4 * heig ht - 128
End Func tion

Func tion Idea lWom an (ByV al heig ht


As Inte ger) As Doub le
'Com pute the idea l weig ht of a woma
n give n her heig ht
Retu rn 3.5 * heig ht - 108
End Func tion

Sub Inpu tBou nds(B yRef lowe r As Inte


ger, ByRe f uppe r As Inte ger)
lowe r Cint (Inp utBo x("E nter lowe r boun d
on heig ht in inch es:" ))
uppe r = Cint (Inp utBo x("E nter uppe
r boun d on heig ht in inch es:" ))
End Sub

Sub Show Weig hts(B yVal lowe r As Inte


ger, ByVa l uppe r As Inte ger)
lstW eigh tTab le. Item s. Add ("
" & "WEIGHT " & " " & "WEIGHT")
lstW eigh tTab le.Ite ms.A dd(" HEIG HT"
& " II & "WOMEN II & II II & "MEN")
For heig ht As Inte ger = lowe r To
uppe r
lstW eigh tTab le.It ems .Add (heig ht
& " " &
Form atNu mber (Idea lWom an(h eigh t),
1) &
" & Form atNu mber (Idea lMan (heig ht),
Next 1))
End Sub

29. Priv ate Sub btnD ispla y_ Clic k(


. .. ) Hand les btnD ispla y.Cl ick
Dim bala nce As Doub le = 0
Dim yr As Inte ger = 2010
For i As Inte ger = 1 To 120
bala nce = (1 .0025 ) * bala nce + 100
If i Mod 12 = 0 Then
lstO utpu t.Ite ms.A dd(y r & "
" & Form atCu rrenc y(ba lanc e))
yr += 1
End If
Next
End Sub

31. Priv ate Sub btnA naly ze Clic k(


... ) Hand les btnA naly ze.C lick
Cons t DECAY RATE As Doub le = 0.12
Dim gram s As Doub le
gram s = 10
For yearN um As Inte ger = 1 To 5
gram s = (1 - DECAY_ RATE) * gram s
Next
lstO utpu t.Ite ms.A dd(" Begi nnin g with
10 gram s of coba lt 60," )
lstO utpu t . Item s . Add( Form atNu mber
(gram s) &
" gram s rema in afte r 5 year s.")
End Sub
Exercises
636 • Ans wers To Se lected Odd-N umb ered

D 6 2 Exercise 31 l = I @) ~~ J
.Allalyze Radio activ e Decay J

Of 10 grams of cobaHiO. j'


5.28 grams rema 1n after 5yea rs .

.Cli ck
Clic k( ... ) Han dles btn Dis play
33. Priv ate Sub btnD ispl ay_
ble
Dim pric e, qua ntit y As Dou
lstO utp ut.I tem s.C lear ()
in mil lion s of bus hels
qua ntit y = 80 'cur ren t crop of soy bea ns
" & "PR ICE ")
& " " & "QUANTITY" & "
lstO utpu t.Ite ms. Add ("Y EAR "
For yr As Inte ger = 2010 To
2020
* qua ntit y
pric e = 20 - 0.1 &
tem s.A dd( yr & " " & For mat Num ber( qua ntity )
lstO utp ut.I ))
" & For mat Cur renc y(p rice
qua ntit y 5 * pric e - 10
Nex t
End Sub
btnA naly zeO ptio ns.C lick
Priv ate Sub btnA naly zeO ptio ns Clic k( ... ) Han dles
35.
'Com pare sala ries
Dim opt1 , opt2 As Dou ble
opt1 = Opt ion1 ()
opt 2 = Opt ion2 () t1))
n 1 " & Form atCu rren cy (op
lstO utp ut. Item s. Add ("O ptio Cur renc y(op t2))
n 2 " & For mat
lstO utpu t.Ite ms. Add ("O ptio
If opt1 > opt2 The n
n 1 pay s bet ter. ")
lstO utpu t.Ite ms. Add ("O ptio
E1s eif opt1 = opt2 The n
ns pay the sam e.")
lstO utpu t.Ite ms. Add ("O ptio
Else
2 pay s bet ter. ")
lstO utp ut.I tem s.A dd ( "Op tion
End If
End Sub

Fun ctio n Opt ion1 () As Dou ble


a fla t sala ry of $10 0/da y
'Com pute tota l sala ry with
Dim sum As Inte ger 0
For i As Inte ger = 1 To 10
sum += 100
Nex t
Ret urn sum
End Fun ctio n

Fun ctio n Opt ion2 () As Dou ble day


ting at $1 and dou blin g each
'Com pute tota l sala ry star ger = 1
Dim sum As Inte ger 0, day Sala ry As Inte
For i As Inte ger = 1 To 10
sum += day Sala ry
day Sala ry = 2 * day Sala ry
Nex t
Ret urn sum
End Fun ctio n
Answers To Selected Odd -N umbered Exercises • 63 7

a~ 6, Exerci"-e 35

Year: 11 Determine Dates

Option 1 = <!1.
Option 2 = S1 .
Option 2 pa>,'S better.

37. Private Sub btnDetermine_ Click( ... ) Handles btnDetermine.Click


Dim dt As Date = CDate("#l/1/" & mtbYear.Text & "#")
Dim d As Date
For i As Integer = 0 To 11
d = dt.AddMonths(i)
lstOutput . Items.Add(FirstTuesday(d))
Next
End Sub

Function FirstTuesday(ByVal d As Date) As Date


For i As Integer = 0 To 6
If FormatDateTime(d.AddDays(i),
DateFormat.LongDate) .StartsWith("Tuesday ") Then
Return d.AddDays(i)
End If
Next
End Function

EXERCISES 6.3

1. Mozart 3. Tchaikovsky 5. 3 7. 80 9. 70 11. 300

13. Private Sub btnCount Click( . .. ) Handles btnCount . Click


Dim numWon As Integer = 0
For i As Integer = 0 To lstBox . Items . Count - 1
If CStr(lstBox.Items(i)) = "USC" Then
numWon += 1
End If
Next
txtOutput . Text CStr(numWon)
End Sub

Q 6.3 Exerci.>e 3 l = I§) 1-·ta


Michigan ;.
1
N ashington State Count Number of
Oregon Games 1,'1/on CiJ' U SC
Mare Island
Great Lakes
Harvard
ICalifomia
Califomia
usc
W ashington
Notre Dame ...-
638 • Answers To Se lected O dd-N um bered Exercises

15. Private Sub btnCoun t_ Click( . .. ) Handles btnDete rmine.C lick


Dim college As String = txtColle ge.Text
txtOutp ut.Clea r()
For i As Integer = 0 To lstBox.I tems.Co unt - 1
If CStr(ls tBox.It ems(i)) =colleg e Then
txtOutp ut.Text = "YES"
Exit For
End If
Next
If txtOutp ut.Text = "" Then
txtOutp ut.Text = "NO"
End If
End Sub

or
Private Sub btnCoun t_ Click( ... ) Handles btnDete rmine.C lick
Dim college As String = txtColle ge.Text
Dim i As Integer = 0
Dim found As Boolean = False
Do Until (found = True) Or (i = lstBox.I tems.Co unt)
If CStr(ls tBox.It ems(i)) =colleg e Then
found = True
End If
i += 1
Loop
If found Then
txtOutp ut.Te xt "YES"
Else
txtOutp ut.Text "NO"
End If
End Sub

a 6.3 Exercise 15

1 -
Michigan
W ashington State r, Notre Dame
Oregon
Mare Island
Great Lakes Determine if College has
Harvard Won a Rose Bowl
califomia
1
Califomia YES
usc
W ashington
~ I
I Notre Dame

k
17 . Private Sub b tnRever se_ Click( ... ) Handles btnReve rse.Clic
Dim highest index As Integer = lstBox.I tems.Co unt - 1
For i As Integer = highest index To 0 Step -1
lstBox2 .Items.A dd(1stB ox.Item s(i))
Next
End Sub
Click
19. Private Sub btnAlph abetize_ Click( ... ) Handles btnAlph abetize.
lstBox2 .Sorted =True
Dim highest index As Integer = lstBox.I tems.Co unt - 1
For i As Integer = 0 To highest index
lstBox2 .Items.A dd(lstB ox.Items (i))
Next
End Sub
Answe rs To Selected Odd -N um bered Exercises
• 639

fl-} 6.3 Exerci e 11 l = I @] J.., . &S J


Michigan
·- io Ohio State ;..

us
Washington State
Oregon
Mare Island
_] usc
usc
u
Great Lakes Texas
Harvard Texas
California usc
California Oklahom a
usc Miami
Washin gton Washin gton
Notre Dame ...... Wiscon sin
Vl/isconsin
( Reverse Ust
1
Michigan ...-

..
a..J 6.3 Exereise 9 l = I@] I~· ~ J
[ Jphabetize States )
Delaware .. Alabama ....
Pennsylvania
New Jersey
Georgia
[l Alaska
Arizona
Arl<ansas
u
Connecticut California
Massachusetts Colorado
M a r1~and Connecticut
South Carolina Delaware
New Hampshire .... Rorida ....

21. Pr i vate Sub btnDi sp l ay_ Click ( . .. ) Handl


es btnDi splay .Click
Dim highe stinde x As Integ er = lstBo x . Items
.Coun t - 1
Dim state As Strin g
For i As Integ er = 0 To highe stinde x
s tate= CStr (lstBo x.Item s(i ) )
I f state . Lengt h = 7 Then
lstBo x2.Ite ms.A dd(sta te)
End If
Nex t
End Sub

D.,. 6.3 Exercis-e 21 l= i @J i~ J

( Displa)' States That Are Seven Letters Long )


Delaware .... Georgia
Penns;~v ani a
New Jersey u Vermont
Indiana
Georgia Alabama
Connecticut Montana
Massachusetts Rorida
M a l)~ and Mordana
South Carolina 1N)'Omin g
N e •~>• Hampshire .... Arizona
640 • Answ ers To Se lected Odd-N um bered Exe rcises

Hand les btnD eterm ine.C lick


23. Priva te Sub btnD eterm ine_ Click ( ... )
Dim highe s tinde x As Integ er = lstBo x.Item s.Cou nt - 1
Dim state As Strin g
For i As Integ er = 0 To highe stind ex
state = CStr (lstB ox.I tems (i))
If state . Start sWit h( "New" ) Then
txtOu tput. Text = state
Exit For
End If
Next
End Sub

...
C· 6.3 Exercise 23 l= l @) l~ d

l Determ ine First State that Begins •.vith New J


,-----
Delaware ...
Pennsylvania
New Jersey I -'
Georgia New Jersey
Connecticut
Massachusetts
Mar11and
South Carolin a
New Hampshire
....

les btnD ispla y . C1ick


25. Priva te Sub btnD isplay _ Click ( . .. ) Hand
er = lstBo x.Item s .Coun t - 1
Dim highe s tinde x As Integ
Dim maxLe ngth As Integ er = 0
Dim state As Strin g
For i As Integ er = 0 To highe stind ex
state = CStr( lstBo x .Item s(i))
If state .Len gth > maxLe ngth Then
maxL ength = state .Len gth
End If
Next
For i As Integ er = 0 To highe stind ex
st at e= CStr (lstB ox.It ems( i))
If state .Leng th = maxL ength Then
1stBo x2.It ems.A dd(st ate)
End If
Next
End Sub

D 6.3 Exerci$e 25 l= l @) l~ '·'l

r Display States with Longest Names J


Delaware ;, South Carolin a
Penns;1vania North Carolina
Ne•, • Jersey
0
Georgi a
Connecticut
Massachusetts
Mar,~and
South Carolin a
New Hampshire
...
Answers To Selected Odd-N umbered Exercises • 641

27. Private Sub btnDetermine _ Click( . .. ) Handles btnDetermine .Click


Dim highestindex As Integer = lstBox.Items. Count - 1
Dim state As String
For i As Integer = 0 To highestindex
state = CStr(lstBox. Items(i))
If NumberOfVow els(state) = 4 Then
lstBox2.Item s.Add(state)
End I f
Next
End Sub

Function NumberOfVow els(ByVal word As String) As Integer


Dim numVowels As Integer = 0
wo rd = word.ToUpper
Dim letter As String
Dim numLetters As Integer = word.Length
For i As Integer = 0 To (numLetters - 1)
letter = word . Substring(i , 1)
If (letter = "A") Or (letter "E") Or (letter "I") Or
(letter = "0" ) Or (letter = "U") Then
numVowels += 1
End If
Next
Return numVowels
End Function

[1 .. 6.3 Exe rci e 27 l = I @] 1~;, ~

I Detennine States having Four Vowels )


Delaware ;.. Delaware ;..

Pennsylvania Pennsylvania
New Jersey
Georgia
Connecticut
l_J Georgia
Connecticut
Massachusetts
F! -

Massachusetts New Hampshire


Maryland Virginia
South Carolina Rhode Island
New Hampshire .,.. Tennessee ....
·-

29. Private Sub btnDetermine Click( ... ) Handles btnDetermine .Click


Dim highestindex As Integer = lstBox.Items. Count - 1
Dim state As String
Dim maxNumOfVow els = 0
For i As Integer = 0 To highestindex
state= CStr(lstBox. Items(i))
If NumberOfVow els(state) > maxNumOfVow els Then
maxNumOfVow els = NumberOfVow els(state)
End If
Next
txtOutput.Te xt CStr(maxNumO fVowels)
End Sub

Function NumberOfVow els(ByVal word As String) As Integer


Dim numVowels As Integer = 0
word = word.ToUpper
Dim letter As String
642 • Answers To Se lected O dd-N um bered Exercise

Dim numLett ers As Integer = word.Len gth


For i As Integer = 0 To (numLett ers - 1)
le t ter = word.Sub str ing(i, 1)
If ( letter = "A") Or (letter "E") Or (letter "I") Or
( letter = "0" ) Or (l etter = "U") Then
numVowe ls += 1
End I f
Next
Return numVowe ls
End Fu nction

c 6.3 Exe rcise 29 l= @] lr..,lJ ....j


j
c= 6.3 Exe rcise 31 l = I @] IMI>· · t3
l Determine Maximum Number of
Vowels in the Name of a State

Delaware
J [ Display Name of Rrst State )
Delaware ;
Pennsylvani a Pe nnS}~v a ni a
New Jersey New Jersey 0
Georgia 6 Georgia
Connecticut Connecticut Delaware
Massachusetts Massachusetts
Maryland M a r,~ a n d
South Carolina South Carolina
New Hampshire Ne•N Hampshire ...-

31. Pr i vate Sub btnDispl ay_ Click( ... ) Handles btnDispl ay.Click
txtOutpu t.Text = CStr(lstB ox.Items (O))
End Sub

33. Private Sub btnDispla y_ Click( ... ) Handles btnDispl ay.Click


txtOutpu t.Text = CStr(lstB ox.Items (4))
End Sub

c~ 6.3 Exe rcise 33 1. = I @] 1..-a J a;;' 6.3 Exe rcise 35

I Display Name of Frfth State ) Grade:

Delaware ... Record Grade


PennS}~vani a
._j
Ne•.v Jersey Calculate Average
Georgia and Lowest Grade
Connecticut Connecticut
75
Massachusetts verage grade : &3. 81
Maryland
South Carolina
...- Lowest grade: 7
New Hampshire

35. Priv ate Sub btnRecor d_ Click( ... ) Handles btnRecor d.Click
lstGrad es .Items.Ad d(txtGrad e . Text)
txtGrade. C lear()
txtGrade . Focus ()
End Sub
Answ ers To Selec ted O dd -Num bered Exerc ises
• 643

Priv ate Sub btnC alcu late_ Clic k( ...


) Hand les btnC alcu late. Clic k
Dim sum As Doub le = 0
Dim minG rade As Doub le = 100
If lstG rade s . Item s . Coun t > 0 Then
For i As Inte ger = 0 To lstG rade
s.Ite ms.C ount - 1
sum+ = CDb l(lst Grad es.It ems (i})
If CDb l(lst Grad es.It ems (i)) < minG
rade Then
minG rade = CDb l(lst Grad es.It ems
(i))
End If
Next
Else
Mess ageB ox.Sh ow(" You must firs t
ente r some grad es.")
End If
txtA vera ge.T ext = Form atNu mber (sum
I lstG rade s.Ite ms.C ount , 2)
txtL owe st.Te xt = CStr (min Grad e)
End Sub

37. Priv ate Sub btnR ecor d_ Clic k( ...


) Hand les btnR ecor d.Cl ick
lstG rade s.Ite ms.A dd(t xtGr ade. Text
)
txtG rade .Cle ar()
txt Grad e . Focu s ()
End Sub

Priv ate Sub btnC alcu late Clic k( ...


) Hand les btnC alcu late. Clic k
Dim sum As Doub le = 0
Dim maxG rade As Doub le = 0
Dim minG rade As Doub le = 100
If lstG rade s . Item s.Co unt > 0 Then
For i As Inte ger = 0 To lstG rade
s.Ite ms.C ount - 1
sum+ = CDb l(lst Grad es.It ems (i))
If CDb l(lst Grad es.It ems (i)) > maxG
rade Then
maxG rade = CDb l(lst Grad es.It ems
(i))
End If
If CDb l(lst Grad es.It ems (i)) < minG
rade Then
minG rade = CDb l(lst Grad es.It ems
(i))
End If
Next
Else
Mess ageB ox . Show ("Yo u must firs t
ente r some grad es . ")
End If
txtA vera ge.T ext = Form atNu mber (sum
I lstG rade s.Ite ms.C ount , 2)
txtR ange .Tex t CStr (max Grad e - minG rade)
End Sub

g ..J 6.3 :..erci.~ e 39 l = I @] I ~ _I

States : Rrst two letters


of state :
.1\labama ;.

. Jas a ,{!.[
I A.n~on a ~,
!Arkansas -
Califomia
Record Grade 71
Colorado
85 Search For
Connecticut
B& State
Calcul ate .l'..verage Delaware
91
Grade and Range Rorida
78
Georg ia
87
A.\l·erage grade : 7 Hawa ii
Idaho ..-
Range : :9 .Arizon a begins with .Ar.
ise
644 • Answ ers To Selected Odd -N umbe red Exerc

... ) Han dles btnS earc h.Cl ick


39. Priv ate Sub btnS earc h_ Cl i ck(
stTw oLe tters .Tex t.To Upp er
Dim lett er s As Stri ng = mtbF i r cons ider ed
Dim i As I nteg er = 4 9 'ind ex of the stat e curr entl y
) .ToU pper <=l ette rs) Or (i = 0)
Do Unt il (CS tr(ls tSta tes. Item s(i)
i = i - 1
Loop Then
) . ToU pper . Star tsW ith( lette rs)
If CSt r(ls tSta tes . Item s(i + 1 ) with " &
tem s(i + 1)) & "be gins
txtO utpu t. Tex t = CStr ( l s t Stat es.I
mtb Firs tTw oLe tters . Text & "·"
Then
) .ToU pper .Star tsW i th(l ette rs)
Else if CStr ( lstS tate s. It ems ( O) "be gins wit h" &
CStr ( lstS tate s.Ite ms( O)) &
txtO utpu t .Tex t
mt b Fi r stTw oLe tters . Text & " "

Else
txtO u t put. Tex t "No s t ate begi ns with " &
mt bF i rstT woL etter s . Text & "·"
End If
End Sub

CHA PTE R 7

EXERCISES 7.1
5. Yes 7. 1 2
1. 101 3. Hav e a d e sser t spoo n .

9. You have a trio . 11. Your aver age is 80


15. one, two, thre e
13. Slum dog Mill iona i re won in 2009

17. 2 even numb ers 19. Pear l Harb or: 1941


23. 6 word s begi n with a v owel
21. cont ains a 19th -cen t ury date

25. 4
6
2
orde r)
27. a. Sup erio r (last nam e in alph abet ical
b. Erie (fi rst n ame in alph abe t ica l orde r)
(. Huro n (first na me in th e array)
d. Sup erio r (las t n ame in the array )
e. 5 (num ber of na mes in the array )
f. Ont ario (seco nd na me in t he array )
g. 3 (first array subscript whose elem ent is Erie)

29. a. 6. 5 (grea test popu latio n of a New


England sta te )
)
b. 0. 7 (leas t popu la tion of a New England state
(. 3. 5 (first popu latio n in th e a rray)
d. 1.3 (last popu lat ion in the array )
e. 6 (num ber of n umb e r in the a rray )
f. 1.1 (four th popu latio n in the a rray )
g. 3 (first array subscr ipt whos e ele men t is 1.1)
. Firs t)
31.a . lstO utpu t . Item s.Ad d( st ates
or lstO u tput .Item s.Ad d(st ates (O))
~ For i As Inte ger = 0 To 1 2
lstO u t put . Item s . Add (sta tes( i))
Next
Answ ers To Selec ted Odd-N umbe red Exerc ises
• 645

C. lstO utpu t.Ite ms.A dd(s tates . Last)


OT lstO utpu t.Ite ms . Add( state s(49 ))
d. lstO utpu t . Item s.Ad d(CS tr(Ar ray.I ndex Of(s
tates , "Ohi o")+ 1))
e. lst0u tput. Item s.Ad d(sta tes(1 ))
f. lst0u tput. Item s.Ad d(sta tes(l 9))
g. For i As Integ er = (stat es.C ount - 9) To
(stat es.C ount )
lstO utpu t.Ite ms.A dd(s tates (i 1))
Next
33. Func tion Task (ByV al nums () As Integ
er) As Integ er
Dim sum As Integ er = 0
For Each num As Integ er In nums
sum += num
Next
Retu rn sum
End Func tion

35. Func tion Task (ByV al nums () As Integ


er) As Integ er
Dim maxE ven As Integ er = 0
For Each num As Integ er In nums
If (num Mod 2 = 0) And (num > maxE
ven) Then
maxE ven = num
End If
Next
Retu rn maxE ven
End Func tion

37. Func tion Task (ByV al nums () As Integ


er) As Integ er
Dim twoD igits As Integ er = 0
For Each num As Integ er In nums
If (num > 9) And (num < 100) Then
twoD igits += 1
End If
Next
Retu rn twoD igits
End Func tion

39. nums (3 l should be chan ged to nums ()

41. Logic error. The va lues of the array elemen ts ca


nnot be altered inside a For Each loop. The
outpu t will be 6.
43. lstB ox.It ems. Add (line .Spli t(" "c)
.Cou nt)
45. Priv ate Sub btnD ispla y_ Click ( ...
) Hand les btnD ispla y.Cl ick
Dim numS tr() As Strin g= IO.F ile.R eadA
llLin es("N umb ers.t xt")
Dim nums (num Str.C ount - 1) As Integ
er
For i As Integ er = 1 To nums .Coun t
- 1
nums (i) = Cint (num Str(i ))
Next
l stOu tput. Item s.Ad d("N umbe r of integ
ers in the file: " & nums .Coun t)
lstOu tput. Item s.Ad d("S um of integ ers
in the file: " & nums .Sum)
End Sub

47. Priv ate Sub btnD eterm ine_ Click (


... ) Hand les btnD eterm ine.C lick
Dim name s() As Strin g = IO.F ile . Read
AllL ines( "Nam es2.t xt")
Dim dups( name s . Cou nt- 1) As Strin
g
Dim n As Inte ger= 0 'inde x for dups
For i As Integ er = 0 To name s.Cou nt
- 2
If (nam es(i + 1) name s(i)) And
(Arra y . Index Of(d ups, name s(i))
- 1) Then
ises
646 • Answ ers To Selected Odd-Num bered Exerc

dups (n) nam es(i)


n += 1
End If
Next
If n = 0 Then
tes. ")
lstO utpu t. Item s .Add ("No dup lica
Else
For i As Inte ger = 0 To n - 1
lstO utpu t.Ite ms.A dd(d ups( i))
Next
End If
End Sub
l= I §J I~ ..I ll= 7. Exerc ise 47
l= I§J ~~. I
II 7 Exerc ise 45

Determine Names that are


[ Display Values
1 Duplicated J

Number of integers in the file : 10 I Dana


Sum of integers in the file : BB Jane
Paul

I
-
Ruth
Thomas I
k( ... ) Han dles btnD ispl ay.C lick
49. Priv ate Sub btnD ispl ay_ Clic
ile.R eadA llLi nes( "Dig its.t xt")
Dim strD igit s() As Stri ng= IO.F
Dim freq (9) As Inte ger
.Cou nt - 1
For i As Inte ger = 0 To strD igits
freq (Cin t(str Dig its(i ))) += 1
Next
lstO utpu t.Ite ms.A dd(" Dig it Freq uenc y")
For i As Inte ger = 0 To 9
" & i & " " & freq (i))
lstO utpu t.Ite ms.A dd("
Nex t
End Sub
l = I §J l...t:S·-:"!_,J
ll
- 7. E ercis e 49

r Display Frequ encies ]


:::>igi t; Fr e que ncy
0 3
1 2
2 3
3 ~

4 2
~ 4
6 3
2
3 3
9 3
-

Inte ger) As Inte ger


51 . Fun ctio n Sum( ByV al num s() As
Dim tota l As Inte ger = 0
unt - 1 Step 2
For i As Inte ger = 1 To num s.Co
tota l += num s(i)
Nex t
Retu rn tota l
End Fun ctio n
Answ ers To Se lected O dd -N um bered Exerc ises
• 647

53. Priv ate Sub btnP roces sEgg s_ Click


( ... ) Hand les btnP roce ssEg gs.C lick
Dim heav iest, ligh test, ounc es As
Doub le
Dim jumb o, xLar ge, large , med, smal
l As Integ er
heav iest = 0 'can be any numb er lowe r than ligh
test egg
l i ghte st = 100 •can be any numb er grea ter than heav
iest egg
Dim strEg gs() As Strin g= IO.F ile.R
eadA llLin es("E ggs.t xt")
Dim eggs (s t rEgg s . Coun t - 1) As Doub
le
For i As Integ e r = 0 To eggs .Cou nt
- 1
eggs ( i) = CDb l(strE ggs( i))
Next
For i As Integ er = 0 To eggs .Cou nt
- 1
ounc es= eggs (i)
If ounc es > heav iest Then
heav iest = ounc es
End if
If ounc es < ligh test Then
l ight est = ounc es
End If
Sele ct Case ounc es
Case Is < 1.5
'too smal l & cann ot be sold
Case Is < 1 . 75
smal l += 1
Case Is < 2
med += 1
Case Is < 2 .25
large += 1
Case Is < 2. 5
xLar ge += 1
Case Else
jumbo += 1
End Sele ct
Nex t
lstO utpu t.Ite ms.C lear( )
l stOu tput. Item s.Ad d(jum bo & " Jumb
o eggs ")
lstO utpu t.Ite ms . Add( xLarg e & " Extr
a Larg e eggs" )
lstO utpu t . Item s . Add( large & " Larg
e eggs ")
lstOu tput. Item s.Ad d(me d & " Mediu m
eggs" )
lstO utpu t . Item s . Add( smal l & " Smal
l eggs ")
If ligh test < > 100 Then
lstOu tpu t .Item s . Add( "Lig htest egg:
" & ligh test & " ounc es")
l stOu tput . Items .Add ( "Hea viest egg :
" & heav iest & " ounc es")
Else
l stOu tput . Item s.Ad d("F ile is empt y")
End If
End Sub

aj 7. Exerci:;e 53 l= i@J L.~.. I

Process Eggs

5 .Jumbo eqg3
9~ ~ xtraLarge e gg3
7E Large e gg3
9E Me dium e ggs
77 Smal l e gg3
Ligh t e st e gg : 1 ounc e 9
Heav i e 3t egg : 2 . E9 ounce 3
648 • Answ ers To Se lected Odd -N umbe red Exe rcises

)
File . Read AllL ines ("Co lors . txt"
55. Dim colo rs () As Stri ng = IO.
) Han dles btnD ispl ay.C lick
Priv ate Sub btnD ispla y_ Clic k( ...
er.T ext.T oUp per
Dim lett er As Stri ng = mtb Lett
lstC olor s.Ite ms. Clea r()
rs
For Each hue As Stri ng In colo
If hue. St arts Wit h(le tter ) Then
lstC ol ors.I tems .Add (hue )
End If
Next
End Sub
ile.R eadA llLi nes( "Co lors .txt" )
57. Dim colo rs() As Stri ng= IO.F
) Han dles btnD ispl ay.C lick
Priv ate Sub btnD ispl ay_ Clic k( ... 'mas k L
Lett er.T ext.T oUp per
Dim lett er As Stri ng = mtb
lstC olor s.Ite ms. Clea r()
llerA rray (lett er)
For Each hue As Stri ng In Sma
lstC olor s. Item s.Ad d(hu e )
Nex t
End Sub
er As Stri ng) As Stri ng()
Fun ctio n Sma llerA rray (ByV al lett
As Stri ng
Dim smA rray( colo rs.C oun t - 1)
Dim coun ter As Inte ger = 0
rs
For Each hue As Stri ng In colo
If hue. S tarts Wit h (l ette r) Then
smA rray (cou nter ) = hue
coun ter += 1
End If
Next
- 1)
ReDi m Pres erve smA rray (cou nter
Retu rn smA rray
End Fun ctio n

a 7.1 Exerc ise 57 l = I [§) I~ ..J


Letter : T Display Colorn

Tan g:J 7.1 Exercise 59 l= l [§) 1-iJ _J


Teal Blue
Tickle Me Pink
TimberWo~ Display Data
Torch Red
Tropical Rain Forest
Average number of words per line: 8.141
Tumb leweed
! Total number of words : 11 4 J
Turquoise Blue

... ) Han dles btnD ispl ay.C lick


59. Priv ate Sub btnD ispla y_ Cl i ck(
Dim line s() As Stri ng= IO.F ile.R eadA llLin es(" Son net .txt ")
Dim n = line s.Co unt - 1
Dim numW ords( n) As Inte ger
For i As Inte ger = 0 To n
"c) .Cou nt
numWords (i) = line s(i ) .Spl it("
Next
er of word s per line : " &
lstO utpu t .I tems .Add (" Av erag e nwnb
Form atNw nber (num Wor ds.A vera ge , 2))
nwnb er of word s: " & numW ords. Sum)
lstO utpu t .Item s.Ad d("T otal
End Sub
Answ ers To Selec ted Odd-N umbe red Exerc ises
• 649

61. Dim grad es(99 ) As Integ er •stor es grad es


Dim numG rades As Int e ger 'num ber of grad es store d

Priv ate Sub btnR ecord_ Click ( ... ) Hand


les btnR ecor d.Cli ck
'Add a score to the array
'If no more room , then disp lay erro
r mess age.
If numG rades >= 100 Then
Mess ageB ox.Sh ow("l OO scor es have been
ente red." , "No more room .")
Else
grade s(num Grad es) = Cint (txtS core .Tex
t)
numG rades += 1
lstO utpu t.Ite ms.C lear( )
txtSc ore.C lear( )
txtSc ore . Focu s ()
End If
End Sub

Priv ate Sub btnD ispla y_ Click ( . .. )


Hand les btnD ispla y . Click
'Disp lay avera ge of grad es and the
numb er of abov e avera ge grad es
Dim temp () As Integ er = grad es
ReDim Pres erve temp (num Grad es - 1)
lstO utpu t.Ite ms . Clea r()
lstO utpu t.Ite ms . Add( "The avera ge grad
e is " &
Form atNu mber (temp .Ave rage, 2) & ".")
lstOu tput.I tems .Add (Num Abov eAve rage(
temp ) &
" stud ents score d abov e the aver age."
End Sub )

Func tion NumA boveA verag e(ByV al temp


() As Integ er) As Integ er
'Cou nt the numb er of score s abov e the
avera ge grad e
Dim avg As Doub le = temp .Ave rage
Dim num As Integ er = 0
For Each grad e In temp
I f grad e > avg Then
num += 1
End If
Next
Retu rn num
End Func tion

63. Priv ate Sub btnD ispla y_ Click ( . .


. ) Hand les btnD ispla y.Cl ick
If IsCh ainL ink(t xtSe nten ce.T ext) Then
txtO utpu t.Tex t "This sente nce is a chai n-lin k sente
Else nce."
txtO utpu t.Tex t "This sente nce is not a chai n-lin k
End If sen tenc e."
End Sub

Func tion IsCh ainLi nk(B yVal sente nce


As Strin g) As Bool ean
'Ana lyze a sente nce to see whet her
it is a chai n-lin k sente n ce.
Dim word s(), endin g As Strin g
'Spl it the sente nce into word s, remo
ving comm as first
word s= txtSe nten ce.T ext.R epla ce(",
", "").S plit( " "c)
For i As Integ er = 0 To word s.Cou nt
- 2
If (wor ds(i) .Len gth< 2) Or (wor ds(i
+ 1) .Len gth< 2) Th e n
Retu rn False 'If any word has is less than two lette
End If rs.
endi ng= word s(i) .Sub strin g(wo rds(i
) .Len gth- 2) .ToU pper
ises
650 • Answ ers To Selec ted Odd -N umbe red Exerc

g(O , 2) .ToU pper Then


If endi ng< > wor ds(i + 1 ) .Sub strin
nnin g of next word .
Retu rn Fals e 'If endi ng does not matc h begi
End If
Next
is a cha in-l ink sent ence .
Retu rn True 'If all word s are ok, then it
End Fun ctio n

a.... 7.1 Exerc ise 63


l=.l@] /w~~J
estimable legions .
Sentence : Broad cast station . once certified . educates

This sentence is a ch a in~ ink sentence .


Analyze Sentence

EXERCISES 7.2
5. 6 7. 103 9. 8
1. 5 3. goin g
7 offe r
can 't

13. 15
11. 3 stud ents have a grad e of 100 12

st grad e is 80
15. The aver age afte r drop ping the lowe
17. 37 is a prim e num ber
) Han dles btnD ispl ay.C lick
19. Priv ate Sub btnD ispl ay_ Clic k( ... 10, 21}
8,
Dim num s() As Inte ger = { 3, 5,
Dim quer y = From num In nums
Whe re num Mod 2 = 0
Sele ct num
" even num bers "
txtO utpu t.Te xt = quer y.co unt &
End Sub

a_. 7.2 E ·e rcise 2 l= I @J !-a ·-1


a 7.2 Exe rcise 19

Displa)' Output
Display Output

Contains a 19th centu r;• date .


2 even numbers

. . . ) Han dles btnD ispl ay.C lick


21. Priv ate Sub btnD ispla y_ Cl i ck(
eadA llLi nes( "Da tes.t xt")
Dim date s() As Stri ng= IO.F ile.R
Dim quer y = From yr In d ates t(yr ) <= 1899 )
Whe re (Cin t(yr) >= 1800 ) And (Cin
Sele ct yr
If quer y.Co unt > 0 Then
txtO utpu t.Te xt "con tain s a 19th cent ury date ."
Else date ."
txtO utpu t.Te xt "doe s not con tain a 19th cent ury
End If
End Sub
Answ ers To Selec ted O dd-N um bered Exerc ises
• 65 1

23. Priv ate Sub btnD ispla y Clic k(


... ) Hand les btnD ispla y.Cl ick
Dim nums () As Inte ge; = {2, 6, 4}
Dim quer y = From num In nums
Orde r By Arra y.Ind exOf (num s, num)
Desc endi ng
For Each num As Inte ger In quer y
lstO utpu t.Ite ms.A dd(n um)
Next
End Sub

a...J
~
7. Exerc i e 25 l= I §l I~ ·:~J
ll ~ 7 2 Exerci se 23 l= l·§l I~ J
( Display Super Bowl ~'inners
]
I Display Output
) 49ers
Bears
;.

lA
6
Bronc os
Buccaneers
u
Chiefs ....

25. Priv ate Sub btnD ispla y_ Clic k(


.. . ) Hand les btnD ispla y.Cl ick
Dim team s() As Stri ng= IO.F ile.R
eadA llLin es("S BWi nner s.txt ")
Dim quer y = From team In team s
Orde r By team Asce ndin g
Dist inct
For Each team As Strin g In quer y
lstO utpu t.Ite ms.A dd(t eam )
Next
End Sub

27. Dim team Nam es() As Stri ng= IO.F


ile.R eadA llLin es("S BWi nner s.txt ")
Priv ate Sub btnD eterm ine_ Clic k( ...
) Hand les btnD eterm ine.C lick
'Dis play the numb er of Supe r Bowl
s won by the team in the text box
Dim quer y = From team In team Name
s
Wher e team .ToU pper = txtN ame. Text
.ToU pper
Sele ct team
txtNu mWo n.Tex t = CStr (que ry.C ount
)
End Sub

29. Priv ate Sub btnD ispla y_ Clic k(


. . . ) Hand les btnD ispla y.Cl ick
Dim quer yl =Fro m grad e In IO.F
ile.R eadA llLin es(" Fina l.txt ")
Sele ct Cint (gra de)
Dim avg As Doub le = quer yl.A vera
ge
Dim quer y2 From grad e In IO.F ile.R eadA llLin
es(" Fina l . txt" )
Wher e Cint (gra de) > avg
Sele ct grad e
txtA vera ge.T ext = Form atNu mber (avg)
txtAb oveA ve . Text = Form atPe rcen t(que
ry2 . Coun t I quer yl.C ount )
End Sub

31. Priv ate Sub btnD ispla y_ Clic k(


. .. ) Hand les btnD ispla y . Clic k
Dim stat es() As Stri ng= IO.F ile.R
eadA llLin es(" Stat es.tx t")
ReDi m Pres erve stat es(l 2)
Dim quer y = From stat e In stat es
Orde r By stat e
Sele ct stat e
cises
652 • Answers To Se lecte d Odd -N um be red Exer

quer y
For Each stat e As Stri ng In
lstO utpu t .Item s.Ad d(st a t e)
Nex t
End Sub

a 7.2 Exercise 3_ l = I @l l-t3 ·tl

Display States
a 7.2 Exercise 29 l = I @) 1•·..-tJ .J
Connecticut
Delaware
Evaluate Grades Georgia
Maryl and
Average grade : 83.25 Mass achusetts
Ne'N Hampshire
54 . 1 7~~ New Jersey
Percentage abov e average :

lick
k( ... ) Han dles btnD ispl ay.C
33. Priv ate Sub btnD ispl ay_ Clic ines ("U SPr es.t xt")
From pres In IO.F ile.R ead AllL
Dim quer y t
"c) .Las
Let lastN ame = pre s.Sp lit("
Ord er By lastN ame
Sele ct pres
For Each pres As Stri ng I n quer y
lstO utpu t.Ite ms. Add (pre s)
Nex t
Dis tinc t
End Sub

a 7.2 Exercise 33 l = I @) I~ _:d

Display Presidents

John Adams
John Q. Adams I]
Chester Arthur
James Buchanan
Martin Van Buren
George H. W . Bush
George IN. Bush

ns.t xt")
IO.F ile.R ead AllL ines ("N atio
35. Dim nati ons () As Stri ng=
. . . ) Han dles MyB ase . Load
Priv ate Sub frmN atio ns _ Load (
ons
lstN ati ons. Dat aSo urce = nati
ons .Sel ecte dite m = Not hing
lstN ati
End Sub
Tex tCha nged
nged ( ... ) Han dles txtN atio n .
Priv ate Sub txtN atio ns_ Tex tCha
Dim quer y From nati on In nati ons
atio n . Tex t)
Whe re nati on.S tart sWi th(t xtN
Sele ct na ti on
lstN ati ons . Data Sou rce = que ry.T oLi st
hing
lstN atio ns. Sele c tedi tem = Not
End Sub
Answers To Selected O dd-N umbered Exercises • 653

Private Sub lstNations_ Click( ... ) Handles lstNations . Click


txtNation.Text = lstNations . Text
End Sub

EXERCISES 7.3
1. The are a of a football field is 19200 square yards .
3. Duke was founded in NC in 1838. 5. heights are same
170

7. Joe: 88 9. Mr . President liv es in Washington, DC


Mo e: 90
Roe: 9 5

11. In the event procedure, peace should be prize. peace and yr should be prize. y r .
13. The condition {game1 > game2) is not va lid. Structures can only be compared one field
at a t ime.
15. The cities in Texas, along with their populations. T he cities are ordered by the size of
the ir populations beginn ing with the most popu lous city.

a 7.3 E erci::;e 15

Display Oties in Tex.as


D:;' 7.3

Display Population Increase for


Phoenix

17. The populat ion growth of Phoenix fro m 2000 to 2010.


19. structure State
Dim name As String
Dim abbreviation As String
Dim area As Double
Di m pop As Double
End Structure

Dim states ( ) As State

Private Sub frmStates _ Load( .. . ) Handles MyBase.Load


Di m stateRecords() As String= IO.File.ReadAllL ines("USStates.tx t")
Dim n As Integer = stateRecords.Cou nt - 1
ReD i m states (n )
Dim l ine As St r ing
Dim data() As Str i ng
Fo r i As Integer = 0 To n
line stateRecords(i )
data= line . Split ( ","c)
654 • Answer s To Se lected Odd-N um bered Exercises

states (i) .name = data(O)


states (i) .abbre viation = data(l)
states (i) .area = CDbl(d ata(2))
states (i) .pop= CDbl(d ata(3))
Next
End Sub

Private Sub btnF ind_ Click( .. . ) Handle s btnFin d.Click


Dim stateAb br As String = mtbAbb rev.Tex t .ToUpp er
Dim query = From state In states
Where state.a bbrevi ation = stateAb br
Select state.n ame, state.a rea
txtOut put.Te xt "The area of " & query. First.n ame & " is " &
Format Numbe r(query .First.a rea, 0) & "squar e miles. "
End Sub
re with the
21. (Begin with the code from Exercise 19 and rep lace the C lick eve nt procedu
followin g.)
lick
Private Sub btnDis play_ Click( ... ) Handle s btnDis play.C
Dim query From state In st ates
Let density = state.p op I state.a rea
Let format tedDen sity = Format Numbe r(densi ty, 2)
Order By density Descen ding
Select state.n ame, format tedDen sity
dgvOut put.Dat aSourc e = query . ToList
dgvOu tput.Cu rrentCe ll = Nothing
dgvOut put.Col umns(" name") . Header Text = "State"
dgvOut put.Co lumns( "forma ttedDe nsity") .Heade rText
"People per Square Mile"
End Sub

23. Structu re Player


Dim name As String
Dim team As String
Dim atBats As Double
Dim hits As Double
End Structu re

Dim player s() As Player

Private Sub frmBas eball _ Load( ... ) Handle s MyBase .Load


ball.tx t")
Dim playerS tats() As String = IO.File .ReadA llLines ("Base
Dim n As Intege r = player Stats.C ount - 1
ReDim players (n)
Dim line As String
Dim data() As String
For i As Intege r = 0 To n
line = player Stats(i )
data= line.S plit(", "c)
player s(i) .name = data(O)
player s(i) .team= data ( l)
player s(i) .atBats = CDbl(d ata(2))
player s(i) .hits= CDbl (data(3 ))
Next
Dim query = From person In player s
Order By person .team Ascend ing
Select person .team
Distin ct
lstTeam s . DataSo urce = query.T oList
End Sub
Answe rs To Selected Odd-N u mbered Exe rcises
• 655

Privat e Sub lstTea ms Select edinde xChan ged( ...


) Handle s
lstTea ms.Se lected indexC hange d
Dim selecte dTeam = lstTea ms.Te xt
Dim query = From person In player s
Where person .team = selecte dTeam
Order By perso n.hits Descen ding
Select person .name, perso n.hits
dgvOu tput.D ataSou rce = query . ToLis t
dgvOu tput.C urrent Cell = Nothin g
dgvOu tput.Co lumns( "name ") .Heade rText "Playe r"
dgvOu tput.C olumn s("hits ") .Heade rText "Hits"
End Sub

25. struct ure Playe r


Dim name As String
Dim team As String
Dim atBats As Double
Dim hi t s As Double
End Struct ure

Dim player s() As Player

Privat e Sub frmBa seball _ Load( . . . ) Handle s MyBas


e.Load
Dim playe rStats () As String = IO . File.R eadAl lLines
("Bas eball. txt")
Dim n As Intege r = player Stats. Count - 1
ReDim player s(n)
Dim line As String
Dim data() As String
For i As Intege r = 0 To n
line= playe rStats (i)
data= line.S plit(" ,"c)
playe rs(i) .name = data(O )
playe rs(i) .team = data(l )
playe rs(i) .atBat s = CDbl( data(2 ))
playe rs(i) .hits= CDbl( data(3 ))
Next
End Sub

Privat e Sub btnDis play_ Click( . . . ) Handle s btnDis


play . Click
Dim query From person In player s
Let ave = perso n.hits I person .atBat s
Select ave
Dim best As Double = query. Max
txtBes tAvera ge.Tex t = Forma tNumb er(best , 3)
Dim query2 = From person In player s
Where person . hits I person .atBat s best
Select person .name , person .team
dgvOu tput.D ataSou rce = query2 .ToLis t
dgvOu tput.C urrent Cell = Nothin g
dgvOu tput . Column s ("name " ) .Heade rText "Playe r"
dgvOu tput . Colum ns("tea m") .Heade rText "Team"
End Sub

27. struct ure Justic e


Dim firstNa me As String
Dim lastNa me As String
Dim apptPr es As String
Dim state As String 'state abbre viatio n
Dim yrApp ointed As Double
Dim yrLef t As Double
End Struct ure
656 • Answ ers To Select ed Odd -Numb ered Exe rcises

Dim j usti c e s ( ) As Justi ce

les MyBa se . Load


Pr iva t e Sub frmJu stice s _ Load( . .. ) Hand
Strin g= IO.F ile.R eadA llLin es("J ustic es.tx t")
Dim j u sti ceRe cords () As
t - 1
Dim n As In teger = justi ceRec ords. Coun
ReDim justi ces(n )
Dim line As Strin g
Dim data( ) As Strin g
For i As I n t eger = 0 To n
line= justic eRec ords( i)
data = l ine.S plit ( " , "c)
justi c e s(i) .f i rstNa me = data( O)
justi c e s( i ) .lastN ame = d ata(l )
justi ces( i) .appt Pres = data( 2)
jus t ices (i) .stat e = data( 3)
justi c es( i ) .yrAp point ed = CDbl (data (4))
jus t ices( i ) . yrLe ft = CDbl (data (S))
Next
En d Sub
les btnD ispla y.Cli ck
Pri vate Su b btnD ispla y_ Click ( .. . ) Hand
Dim query From perso n I n justi ces
Where perso n. y rLeft = 0
Order By perso n.yr Appo inted
Name
Selec t perso n . firstN ame & " " & perso n.last
lstOu tput. DataS ourc e = query .ToL ist
lstOu t p ut. Selec tedite m = Nothi ng
End Sub

II 7.3 Exercise 27 l= I@J " S2. .I

( Display Justices )
John Stevens
Jlvitonin Scalia
Anthony Kenned y
Oarenc e Thoma s
Ruth Ginsbu rg
Stephen Breyer
John Roberts
~muel Alito
nia Sotomayor

e th e C lick event proce dure with th e


29. (Begi n with th e code from Exerc ise 27 and replac
fo llowin g. )
les btnD ispla y.Cli ck
Priva te Sub btnD isplay _ Click ( ... ) Hand
Dim q u ery From perso n In j ustic es
Where perso n.sta te = mtbS tate.T ext
& perso n.last Name
Let fullN ame = perso n.firs tNam e & " "
on . yrAp point ed, perso n.yrL eft )
Let yrs = Years Serve d (pers
= perso n . apptP res.S plit( " "c) .Last
Let presL astNa me
Selec t fullN ame , presL astNa me, yrs
If que ry .Coun t = 0 Then
from that state .", "NONE")
Mess a geBox .Show ("No justi ces appo inted
mtbS t ate. Focus ()
Answ ers To elected Odd -N umbe red Exer
cises • 657
Else
dgv Out put. Data Sou rce = que ry.T
oLi st
dgv Out put. Cur rent Cell = Not
hing
dgv Out put. Colu mns ("fu llNa me"
) . Hea derT ext = "Ju stic e"
dgv Out put. Colu mns ("pr esLa stNa
me" ) .Hea derT ext = "Ap poin ting
dgv Out put. Colu mns ("yr s") .Hea Pre side nt "
derT ext = "Ye ars Serv ed"
End If
End Sub

Fun ctio n Yea rsSe rved (ByV al


ente r As Dou ble,
ByV al leav e As Dou ble) As Dou
If leav e = 0 Then ble
Retu rn (Now .Yea r - ente r)
Else
Retu rn (lea ve - ente r)
End If
End Fun ctio n

ll _. 73 Exerci:;e 3_ l= I @J 1-&S ·"l


Da'l Numb er: 3
I Display Gifts )
~e giCe o ' " ' d•> 3 .ar e
parr ;rid ge in a p e ar 'Gt ee
'Gl.l.Z::tl e do'f;,..e3
3 Fr e nch h e n3

j co3 t ~or day 3: $ 260 . 97


Iota l cost ~or r;he ~ir3t
3 da ~{ .3 : :Hi% . 93

31. stru ctur e Day


Dim num As Inte ger
Dim pres ent As Stri ng
Dim pric e As Dou ble
End Stru ctur e

Dim day s() As Day

Pr ivat e Sub frmX mas _ Load ( ...


) Han dles MyB ase.L oad
Dim gift s() As Stri ng= IO.F
ile.R ead AllL ines ("G ifts .txt ")
Dim n As Inte ger = gift s.C oun
t - 1
ReD im day s(n)
Dim data () As Stri ng
For i As Inte ger = 0 To n
dat a= gift s(i) .Sp lit( ","c )
day s(i) .num = Cin t(da ta(O ))
day s(i) .pre sen t = data (l)
day s(i) .pri ce= CDb l(da ta(2
))
Nex t
End Sub
d Exe rcises
658 • Ans wer s To Se lected Odd - um bere

btn Dis pla yG ifts .Cl ick


ifts Cli ck( ... ) Han dle s
Pri vat e Sub btn Dis pla yG
rn.T ext)
Dim dayN urn = Cin t(tx tDa yNu
Dim cos t As Dou ble = 0
= 0
Dim tota lCo st As Dou ble
lstO utp ut.I tem s.C lea r()
urn & " are ")
e gif ts for day " & dayN
lstO utp ut.I tem s.A dd( "Th
(day Nur n - 1)
For i As Int ege r = 0 To .pr ese nt)
lstO utp ut. Item s . Add (da ys( i) .nur n & " " & day s(i)
s(i ) .pr ice
cos t+= day s(i) .nur n * day
tota lCo st += day s(i) .nur n * day s(i) .pr ice *
(day Nur n + 1 - day s (i) . nurn)
Nex t
ls tOu tpu t.I tem s.A dd( "") ": " &
st for day " & dayN urn &
lstO utp ut . Item s.A dd( "Co
For ma tCu rren cy( cos t))
" & dayN urn &
ta l cos t for the fir st
lstO utp ut . Item s.A dd( "To tCu rren cy( tot alC ost ))
"da ys: " & For rna
End Sub

33. Str uct ure Far nou sPe rson


Dim nam e As Str ing
Dim dat eOf Bir th As Dat e
End Str uct ure

Far nou sPe rson


Dim farn ous Per son s() As
ad
d ( ... ) Han dles My Bas e.Lo
Pri vat e Sub frrn Farn ous _ Loa s("F arn ous .txt ")
IO. File .Re adA llL ine
Dim peo ple () As Str ing =
.Co unt - 1
Dim n As Int ege r = peo ple
ReD im farn ous Per son s(n)
Dim lin e As Str ing
Dim dat a() As Str ing
n
For i As Int ege r = 0 To
lin e = peo ple (i)
dat a = lin e.S pli t(" ,"c )
dat a(O )
farn ous Per son s(i) .na me =
.da teO fBi rth = CD ate (da ta(l ))
f arn ous Per son s(i)
Nex t
End Sub
pla y .C lic k
Cli ck( .. . ) Han dles btn Dis
Pr iva te Sub btn Dis pla y _ Per son s
From per son In fam ous
Dim que ry >= #1/ 1/1 970 #) And
Whe re (pe rso n.d ate OfB irth
1/1 980 #)
(pe rso n.d ate OfB irth < #1/
Sel ect per son .nar ne
lstO utp ut.D ata Sou rce = que ry.T oLi st
= Not hin g
lstO utp ut.S ele cte dite m
End Sub

35. Dim peo ple () As Per son


ad
d( . . . ) Han dles My Bas e.Lo
Pri vat e Sub frm Farn ous Loa o the arr ay peo ple .
h per son int
'Pla ce the dat a for eac arn ous .txt ")
IO . File .Re adA llL ine s("F
Dim gro up( ) As Str ing =
Cou nt - 1
Dim n As Int ege r = gro up.
ReD im peo ple (n)
Dim dat a() As Str ing
Answers To Selecred Odd -N umbered Exercises • 659

For i As Integer = 0 To n
data= group(i) .Split(","c)
people(i) .name = data(O)
people(i) .dateOfBirth = CDate(data(l))
Next
End Sub

Private Sub btnDisplay_ Click( .. . ) Handles btnDisplay.Click


Dim query From individual In people
Let ageinDays = FormatNumber(Da teDiff(Dateinterva l.Day,
individual . dateOfBirth, Today), 0)
Let dayOfBirth = DayOfWeek(indivi dual .da teOfBirth)
Where individual.date0f Birth.AddYears(4 0) <=Today And
individual.dateOf Birth.AddYears(S O) > Today
Select individual.name, ageinDays, dayOfBirth
dgvOutput.DataSo urce = query.ToList
dgvOutput.Curren tCell = Nothing
End Sub

Function DayOfWeek(ByVal d As Date) As String


Dim dl As String= FormatDateTime(d , DateFormat.LongD ate)
Dim d2() As String= dl.Split(","c)
Return First
End Function

IJ ~ 7.3 Exercise 35

Display Table

name age In Days dayOfBirth


Michael Dell 16. 0 Tuesday
Barack Obama 17.703 Friday
Conan 0 Brien 17, 91 Monday
Sean Penn 18.055 1/lfednesday
Will Smith 15. 9 1/1/ednesday
Renee Zellweger 1 ,882 Friday

37. Private Sub btnDisplay_ Click( . .. ) Handles btnDisplay .Cl ick


lstOutput.Items.C lear()
For i As Integer = 0 To club.Count - 1
If club(i) .courses.Count = 3 Then
lstOutput . Items.Add(club(i ) .name)
End If
Next
End Sub

39. Private Sub btnDisplay_ Click( ... ) Handles btnDisplay.Click


'Displays the students who are not enrolled in CMSC 100
Dim subject = "CMSC 100 11

Dim ub = club . Count - 1


Dim checkList(ub) As Boolean
For i As Integer = 0 To ub
For j As Integer = 0 To club(i) .courses.Count - 1
660 • Answers To Selected Odd -N um bered Exercises

If club(i) .courses ( j ) subject Then


checkList( i) = True
End If
Next
Next
Fo r i As In teger = 0 To ub
If Not checkL i st( i) Then
lstOu tput . Items . Add(cl ub(i ) .name)
End If
Ne xt
End Sub

EXERCISES 7.4

1. 1 3. 3 5. 55 7. 14 9. 2 11. 55

13. Dim twice(2, 3 ) As Double


For r As Integer = 0 To 2
For c As Integer = 0 To 3
twice(r, c) = 2 * nums (r , c )
Next
Next

15. 'use a For Each l oop


Dim total As Double = 0
For Each num As Double I n n ums
If num Mod 2 = 0 Then
total += num
End If
Next
ls t Output.Ite ms . Add(total)

'us e LINQ
Dim query From num In nums .Cast(Of Double)()
Where (num Mod 2 = 0)
Select num
lstOutput .Items . Add(query. Sum)

Display Resu~s I

17. 12
19. Private Sub btnDisplay _ Cli ck ( . .. ) Handles btnDisplay . Click
'Display a company' s inven tory from its two stores
Dim inventory ( , ) As Intege r = {{25, 64, 23}, {30 , 82, 19}}
Dim sales(, ) As Intege r = {{7 , 45, 11}, {4, 24, 8}}
Dim total(2 ) As I n teger
'Adjust the inventory val u es to reflect today's sales
For store As Intege r = 1 To 2
For item As Integer = 1 To 3
inventory (s t ore - 1 , i t em - 1)
An swers To Se lected O dd -N umbere d Exe rc ises
• 66 1

inven tory(s tore - 1, item- 1) - sales( store


- 1, item - 1)
'Accum ulate the total invent ory per store
total( store) += inven tory(s tore- 1, item- 1)
Next
Next
' Di splay the store 's invent ory and totals
lstOut put. Items .Add (" 1 2 3 TOTAL")
For store As Intege r = 1 To 2
lstOut put . Items . Add(s tore & " " & inven tory(s tore - 1, 0) &
" & inven tory(s tore 1, 1) & " " &
invent ory ( store - 1, 2) & " " & total ( store) )
Ne x t
End Sub

a.,. 7. Exercise 21

Display Enrollment Data


1
CAI-!P

30
6
s E.lROL LHENT
l
_ 96
E ·L LU1EH
_g
50
a.. 7.4 E){ercise 19 l= I@) 1- £1 J 05
g
69
Display Inventory per Store and ~ em ... 6

I _3
2 3
IOAL 5
9 49
li_ 26 52 .1 95
5

J
21. Pr ivat e Sub btnDis play_ Click ( .. . ) Handle s btnDi
splay. Click
'Displ ay the course and c ampus enroll ments
'enrol lment array named er
Dim er(,) As Int e ger= {{5, 15, 22 , 21, 12, 25,
16, 11, 17, 23},
{11 , 2 3 , 51, 25, 32, 35, 32, 52, 25, 21},
{2, 12 , 32, 32, 25, 26, 2 9, 12 , 15, 11}}
'Def i ne the a r ray s to accum ulate the inform ation
Dim campu sTotal (2) , course Total( 9) As Intege r
For campus As Intege r = 0 To 2
For course As Intege r = 0 To 9
campu sTotal (c ampus) += er(cam pus, course )
c ourseT otal (cours e) += er(cam pus , course )
Next
Next
'Displ ay the campus enroll ment
l s tOutpu t . Items . Add ("CAMPUS ENROLLMENT")
For campus As Intege r = 0 To 2
lstOut put.Ite ms.Ad d((cam pus + 1) & ": " & campu
sTotal (camp us))
Next
' Displa y the course enroll ment
662 • A nswers To Se lected Odd -Numbered Exercises

l stOut pu t. Items. Add(" COUR SE ENROLLMENT")


For cours e As Integ er = 0 To 9
cours eTota l(cou rse))
lstOu tp ut . Items . Add(( cou rse + 1) & ": " &
Next
End Sub
es btnDi splay .Click
23. Pri vate Sub btnDi splay_ Clic k ( . . . ) Handl
'Load go lf data , cumul ate total s, and displ a y resul ts
Dim sc ores( 3 , 3) As Integ e r
Dim gol f er s(3) As Strin g
s("Go lf.txt" )
Dim tab le() As Strin g= I O.Fil e . ReadA llLine
Dim d a t a () As Strin g
3) As Integ er
Di m golfe rTota l(3) As Int e ger, round Total(
For i As I ntege r = 0 To 3
dat a = t able( i) .Spli t(" , "c)
golf e rs( i) = data ( O)
For j = 0 To 3
scor es( i, j) = Cint(d a ta(j + 1))
Next
Next
For g o lfer As Integ er = 0 To 3
For r ound As Integ er = 0 To 3
)
golfe rTota l (golfe r) += score s(gol fer, round
r o u n d Total (roun d) += score s(gol fer, round )
Next
Next
'Disp lay golfe r ' s tota l s
lstOu tpu t .Item s . Add("G OL FER TOTALS")
For go l fe r As Integ er = 0 To 3
& golfe rTota l(gol fer))
lstOu tput . Items . Add (go l fers(g olfer) & ": "
Next
lstOu tput. Items .Add( "" )
'Disp l a y a v erage per roun d
lstOu tput. Items .Add ( "ROUND AVERAGE")
For round As Integ er = 0 To 3
ls t Outpu t . Items .Add( rou nd + 1 & ": " &
Forma t Numb er(rou ndTot al(rou nd) I 4))
Next
End Sub

Exercise 23

Analyze Go~ Scores

GOLF::: ;< I IJ!.lS


:::un Hee - i: 284
Candi e Kung: 285
In - K~~ng Kim: 286 o_. 7.4 Exercise 25
Crist i e Ke rr: 286
University: Stanford
;<. IDD =' .:. ;<AG:::
1: 0- 5
Display High-Ranking Divisions
2: 72. 7"6
3: 0.50
4: 1.25 Education Engineering Law

es btnD i splay . Click


25. Priva t e Sub btnDi splay _ Cl i ck( .. . ) Handl
Dim r ank ing(2 , 4 ) As St r ing
Ans wers To Sele cted Odd -Num bere d
Exercises • 663
Dim disc ipli nes (2) As Stri ng
Dim tabl e() As Stri ng= IO.F
ile . Rea dAl lLin es(" Ran king .txt"
Dim data () As Stri ng )
For fiel d As Inte ger = 0 To
2
dat a= tabl e(fi eld) .Sp lit( ","c
)
disc ipli nes (fie ld) = data (O)
For rank As Inte ger = 0 To 4
ran kin g(fi eld, rank ) = data (ran
k + 1)
Nex t
Nex t
Dim resu lt As Stri ng = ""
For cate gory As Inte ger = 0
To 2
For rank As Inte ger = 0 To 4
If txtN ame .Tex t.To Upp er = rank
ing( cate gory , rank ) .ToU pper
'App end cate gory name to resu Then
lt
resu lt &= disc ipli nes (cat ego
ry) & "
End If
Nex t
Nex t
If resu lt = "" Then
txtO utpu t.Te xt "No ne."
Else
txtO utpu t.Te xt resu lt
End If
End Sub

27. Dimsco res( l4, 4) As Inte ger


'Sto res stud ents ' exam scor es
Dim cou nt As Inte ger
'Cur rent num ber of stud ents
Dim nam es ( l4) As Stri ng stor ed
'Sto res stud ents ' nam es
Priv ate Sub btnA dd_ Clic k( ..
. ) Han dles btnA dd.C lick
If (cou nt = 15) Then
Mes sage Box . Sho w(" Fift een stud
ents alre ady stor ed." , "Wa rnin
Else g")
cou nt += 1
nam es ( cou nt - 1 ) = txtN ame
.Tex t
scor es(c oun t 1, 0) Cin t(tx tExa ml.T ext)
scor es(c oun t 1, 1) Cin t(tx tExa m2. Tex t)
scor es(c oun t 1, 2) Cint (txtE xam 3 . Tex t)
scor es(c oun t 1, 3) Cin t(tx tExa m4. Tex t)
scor es(c oun t 1, 4) Cin t(tx tExa mS. Tex t)
' Res et inpu t
txtN ame .Cle ar()
txtE xam 1.Cl ear( )
txtE xam 2.Cl ear ( )
txtE xam 3.Cl ear( )
txtE xam 4 . Cle ar ( )
txtE xam S . Cle ar ()
txtN ame .Foc us()
End If
End Sub

Priv ate Sub btnD ispl ay_ Clic k(


. .. ) Han dles btnD ispl ay.C lick
Dim sum As Dou ble , even As Boo
lean
lstO utpu t.Ite ms. Cle ar()
lstO utpu t.Ite ms . Add ("Se mes ter
Ave rage s")
For i As Inte ger = 0 To c oun
t - 1
sum = 0
For exam As Inte ger = 0 To 4
sum += sco res( i, exam )
Nex t
Exercises
664 • Answer s To Se lected O dd -N umb ered

um 1 S))
) & ": " & Form atN umb er(s
lstO utp ut.I tem s.A dd( nam es(i
Nex t
s
' Dis pla y med ian on the exam
I tern s. Add ("Ex am Med ians ")
1 s tOu tpu t.
cou nt I 2)
eve n= (In t(co unt I 2) =
0 To 4
For exam As Inte ger =
+ 1 & ": " &
lstO utp ut.I tem s.A dd( exa m , eve n))
Me dian (sco res, cou nt, exam
Nex t
End Sub

Name : Exam 1:
Exam 2:
Add Student
Exam 3:

Exam :
Display Report
Exam 5:

en:es-cer Av era ges 1 7.4 Exercise 29

~
c'"'

ary : 32 . 6
_ _ _ : gs . 6 Displ ay Sales
cot t : S3 . _
xarr. Hed ia.:J s I Sa _ es per sto re
- · g2 1 : &3, 6 _8 . 30
2 : 90
2 : &11 ,2 5 . 9
3: =7 3 : 59, _ 07 . 4
4 : 82 1
:ot a _ sa es : S29 ,u _ . 6J
5 : <>'

ck( ... ) Han dles btn Dis pla y.C lick


29. Pr iva te Sub btn Dis pla y_ Cli cum ulat e tot als , and dis pla y a rep ort
' Loa d dat a intoan arra y,
Dim tota lSa les As Dou b l e 45, 14} ,
{{2 5, 64, 23,
Dim sal es( ,) As Int ege r= 34, 63} ,
{12 , 82, 19,
{54 , 22, 17, 43, 35} }
ble = {12 , 17. 95, 95, 86. 5, 78}
Dim pric e() As Dou
' Cum ulat e tot als
Dim tota ls(2 ) As Dou ble
To 2
For sto re As Inte ger = 0
For item As Inte ger = 0 To 4
re, item ) * pric e(it em )
tota ls(s tor e) += sal es( sto
Nex t
Nex t
gra nd tot al in tota ls(O )
'Di spla y rep ort, sto rin g
les per sto re" )
lstO utp ut.I tem s.A dd( "Sa
= 0 To 2
For sto re As Inte ger cy( tota ls(s tore )))
tem s . Add ( sto re + 1 & ": " & For ma tCu rren
lstO utp ut.I
e)
tota lSa les += tota ls(s tor
Nex t cy( tota lSa les) )
sal es: " & For mat Cur ren
lstO utp ut.I tem s.A dd( "To tal
End Sub
Answer s To Selected Odd-N umbered Exercises
• 665

C H APTER 8
EXERCISES 8.1
1. Samuel Alito,N J 3. Alito was appoin ted by Bush
Henry Baldwi n,PA Baldwi n was appoin ted by Jackson

5 . Alito,S amuel, 2006


Baldwi n,Henr y,l830

7. T he new file contains the full names of the justices whose last name begins
with the letter
Band the years they were appo inted to the court. The justices are ordered
by the year they
were appo inted.
9. The new file is the same as the original file except that the last three fields
have been
de leted from each record.
11. T he new fi le con ta ins the names of the people who subscrib
e to either the New Yo rk
Times or the Wall Street Journal, or both.
13. T he new file conta ins the names of the people who subscribe to the New
York Times but
not the Wall treet Journal.
15. Privat e Sub btnBot h_ Click( ... ) Handle s btnBot h.Click
'Create a file of presid ents who were also vice presid
ents
Dim vicePr es() As String = IO.File .ReadA llLines ("VPre
s.txt")
Dim presid ents() As String = IO . File.Re adAllL ines("U
SPres.t xt")
Dim both() As String = presid ents.In tersect (viceP res)
.ToArra y
IO.File . WriteA llLines ("Both .txt", both)
Messag eBox.S how(bo th . Count & " presid ents", "File Created
")
End Sub

a~ 8. Exe rcise 17

Create a File Containing the Presidents Presidents Or "\;ke Presidents


who •.-.•ere also Vice-Presidents But Not Both

17. Privat e Sub btnXor _ Click( ... ) Handle s btnXor .Click


'Create a file of people who were pres or VP but not
both
Dim vicePr es () As String = IO . File. ReadAl lLines ( "VPres
. txt")
Dim presid ents() As String = IO.File .ReadA llLines ("USPr
es.txt" )
Dim eitherO r() As Str i ng = preside nts.Un ion(vic ePres)
.ToAr ray
Dim both( ) As String = presid ents.In tersect (viceP res)
.ToArra y
Dim exclus iv eOr() As String = eitherO r.Exce pt(both ) .ToArra
y
I O.File .Write AllLin es("Xo r.txt" , exclusi veOr)
Messag eBox . Show(e xclusiv eOr.Co unt &
" presid ents or vice presid ents, but not both" , "File
Created ")
End Sub

19. Dim countr ies () As String = IO. File . ReadAl lLines ("UN
. txt")
'lstCon tinents was filled at design time
Privat e Sub lstCon tinents Selecte dindex Change d( ... )
Handle s
lstCon tinents .Select edinde xChan ged
Dim selecte dConti nent As String = lstCon tinents . Text
If selecte dConti nent = "Antar ctica" Then
666 • Answe rs To Selecte d Odd-N umbered Exercises

lstCo untrie s.Dat aSour ce = Nothi ng


Antar ctica. ")
Messa geBox . Show( "There are no count ries in
Else
Di m query From natio n In count ries
Let data= natio n.Spl it("," c)
Let name = data(O )
Let conti nent = data( l)
Where conti nent = select edCo ntine nt
Selec t name
lstCo untrie s.Dat aSour ce = query .ToLi st
lst Count ries.S electe ditem = Nothi ng
End If
End Sub

a~ 8.1 Exercise 19
l = I @] 1-fA · J

Oick on the name Antigua and Barbuda


of a continent : Bahamas
Barbados
..Airica Belize L
Antarctica Canada
Asia Costa Rica
Australia / Oceania Cuba
Euro~ Dominica
l~tMl;r41u@U$ Dominican Republic
South .America
L....:.--'-..-'- '-'....:....:..:_ ____, I B Salvador

es btnDi splay .Click


21. Priva te Sub btnDi splay_ Click ( ... ) Handl
Di m citie s() As Strin g= IO . File.R eadA llLine s("Ci ties . txt")
Dim query = From city In citie s
Let data= city.S plit(" ,"c)
Let pop20 10 = CDbl( data(3 ))
Order By pop20 10 Desce nding
Selec t pop20 10
Dim pops( ) As Doub le= query .ToAr ray
ReDim Prese rve pops( 9)
um, 0)
txtOu tput.T ext = Forma tNumb er(lOO OOO * pops.S
End Sub

a:.. 8.1 Exercis e 21

Display Sum of the 2010 Populations


of the Ten Largest Cities

25.1 24 .000

es btnDi splay .Click


23. Priv ate Sub btnDi splay_ Click ( ... ) Handl
Di m state s() As Strin g = IO.Fi le.Re adAll Lines ("USS tates. txt")
Dim query = From line In state s
Let name= line.S plit(" ,"c) (0) .ToUp per
Let abbre v = line.S plit(" ,"c) (1)
Where Not name . Starts With( abbre v)
Order By name Ascen ding
Selec t abbre v, name
Answ ers To Selected O dd -N umbered Exe rci es
• 667

dgvO utput .Data Sourc e = query .ToL ist


dgvO utput .Curr entCe ll = Nothi ng
dgvO utput .Colu mns(" abbre v") .Head erTex
t = "Stat e Abbr eviat ion"
dgvO utput .Colu mns(" name ") . Head erTex t
"Stat e"
End Sub

Display States and . bbreviations


Display States Ordered by Land Area

State
State
r
Percentage of ,..
Abbreviation I ., State
Total Area
AK ALASKA. aska 15.9 i:

AZ ~ RIZON " Texas 7.31 ~~


CT CONN ECTICUT Califomia - .3 o,,,
GA GEORGI Morrtana ... .1 :,,.-
HI H.A.l/1/AII New Mexico 3 . 39 ~~

25 . Priv ate Sub btnD ispla y_ Click ( ... )


Hand les btnD ispla y.Cli ck
Dim state s() As Strin g= IO.F ile.R eadA
llLin es("U SStat es.tx t")
Dim query l = From line In state s
Let area = Cint( line. Spl it (" , "c) (2))
Selec t area
Dim total Area = query l.Sum
Dim query 2 = From line In state s
Let name = line. Split (","c ) (0)
Let area = Cint (line .Spli t("," c) (2))
Let perce ntAre a = Form atPer cent( area
I t otalA rea)
Order By area Desce nding
Selec t name, perce ntAre a
dgvO utput .Data Sourc e = query 2.ToL ist
dgvO utput .Curr entCe ll = Nothi ng
dgvO utput .Colu mns(" name ") .Head erTex t
= "Stat e"
dgvO utput . Colum ns("p ercen tArea ") .Head
erTex t
"Perc entag e of Total Area"
End Sub

27. Priva te Sub btnU pdate Click ( . . . ) Hand


les btnUp da te .Clic k
Dim color s() As Strin g= IO.F ile . Read
AllLi nes(" Pre19 90Co lors . txt")
Dim retir ed() As Strin g= IO.F ile.R eadA
llLin es("R etire dCol ors.tx t")
Dim added () As Strin g= IO.Fi le.Re adAl
lLine s("Ad dedC olors .txt")
Dim tempA rray( ) As Strin g= color s.Exc
ept(r etire d) . ToAr ray
Dim query = From color In tempA rray.C
oncat (adde d)
Order By color
Selec t color
IO.Fi le.Wr iteAl lLine s("Ne wCol ors . txt",
query )
End Sub

29. Pr i vate Sub btnC reate _ Click ( ... ) Hand


les btnC reate .Clic k
Dim justi ces() As Strin g= IO.F ile.R eadA
llLin es("J ustic es.tx t")
ise
668 • Answ ers To Se lected O dd -N umbe red Exerc

Dim que ry From just ice In just ices


Let data = just ice. Spl it(" ,"c)
Let first Nam e = data (O)
Let seco ndNa me = data (l)
Let pres = data (2)
Let yrAp pt = d a ta(4 )
Let yrL eft = d a ta(S )
me & " , " & pres & "," &
Sele ct firs t Name & "," & seco ndNa
yrAp pt & "," & yrL eft
sNo Stat e.tx t", quer y)
I O. File .Wr i teA llLi nes( "Jus tice
End Sub

ll _. 8.1 Exe rcise 27

C========Up=d=&=e=u=·&=o=f=C=olo=r=n =====~~ ==&


li==========Cre =e==R=Ie==========J

( . .. ) Han dles btnD ispl ay.C lick


31. Priv ate Sub b tnC r eate Clic k
' quer yl : a ll stat es; quer y 2 : stat es with just ices
")
Dim st a t e s () As Stri ng= IO . File . Rea dAl lLin es(" USS tate s.txt
ile.R eadA llLi nes( "Jus tice s.tx t")
Dim jus ti ces( ) As Stri ng= IO.F
es
Dim quer yl = From stat e I n stat
Let abb r e v = stat e . Spl it(" ,"c) (l)
Sele ct abbr ev
Dim quer y2 From just i c e In just ices
Let stat e= just ice . Spl it(" ,"c)
(3 )

Sele ct stat e
ces. txt" , quer yl . Exc ept( quer y2))
I O. F i le.W ri teAl lLin es ( "NoJ usti
End Sub

ll .,. 8. Exe rcise 33


D.,. 8.1 Exe rcise 31

~========er=e&=e=R=Ie========~~ ~~ =========er=e&=e=R=Ie========~
.txt" )
IO.F ile . Rea dAl lLin es(" Just ices
33. Dim just ices () As Stri ng=
Han dles Crea te . Clic k
Priv ate Sub Crea te_ Cl ick ( . . . )
Dim quer y From line In just ices
Let stat e= l ine. Spl it(" ,"c) ( 3)
Orde r By stat e Asce ndin g
fJus tice s(sta te )
Sele ct stat e & "," & Nwn berO
Dis tinc t
.txt" , quer y)
IO.F i l e . Wr i teAl lLin es(" New File
End Sub
stat e As Stri ng) As Inte ger
Fun ctio n Num berO fJus t i ce s(By Val
Dim que ry = From line In jus t ices
Let plac e= l ine. Spl it(" , "c) (3)
Whe re p lace = stat e
Sele ct plac e
Retu rn quer y . Coun t
End Func t ion
Answe rs To Se lected O dd -Numbered Exercises
• 669

35. Priva te Sub btnDi splay Click ( ... ) Handl es btnDi splay .Click
Dim query From state In IO.Fi le.Re adAll Lines ("USS tates.
txt")
Let data= state .Spli t(","c )
Let name = data(O )
Let abbre v = data( l)
Let area= Forma tNum ber(da ta(2), 0)
Let pop= Forma tNum ber(da ta(3), 0)
Order By name
Selec t name, abbre v, area, pop
dgvSt ates.D ataSo urce = query .ToLi st
dgvS tates. Curre ntCel l = Nothi ng
End Sub

a~ 8. _ ercise 35

Display Contents of Rle

name abbrev area pop ;.

.L h .7- c
A 571. 51
z 113.&35
R 5 ..
P.. 15 .~5
___,
Colorado co

EXERCISES 8.2
1. Hello 3 . Bon Jour 5. You must enter a numbe r.
7. Error occur red. 9. File Ages .txt conta ins an inval id age.
11 . The file W elco me.tx t is create d and ha the fo llowin g lines:
Hello
Bon Jour

13. The fi lespec Greet ings. txt should be delimi ted


with quotation marks .
15. There sh ould be no quotations around the variab le name
as th e argum ent to the
C reateT ex t metho d.
17. The variab le age is declared with in the Try-C atch -Fina lly
block. There fo re it has block-
leve l scope and is not ava ilable be low the line End Try.
19. Priva te Sub btnCr eate_ Click ( ... ) Handl
es btnCr eate.C lick
'Crea te a text file and popul ate it
Dim sw As IO.St reamW riter = IO . File . Creat eText
("Cow boy.tx t")
sw .Write Line( "Colt Peace maker ,l2 . 20")
sw.W riteLi ne("H olster ,2.00" )
sw.W riteLi ne("L evi Strau ss jeans ,l.35" )
sw.W riteLi ne("S addle ,40.00 ")
sw . Write Line( "Stets on , lO.OO ")
sw.Cl ose() 'Alwa ys close the write r when finish ed.
Messa geBox . Show( "The file has been creat ed.",
"Done ")
End Sub
670 • Answ ers To Select ed Odd-N umbered Exercises

a_. 8.2 Exercise 2

Create File I ,
I . __(_Add-~en_ to Fi_ile --J

~============~
les btnA dd.Cl ick
21. Priva te Sub btnAd d_ Click ( .. . ) Hand
'Appe nd item to a text fi l e
ndTe xt("C owbo y.txt" )
Dim sw As IO.St ream Write r = IO.F ile . Appe
,20.5 0 " )
sw.W riteL ine(" Winc heste r Rifle
sw.C lose ()
to the file .", "DONE")
Messa geBox .Show ("The item has been added
End Sub

D_. 8.2 Exerci se 25 l = I @] 1-.tJ: d

[ Display File ]
item cost
--
Co~ Peacem aker 12.20

a_. 8.2 Exercis e 23 l = I @] l..£5 l Holster 52.00

Levi Strauss jeans sus


~em : Price : Saddle 540.00

Add ~em to Ust Stetson S10.00

les btnA dd.Cl ick


23. Priva te Sub btnAd d_ Click ( . . . ) Hand
Dim item As Strin g
Dim price As Doub le
Dim sr As IO.St reamR eader IO. File .Open Text ("Cow boy. txt")
Dim sw As IO.St reamW rite r IO.Fi le.Cr eateT ext(" Cowb oy2.t xt")
Dim flag As Boole an = False
Dim line As Strin g = ""
Dim data( ) As Strin g
sr.En dOfS tream )
Do While (line < txtite m.Te xt) And (Not
line sr.Re adLin e
data = line. Split (","c )
item = data( O)
price = CDbl (data (l))
If item > txtite m.Te xt Then
atNu mber (txtP rice.T ext))
sw.W riteL ine(t xtitem .Text & "," & Form
again at the end
'Set flag to True s o we don't add it
flag = True
End If
sw.W ri teLin e(lin e)
Loop
Do Until sr.En dOfS tream
line = sr.Re adLin e
sw.W rit eLine (line )
Loop
If Not flag Then
atNu mber (txtP rice.T ext))
sw.Wr iteLi ne(tx titem . Text & "," & Form
End If
Answers To Se lecte d O dd-N umbe red Exe
rcises • 671

sr .Clo se ()
sw . Clos e()
Mes sage Box .Sho w("I tem adde d to
Cow boy2 .txt" )
txtit em. Clea r()
txtP rice .Cle ar ()
End Sub

25. Priv ate Sub btnD ispl ay_ Clic


k( ... ) Hand l es btnD ispl ay.C lick
Dim sr As IO.S trear nRea der = IO.F
ile.O penT ext( "Co wbo y.tx t")
Dim line s(4) As Stri ng
For i As Inte ger = 0 To 4
line s(i) = sr.R eadL ine
Nex t
Dim quer y = From line In line s
Let data line .Sp lit(" ,"c)
Let item = data (O)
Let cos t= Forr natC urre ncy( data
(l))
Sele ct item , cost
dgvO utpu t.Da taSo urce = quer y.To
List
dgvO utpu t.Cu rren tCel l = Noth ing
End Sub

27. Priv ate Sub btnD eterr nine _ Clic


k( ... ) Han dles btnD eter rnin e.Cl
Dim sr As IO.S trear nRea der = IO ick
. File .Ope nTe xt(" Nur nber s.txt ")
Dim coun ter As Inte ger = 0
Dim nurn As Dou ble
Do Unt il sr . EndO fStre arn
nurn = CDb l(sr. Read Line )
coun ter += 1
Loop
txtO utpu t.Te xt CSt r(co unte r)
sr.C lose ()
End Sub

a_. 8.2 Exercise 27 l= J§] I. -~


a::} 8.2 Exercise 29

Detennine Number of Numb ers


Calcu late Smallest Number
10

29. Priv ate Sub btnC alcu late Clic


k( ... ) Han dles btnC alcu late . Clic
Dim sr As IO.S trear nRea der = IO.F k
ile.O penT ext( "Nu rnbe rs.tx t")
Dim nurn As Dou ble
Dim min As Dou ble = CDb l(sr. Read
Line )
Do Unt il sr.E ndO fStre arn
nurn = CDb l(sr. Read Line )
If nurn < min Then
min = nurn
End If
Loop
txtO utpu t.Te xt CStr (min )
sr.C lose ()
End Sub

31. Priv ate Sub btnC alcu late _ Clic


k( ... ) Han dles btnC alcu late .Cli
Dim sr As IO.S trear nRea der = IO.F ck
ile.O penT ext( "Nu rnbe rs.tx t")
cises
672 • Answ ers To Se lected O dd-N umb ered Exer

Dim cou nter As Inte ger = 0


Dim tota l As Dou ble = 0
Dim num As Dou ble
Do Unt il sr.E ndO fStr eam
num = CDb l(sr. Rea dLin e)
cou nter += 1
tota l += num
Loop )
txtO u tpu t. Tex t Form atNu mbe r(to tal I cou nter
sr. Clos e ()
End Sub

a-i 8.2 Exe rcise 31

Calculate Average of Numbers

9.00

EXERCISES 8.3
1. N o 3. N o 5. N o 7. No 9. N o

11. <?xm l vers ion= 'l.O '?> inau gura ted . - ->
ages of the pres iden ts when
< !--T hi s file con tain s the
<Pre side nts>
<pr esi dent >
>
<nam e>Ge orge Was hing ton< / name
on >57 </ag eAt inau gua tion >
<age Atin aug uati
</pr es iden t >
<pr esi dent >
<nam e>Jo hn Adam s</n ame >
ugu atio n>
<age Atin aug uati on >6 1</a geA tina
</pr esid ent>
</ Pres iden ts>
lick
k( . .. ) Han dles btnD ispl ay.C
13. Priv a te Sub btnD ispl ay_ Clic oad( "US Stat es.x ml")
t = XEl eme nt.L
Dim stat eDa ta As XEle men
Dat a . Des cen dan ts(" stat e" )
Dim que ry= From st In s tate > .Val ue)
Let pop = Cin t(st . <po pula tion
Sele ct pop
r(qu ery . Sum, 0)
txtO utpu t.Te xt = Form atNu mbe
End Sub

l = i @.l i. ..i"'L _I a';! 8.3 Exe rcis-e 15 l = I @) ~~ . . ,.J


g . 8.3 Exerc ise 13

Displa)' Population Density


I Displa'f Total Population of States
7S.9J people per square mile
27 ,73'0.562

k
k( ... ) Han dles btnD ispl ay . Clic
15. Priv at e Sub btnD ispl ay_ Clic d("U SSta tes.x ml" )
XEle men t . Loa
Dim s ta teD ata As XEle men t =
Answe rs To Se lected Odd-N um bered Exercises
• 673

Dim query Pop From st In stateD ata.D escen dants ("stat e")
Let pop = Cint( st . <popu lation >.Val ue)
Selec t pop
Dim query Area From st In stateD ata.D escen dants ("stat e")
Let area = Cint( st.<ar ea>.V alue)
Selec t area
txtOu tput.T ext Forma tNumb er(que ryPop .Sum I queryA rea.Su m)
&
" peopl e per squar e mile"
End Sub

17. Priva te Sub btnDi splay_ Click ( . . . ) Handl


es btnDi splay .Click
Dim stateD ata As XElem ent = XElem ent.Lo ad("U
SState s.xml ")
Dim query = From st In stateD ata . Desce ndant
s("sta te")
Let name = st . <name >.Valu e
Let area = CDbl (st.<a rea>.V alue)
Let forma ttedA rea = Forma tNumb er(are a, 0)
Where area > 10000 0
Order By area Desce nding
Selec t name, forma ttedA rea
dgvSt ates.D ataSo urce = query .ToLi st
dgvS tates. Curre ntCel l = Nothi ng
dgvSt ates.C olumn s("nam e") . Heade rText = "State
"
dgvSt ates.C olumn s("for matte dArea ") .Head erTex
t = "Area "
End Sub

a~ 8.3 Exercise 17

Display States Having Nea Greater Than


a;! 8.3 Exercis e 19 l = i @l 1 ·~
f 100,000 Square Miles

State Nea .... Display States with Most

~
Alaska Different Vowels
571.951
Texas 261.797 Georgia
Connecticut
Califomia 155.959 South Carolina
Montana Rhode Island
147.046 Louisiana
New Mexico 121 ,598 Minnesota
~
[

19. Priv ate Sub btnDi splay_ Click ( ... ) Handl


es btnDi splay .Click
Dim stateD ata As XElem ent = XElem ent.Lo ad("U
SState s.xml ")
Dim query l = From st In stateD ata.D escen dants
("stat e")
Let name = st . <name >.Valu e
Let numVo wels = Numbe rOfVo wels(n ame)
Order By numVo wels Desce nding
Selec t numVo wels
Dim maxVo wels As Integ er = query l . First
Dim query 2 =From st In stateD ata.D escen dants
("stat e")
Let name = st . <name > . Value
Where Numbe rOfVo wels(n ame) = ma xVowe ls
Selec t name
lstOu tput . DataS ource = query 2.ToL ist
lstOu tput.S electe ditem = Nothi ng
End Sub
674 • Answ ers To Selec ted Odd -N umbe red Exerc ises

Func tion Nurn berO fVow els(B yVal word As Strin g) As Inte ger
word = word .ToU pper
Dim num As Inte ger = 0
If word .Inde xOf( "A") <> -1 Then
num += 1
End If
If word .Inde xOf( "E") <> -1 Then
num += 1
End If
If word . Inde xOf ("I") <> - 1 Then
num += 1
End If
If word . Inde xOf { "0") <> -1 Then
num += 1
End If
If word . Inde xOf ( "U" ) <> - 1 Then
num += 1
End If
Retu rn num
End Func tion
men t.Lo ad(" Coll eges .xml ")
21. Dim coll eges As XEle ment = XEle
) Hand les btnD ispla y.Cl ick
Priv ate Sub btnD isp lay_ Cl ick ( ...
. xml loca ted in the give n stat e
'Dis play the coll eges in Coll eges 'mas k LL
tate. Text .ToU pper
Dim chos enSt ate As Strin g = mtbS ege" )
Desc enda nts ("co ll
Dim quer y= From col I n co l lege s.
Let name = col. cnam e > .Val ue
Let stat e = c ol.c stat e >. Valu e
>. Valu e
Let year Foun ded = col. cyea rFou nded
Wher e stat e = chos enSt ate
Orde r By name Asce ndin g
Sele ct name & " " & year Foun ded
lstC olle ge s.Da taSo urce = quer y.To List
lstC olle ges. Sele cted item = Noth i ng
End Sub
ment .Loa d("C olleg es .xml ")
23. Dim coll eges As XEle ment = XEle
) Hand les MyB ase.L oad
Priv ate Sub frmC olleg es _ Loa d( ...
into the left list box
'Plac e the year s for each colle ge
colle ges. Desc enda nts( "col lege " )
Dim quer y= From col In
.Val ue
Let year Foun ded = col.c year Foun ded>
Orde r By year Foun ded Asce ndin g
Sele ct year Foun ded
Dist inct
For Each yr i n que ry
lstY ears .Item s .Add {yr)
Next
End Sub
hang ed( ... ) Hand les
Priv ate Sub lstYears Sele c tedin dexC
lstY ears . Se lecte dind exCh ange d
ar As Strin g = lstY ears . Text
Dim chos enYe
Desc enda nts(" colle ge")
Dim quer y = From col In colle ges.
Let name = c ol.cn ame> .Val ue
Let year Foun ded = col.c year Foun ded >.Va lue
Wher e year Foun ded = chos enYe ar
Sele ct name
lstC olle ges.D ataS ourc e = quer y.To List
g
lstC olle ges .S elec tedit em = No thin
End Sub
Answ ers To Selec ted Odd -Num bered Exercises
• 675

Oick on a year.
1793 Bowdoin College
U. of Tennessee

25(a).
Priv ate Sub btnS enat e Clic k( ...
) Han dles btnS enat e . Clic k
Dim sr As IO.S tre amR eade r = IO.F
ile.O pen Tex t("S enat elll. txt" )
Dim sw As IO.S trea mW riter = IO.F
ile.C reat eTe xt(" Sen atel ll.xm l")
sw . Wri teLi ne(" <?xm l vers ion= 'l.O
'?>" )
sw. Wri teLi ne ( "< ! - - This file
cont ains data on the lllt h Sena
sw.W riteL ine( "<Se nate lll> ") te -->" )
Dim temp As Stri ng = ""
Do Unt il sr.E ndO fStre am
temp = sr.R eadL ine
sw.W riteL ine( " <sen ator >")
sw . Wri teLi ne(" <nam e>" & tem p.Sp lit(" ,"c) (0)
sw.W riteL ine( " & "</n ame> ")
<s tate >" & temp . Spl it(" ,"c) (1)
& "</s tate >")
sw.W riteL ine( " <par ty> " & tem p.Sp lit(" ,"c) (2)
& "</p arty >")
sw.W riteL ine( " </se nato r>")
Loop
sw.W riteL ine( "< /Sen atel ll > ")
sr . Clos e()
sw. Clos e ()
Mes sage Box .Sho w("F ile Crea ted"
)
End Sub

Convert Senate 111 .txt to ML

g 8.3

( Displ- Senators

Senator State Party ffiliation


"'
Jeff Sessions •Jaba ma R ·--
Richard Shelby Alabama
-
R
Usa Murko•Nski Jaska R
Mark Begich !Alaska D

1~
John McCa in 1\sizona R

25(b).
Priv ate Sub btnD ispl ay_ Clic k( .
.. ) Han dles btnD ispl ay .C lick
Dim sena teDa ta As XEle men t = XEl
eme nt.L oad( "Sen atell l.XM L")
cises
676 • Answ ers To Selected Odd-N umb ered Exer

dan ts(" sena tor" )


Dim que ry From st In sena teD ata . Des cen
Let name = st.< nam e>.V alue
Let stat e = st.< stat e>.V alue
Let par ty = st.< part y>.V alue
ng
Ord er By stat e, name Asc endi
Sele ct nam e, stat e, part y
ry.T oLi st
dgv Sen ator s. Data Sou rce = que
rren tCe ll = Not hing
dgv Sen ator s.Cu
ator s.Co lum ns(" nam e " ) .Hea derT ext = "Sen ator "
dgv Sen
.Hea derT ext "Sta te"
dgv Sen ator s.Co lum ns(" stat e")
part y") . Hea derT ext = "Pa rty Aff ilia tion "
dgvS enat or s.Co lum ns("
End Sub

CHA PTE R 9

EXERCISES 9.1

1. Cho pin i dele ted from the list.


l s tBox , Mozart, is dele ted.
3. The curr ently selec ted item in
lstB ox betw een C hop in and Moz
art.
5. The item H aydn is inse rted into
r in desc endi ng alph abet ical orde r.
7. The nam es in the list box will appe a

9. cboB ox.T ext = "Da nte"


s pear e")
11. cboB ox.I tem s. Rem ove( "Sha ke
x.Ite ms . Cou nt - 1)
13. cboB ox.I tem s. Rem oveA t(cb oBo

15. Dim i As In tege r = 0


unt
Do Whi le i < cboB ox.I tem s.Co "M" Then
r(cb oBo x . Item s(i) ) .Sub strin g(O , 1)
If CSt
cboB ox .Item s.Re mov eAt( i)
Else
i += 1
End If
Loop
( . . . ) Han dles btnS ort. Clic k
17. Priv ate Sub btnS ort_ Clic k txt" )
ile.R eadA llLi nes( "Po pula rNa me.
Dim name s() As Stri ng= IO.F
lstO u tput .So rted = True
lstO utpu t.Da taSo urce = nam es
hing
lstO utpu t.Se lect edit em = Not
utpu t.Ite ms. Cou nt - 1
For i As Inte ger = 0 To lstO
ms( i))
nam es(i ) = CSt r(ls tOu tput .Ite
Nex t
ame s.tx t", nam es)
IO.F ile .Wr iteA llLi nes( " Sort edN
orde red file has been crea ted. ", "Do ne")
Mes sage Box .S how ("Th e
End Sub
ile.R ead AllL ines ("A gesA tina ugu ral.t xt")
23. Dim ages () As Stri ng= IO.F
) Han dles MyB ase . Load
Priv ate Sub frmP res Load ( . ..
IO . File .Rea dAl lLin es(" USP res. txt" )
Dim pres () As Stri ng=
lstP res. Data Sou rce = p r es
End Sub
Answ ers To Selec ted Odd-N um bered Exerc ises
• 677

Priv ate Sub lstPr es_ Selec tedin dexC hang


ed( ... ) Hand les
lstPr es.Se lecte dind exCh ange d
txtA ge.T ext = ages (lstP res.S elect edin
dex)
End Sub

a. 9.1 Exerci se 17 = @] ~

( Sort Names ]
Abigail
.J.
fl;jdan
Ava Done
Braden
Brianna
Cai~'11
Cait~fll The ordere d fi le ha~ been create d.
Caleb
Chloe
Connor
Emma
B han OK
Isabella
Jacob
Jaden
Kaden
Landon
Madeline
Noah
Olivia
'- -

25. 'Note : This even t proc edur e hand les even


ts from all three comb o boxe s
Priv ate Sub Selec tedin dexC hang ed( ... ) Hand les
cboB rand. Selec tedin dexC hang ed,
cboM emor y.Sel ected index Chan ged ,
cboM onito r.Sel ected index Chan ged
'Upd ate outp ut if all choi ces have
been made .
If (cbo Bran d.Se lecte dind ex >= 0) And
(cboM emor y.Sel ected index >= 0) And
(cbo Mon itor.S elect edind ex >= 0) Then
txtO utpu t . Text = "You have a " & cboB
rand. Text &
" comp uter with " & cboM emor y.Tex t
&
" of memo ry and a " & cboM onito r.Tex
t & "mo nito r."
End If
End Sub

0
- 9. Exerci s e 25 l = I @] l~.a ~J

Select the brand of computer: Dell ....

Select the amount of memory : [2GB


.... ]
Select the size of the monitor: [ 2o-tnc
h .... ]
You have a Dell computer with 2GB of memory and -
a 20-inch monitor.
678 • Answ ers To Se lected O dd -Num bered Exe rcises

EXERCISES 9.2
ds (500 0 mi lliseconds).
1. The Tick eve nt will be trigge red every 5 secon
cur or is hove red over a cont ro L
3. The too ltip will appear one second after the
rderA sc menu item .
5. A chec k mark appears in front of the rnnuO
secon ds.
7. The Tick eve nt wi!l be trigge red every intv ar
is selec ted at rand om and displayed in
9. The name of one of the 44 U .S. presidents
txtB ox.
yed in the list box.
11. Two states are selected at rand om and d ispla
13. The con te nts of the C lipboa rd are delet ed.
is copied into the C lipbo ard.
15. The text curre ntly se lected in txt Box, if any,
17. The cont ents of the C li pboa rd are d isplay
ed in txtB ox.

19. The cont ents of the C lipbo ard are assig


ned to the varia ble strVar.
n in the pictu re box. Its uppe r- leftm os t poin t
21. A blue circle of radiu s 50 pixels wi!l be draw
re box and 30 pixe ls from the top side.
wi!l be 20 pixels from the left side of the pictu
23. A picture of an airplane will be place d in
the pictu re box.
scroll bar wi !l move the butto n the same
25. C lickin g on the arrow on eithe r end of the
the scroll box and an arrow.
("large" ) dista nce as click ing on the bar betw een
27. Tim erl.E nabl ed = Fals e

29. Dim rando mNum As New Rand om()


, 13))
txtB ox.T ext = CStr (rand omN um.N ext(l
. File s . Read Text ("To wns . txt" )
31. Dim sr As IO.S tream Read er = IO
Dim rando mNum As New Rand om ()
Dim num As Inte ger rando mNum . Nex t(l, 26)
Dim city As Strin g
For i As Inte ger = 1 To num
city = sr. Read Line
Next
txtB ox.T ext = city
nt
33. Dim n As Inte ger = rive rs .Cou
If n ?: 2 Then
Dim rando mNum As New Rand om()
Inte ger
Dim first Num ber, secon dNum ber As
umb er = rando mNum .Nex t(O, n)
firstN
Do
n)
secon dNum ber = rando mNu m.Ne xt(O,
Unti l secon dNum ber <> first Num ber
er))
lstB ox.I tems .Add (rive rs(fi rstN umb
rs( s econ dNum ber))
lstB ox.I t ems. Add (rive
Els e
r than two elem ents .")
Mess ageB ox . Show ("Th e arra y has fewe
End If

35. Clip boar d.S etTe xt("" )


Text )
37. Clip boar d.Se tTex t(txt Box .Sele cted

39. Dim amou nt As Inte ger


amou nt = Cint (Clip boar d.Ge tTex t)
Answ ers To Selec ted Odd -Num be red Exerc
ises • 679

41. rnnu Orde rDes c.Ch ecke d = Fals


e
43. vscr ol1B ar2. Valu e = VSc rollB
ar2.M inim um
45. The me nu item mnu Orde rAsc is gray
ed o ut and cann ot be se lec ted .
49. Priv ate Sub btnS elec t Clic k(
... ) Han dles btnS elec t.Cl ick
'Assu me ther e are at leas t thre
e mem bers in the club .
Dim nam es() As Stri ng= IO.F ile.R
eadA llLin es(" Mer nber s.txt ")
Dim n As Inte ger = narn es.C ount
Dim p As Inte ger
Dim rando rnNu m As New Rand om()
p = rand ornN um.N ext(O , n)
txtP resi den t.Te xt = narn es(p )
•swa p Pres iden t with the pers on
in the last arra y elem ent.
narn es(p ) = narn es(n - 1)
narn es(n - 1) = txtP resi den t.Te
xt
'Cho ose a rand om pers on from firs
t n-1 for Trea sure r.
p = rand ornN urn.N ext(O , n - 1)
txtT reas urer .Tex t = narn es(p)
'Swa p Trea sure r with the pers on
in the next to last arra y elem
narn es(p ) = narn es(n - 2) ent .
narn es(n - 2) = txtT reas urer .Tex
t
'Cho ose a rand om pers on from firs
t n-2 for Sec reta ry .
p = rand ornN urn.N ext(O , n - 2)
txtS ecre tary .Tex t = narn es(p)
End Sub

11 _. 9.2 Exercis.e 49 l = I @) 1-ti


President : Michael

Treasurer: Connor ...


g ...J

Secretary Stephanie
Roll Dice

Select Officers
Odds of tossin g 7 are about 1 in

51. Dim rando rnNu m As New Rand om()

Priv ate Sub btnP lay_ Clic k( ...


) Han dles btnP lay .Cli ck
'Rol l a pair of dice unt il 7 appe
ars 1000 time s.
Dim diel , die2 As Inte ger
Dim nurn berO fSev ens As Inte ger
= 0
Dim nurn berO fRol ls As Inte ger
= 0
Do
'Rol l the dice
diel = rand ornN urn.N ext(l , 7)
die2 = rand ornN um.N ext(l , 7)
'If luck y 7, incr eme nt the seve
ns coun ter.
If (die l + die2 ) = 7 Then
nurn berO fSev ens += 1
End If
nurn berO fRol ls += 1 'Incr eme nt the roll s coun ter.
Loop Unt il (nurn berO fSev ens =
1000 )
'Dis play the resu lt to two deci
mal plac es.
txtO utpu t.Te xt = Forr natN urnb er(nu
rnbe rOfR olls I nurn berO fSev ens,
End Sub 2)
Exercise
680 • Ans wer s To Selected Odd -N umbered

pla y . Cli ck
Cli ck ( . .. ) Han dles btn Dis
57. Pr iva te Sub btn Dis pla y_ fil e
a log box to get the
'Di spla y t he ope n fi l e di
Dim file Sp ec As Str i ng
()
Ope nFi l e Di alog l.Sh owD ial og
= Ope nF i leD i alo gl. File Nam e
f ileS pec
ed in the f i le .
' Dis pla y p i c ture con tain
Fil e( file Spe c )
picB ox. I mag e = Ima ge . From
End Sub
ck
k( .. . ) Han dles tmrM oon . Ti
59. Pr i vat e Sub tmrM oon_ Tic ima ge .
p lay the
'Up date the pha se and dis t i ng is Tru e
s 2 000 ; Tim e r Ena bled set
'Tim er Int erv al set tin g i
pha se += 1
If pha se = 9 The n
pha se = 1
End If se & " . b mp" )
picB ox . Ima ge Ima ge . From Fi l e("M oon " & pha
End Sub
k
ck ( ... ) Han dles tmr Bal l . Tic
61. Priv ate Sub tmr Bal l_ Ti and lab el.
scr oll bar
'Up date the v alu e o f the
er Int erv al set t i ng i s 100 0
'Tim 10
Ball .Ma xim urn
'vsb Bal l. Min i murn = 0 , vsb
cou nt = c oun t - 1
vsb Bal l .Val ue = 10 cou n t
lblB a ll.T ext = CSt r (co u n t)
y the mes sag e and end pro gram .
'If at zer o , dis pla
If cou n t = 0 The n
tmr Bal l. En abl ed = Fal se
YEA R!!! ! " , "NYE" )
Mes sage Box .Sho w (" HAPPY NEW
Me. Clo s e()
End If
End Sub

a. 9.2 Exercise 61 I=@)

HAPPY NE hi YEAR!!!!

0
Ans wer s To Selected Odd -Nu mbe red
Exe rcises • 68 1

EXERCISES 9.3
1. $10 6 . 00 3. You r las t nam e beg ins wit h
K.
5. 'Fo rml ' s cod e
Pri vat e Sub btn Dis pla y_ Cli
ck( ... ) Han dles btn Dis pla
For m2. Sho wD ialo g() y.C lick
txtQ uot atio n.T ext = For m2.
quo tati on
End Sub

'Fo rm2 's cod e


Pub lic quo tati on As Str ing

Pri vat e Sub btn Pro ces sSe


lec tion_ Cli ck( . .. ) Han dles
btn Pro ces sSe lec tion .Cl ick
If rad l.Ch eck ed The n
quo tati on= "Pl ast ics . "
End If
If rad 2.C hec ked The n
quo tati on= "Ro sebu d . "
End If
If rad 3.C hec ked The n
quo tati on= "Th at's all folk
s."
End If
Me. Clo se()
End Sub

a 9.3 E:oce r ci~ e 5

Display a Movie Quot ation

Rosebud .

7. 'Cod e for frm Mil lion aire


Pub lic num berO fYrs As Inte
ger
Pub lic Con st INTEREST RAT
E As Dou ble = 0 . 06
Pri vat e Sub btn Cal cul ate_
Cli ck( ... ) Han dles btn Cal
Dim bal anc e As Dou ble, num cul ate .Cl ick
Yea rs As Inte ger
bal anc e = CD bl(t xtA mou nt.T
ext)
Do Wh ile bal anc e < 100 000
0
bal anc e += INTEREST RATE
* bal anc e
num Yea rs += 1
Loo p
txtW hen . Tex t = "In " & num
Yea rs &
" yea rs you wil l hav e a mil
lion dol lars ."
num berO fYrs = num Yea rs
frm Bal anc e.Sh owD ialo g()
End Sub

'Cod e for frm Bal anc e


Str uct ure Yea r
Dim num As Inte ger
Dim amo unt As Dou ble
End Str uct ure
bere d Exe rcises
682 • An swe rs To Se lect ed Odd -N um

Me . Loa d
Act iva ted ( ... ) Han dle s
Pri va te Sub frm Bal anc e_
be r OfY rs) As Yea r
Dim a(fr mM il l i ona ire . num
a(O ) .num = 0 t)
l l i ona i re.t xtA mo unt . Tex
a(O ) .amo unt = CDb l (frmMi 1
a. Cou nt -
Fo r i As Int ege r = 1 To
a(i ) .num = i * a(i - 1) . amo unt
.am oun t = (1 + frmM il lio nai re . INTEREST_ RATE)
a(i )
Ne xt
a
Dim que ry = Fro m yr I n
Let Yea r = yr . n um
cy (y r.am oun t)
Let Amoun t = Forma tCu rren
Sel ect Yea r, Am oun t
= qu ery .To L i st
d gvB ala nce . Dat aSo u r c e
= Not hin g
dgv Bal anc e.C urr ent Ce l l
End Sub
s Me .Fo rmC losi ng
For mCl osi ng( ... ) Han dle
Pri vat e Sub f rmB alan ce
. Cle ar( )
frm Mi l lio nai re.t xtA mo unt
ona ire . txtW hen .C l e ar ()
f rmM illi
t .Fo cus ()
frm Mi l lio na ire . tx tAm oun
En d Sub

11. 'Fo rm1 's cod e (Cu s t ome r ) t.C lick


ck ( . . . ) Han dle s btn Ge
Pr iva te Sub btn Ge t _ Cl i
Th en
If rad Bi l l Cus t.C hec ked
For m2. Sho wD ialo g ()
Els e
For m3. Sho wD ialo g()
End If
End Sub
r I nf o)
' For m2 's c ode (Cu stom e
For m2 _ Loa d( ... ) Han dle s My Bas e.L oad
Pri vat e Sub
am e.T ext
txtN ame . Tex t = For m1 . txtN
End Sub
Rec ord .C lic k
Cli ck ( . .. ) Han dle s btn
Pri vat e Sub btn Rec ord_
S tr i ng
Dim cit y, s tat e , z i p As
Item s . Add ("M ail bil l to : ")
For ml. ls tOu tpu t .
Ad d(tx tNa me .Te xt)
For m1 .ls tOu tpu t . It e ms .
d(t xtA ddr ess .Te x t)
For ml . l stO utp ut. It e ms. Ad
cit y = tx tCi ty .Te xt
sta te = c bo Sta te . Tex t
zip = txt Zi p . Tex t " & zip )
d(c ity & " " & sta te & "
For m1 . ls tOu tp u t. Ite ms .Ad
Me. Clo se ()
End Sub
Car d Inf o )
'Fo rm3 's c ode (Cr edi t d
Loa d ( . . . ) Han dle s MyB ase . Loa
Pri vat e Sub For m3
ay. Yea r
Dim num As Int ege r= Tod
i As Int ege r = num To num + 5
For
cbo Ye ar .I tem s. Add (i)
Nex t
End Sub
Rec ord .Cl ick
Cl i ck( ... ) Han dle s btn
Pri va t e Sub btn Rec ord_ " & cbo Car d.T ext )
Ad d(" Bil l
Fo rml . lstO utp ut .I t ems . d: " & txtN am e.T ext )
Add ("N ame on car
For ml. lstO utp ut .I tem s. txtC ard Nu mb er.T ext )
Add ("C ard num ber : " &
For ml .lst Ou tpu t . Item s .
Answe rs To elected Odd-N umbered Exercises
• 6 3

Forml .lstOu tput.It ems.A dd("E xpirat ion date: "


&
cboMo nth.Te xt & "I" & cboYe ar.Tex t)
Me .Close ()
End Sub

EXERCISES 9.4
1. Privat e Sub btnDra w_ Click( ... ) Handle s btnDra w.Clic k
Dim gr As Graph ics = picBo x.Crea teGrap hics
Dim x As Double picBox .Width I 2
Dim y As Double = picBo x.Heig ht I 2
Dim r As Double = x I 2
If r > y I 2 Then
r = y I 2
End If
gr.Fil lEllip se(Br ushes .Black , CSng (x- r), CSng
(y- r),
CSng(2 * r), CSng(2 * r))
End Sub

11 9. Ex:erci e 3 l = l:@l I~ l
Dra•t • Orcle Draw Orcle

3. Privat e Sub btnDra w_ Click( . .. ) Handle s btnDra w


.C lick
Dim gr As Graph ics = picBo x.Crea teGrap hics
Dim x As Double picBox .Width I 2
Dim y As Double = picBo x.Heig ht I 2
Dim r As Double = 20
gr.Fil lEllip se(Br ushes .Red, CSng(x r) , CSng (y- r),
CSng(2 * r), CSng(2 * r))
r = 19
gr.Fil lEllip se(Br ushes .Whit e, CSng(x r), CSng (y- r),
CSng(2 * r), CSng(2 * r))
End Sub

5. Privat e Sub btnCr eate_ Click( .. . ) Handle s btnCr eate.C


lick
Dim gr As Graph ics = picFla g.Crea teGrap hics
Dim br() As Brush = {Brush es.Gre en, Brush es.Wh
ite, Brushe s.Red}
'picFl ag.Wi dth = 149; picFla g.Heig ht = 99
For i As Intege r = 0 To 2
gr.Fil lRect angle (br(i) , 0 + i *50, 0, 50, 99)
Next
gr . DrawL ine(Pe ns . Black, 0, 0, 148, 0) 'top border
684 • Answ ers To Se lected O dd-N um bered Exe rc ises

'left borde r
gr.Dr awLi ne(Pe ns.Bl ack , 0, 0, 0, 98)
'botto m borde r
gr.Dr awLi ne(Pe ns.Bl ack , 0, 98, 148, 98)
'righ t borde r
gr.Dr awLi ne(Pe ns.Bl ack, 148, 0, 148, 98)
End Sub
les btnC reate .Clic k
7. Priva te Sub btnC reate _ Click ( ... ) Hand
Dim gr As Grap hics = picFl ag.Cr eateG raphi cs
Dim br() As Brush = {Brus hes.O range , Brush es.W hite, Brush es.Gr een}
Dim r As Integ er = 12 'radi us of circl e
99
'p ic Flag. Widt h = 149; picFl ag.H eight =
For i As Integ er = 0 To 2
149, 33)
gr . FillR ectan gle(b r(i), 0, 0 + i * 33,
Next
r, 2 * r, 2 * r, 0, 360)
gr.Fi llPie (Bru shes. Oran ge, 75 - r, 49
, 0, 0, 148, 0) 'top borde r
gr . Draw Line( Pens. Black
Pens. Black , 0, 0, 0, 98) 'left borde r
gr . Draw Line(
'botto m borde r
gr . Draw Line( Pens. Black , 0, 98, 148, 98)
0, 148, 98) 'righ t borde r
gr . DrawL i ne(Pe ns.Bl ack, 148,
End Sub
lick
9. Priva te Sub btnDr aw_ Click ( . . . ) Hand les btnD raw.C
Dim numb ers As Strin g =
1111

Dim gr As Grap hics = picBo x.Cre ateGr aphic s


picBo x. Refre sh ()
)
Dim n As Integ er= Cint( txtNu mber .Text
'Font is Micr osoft Sans Serif
For i As Integ er 0 To n
If i < 9 Then
numb ers &= i & 11
Else
numb ers &= i & 11
End If
5, 12 + (24 * i), 15)
gr . Draw Line( Pens. Blue, 12 + (24 * i),
Next
+ 1), 10)
gr.Dr awLi ne(Pe ns.Bl ue, 0, 10, 24 * (n
es.Bl ue, 8, 20)
gr.Dr awSt ring( numb ers, Me.F ont, Brush
End Sub

l = -1 @) j, _a ...J
g_ 9. Exercise 9

Dra •~oo• .1\xis


Maximum Number (1-2 ):

4 5 6 B 9 10 12 13 15 16
0 2 3

CH APT ER 10

EXERCISES 10.1

1. (e ) 3. (d) 5. (b )
se.Lo ad
7. Priva te Sub frmC ities Load( ... ) Hand les MyBa
Data Set.C ities)
itiesT ableA dapte r.Fill (Me. Mega cities
Me.C
End Sub
Answ ers To elected O dd -N um bered Exerc ises
• 685

Priv ate Sub btnD ispla y_ Clic k( ... ) Hand les


btnD ispla y.Cl ick
Dim quer y From city In Meg aciti esDa taSe t.Cit
ies
Let popG rowt h = (city .pop 2015 -
city. pop2 010) / city. pop2 010
Let form atted PopG rowt h = Form atPe
rcen t(pop Grow th)
Orde r By popG rowt h Desc endi ng
Sele ct city. nam e, city .cou ntry ,
form atted PopG rowt h
dgvO utpu t . Data Sour ce = quer y . ToL
ist
dgvO utpu t.Cu rren tCel l = Noth ing
dgvO utpu t.Col umn s("na me") .Hea derT
ext = "Cit y"
dgvO utpu t.Co lumn s("co untry ") .Hea
derT ext = "Cou ntry"
dgvO utpu t.Co lumn s("fo rmat tedP opGr
owth ") .Hea derT ext =
"Pro jecte d Popu latio n Grow th"
End Sub

17. Priv ate Sub frmN ation s _ Load ( ...


) Hand les MyB ase.L oad
Me.N ation sTab leAd apte r.Fil l(Me .UND
ataS et .Nat ions )
Dim quer y = From nati on In UND ataS
et.Na tions
Orde r By nati on.c onti nent Asce ndin
g
Sele ct nati on.c onti nent
Dist inct
lstC onti nent s.Da taSo urce = quer y.To
List
End Sub

Priv ate Sub lstC onti nent s Sele cted


inde xCha nged ( ... ) Hand les
lstC onti nent s.Se lecte dind exC hang
ed
Dim quer yPop = From nati on In UND
ataS et.N ation s
Wher e nati on.c onti nent = lstC onti
nent s.Te xt
Orde r By nati on.p opul atio n Desc endi
ng
Sele ct natio n.na me
lstC ount riesP op . Data Sour ce = quer
yPop .ToL ist
lstC ount riesP op.S elec tedit em = Noth
ing
Dim quer yAre a = From nati on In UND
ataSe t . Nati ons
Wher e nati on . cont inen t = lstC onti
nent s . Text
Orde r By nati on.a rea Desc endi ng
Sele ct natio n.na me
l stCo untr iesA rea.D ataS ourc e = quer
yAre a.To List
lstC ount riesA rea.S elec tedit em =
Noth ing
End Sub

a 10.1 Exe rcise 21 a~ 10.1 Exercise 23 [ = I @) III!F!.tJ ~""'I


uwait .Angels
Malta .Astros
0Jrrency
Jordan /!lihlet ics
N Zealand Franc Blue Jays
.Ameri ca Braves
Canada Exchange rate Brewers
Austra lia
Switzerland
Turkey
1.1 26 .
Cardinals
-
Diamondbacks
Tunisi a
Singapore Stadium : Vll'rigle>t Field

21. Priv ate Sub frmC urren cies _ Load


( . .. ) Hand les MyB ase.L oad
Me . Rate sTab leAd apte r.Fil l(Me .Exc
hrate Data Set.R ates)
Dim quer y = From mone y In Exch rateD
ataS et . Rate s
Orde r By mon ey.d ollar Rate Asce ndin
g
Sele ct mon ey.co untry
Exe rcises
686 • Ans wers To Se lected Odd -Num bered

lstC oun trie s.D ataS our ce que ry.T oLi st


End Sub
dles
ecte di ndex Cha nged ( ... ) Han
Priv ate Sub lstC oun trie s_ Sel ed
ang
lstC oun trie s. Sele cted inde xCh
tes
Dim que ry From mon ey In Exc hrat eDa taSe t.Ra
= lstC oun trie s.T ext
Whe re mon ey.c oun try
one tary Uni t, mon ey.d olla rRa te
Sel ect mon ey.m
t.m one tary Uni t
txtC urre ncy .Te xt = que ry. Firs
. Firs t.do llar Rat e)
txtR ate. Tex t = CSt r(qu ery
End Sub
d
Loa d( ... ) Han dles MyB ase. Loa
23. Priv ate Sub frm Bas eba ll eba llDa taSe t.Te ams )
(Me .Bas
Me .Tea msT able Ada pte r.Fi ll
eba llDa taSe t.Te ams
Dim que ry = From team In Bas
Ord er By team .nam e
Sel ect team .nam e
oLi st
lstT e ams .Da taSo urce = que ry.T
End Sub

inde xCh ang ed( .. . ) Han dles


Priv ate Sub lstT eam s Sele cted
lstT eam s.S e lect edin dex Cha nge d
From team In Bas eba llDa taSe t.Te ams
Dim que ry
Whe re team .nam e = lstT eam s.Te xt
Sel ect team . s tadi um
txtS tadi um. Tex t = que ry.F irst
End Sub
d
Loa d( ... ) Han dles MyB ase. Loa
33. Priv ate Sub frm Bas eba ll aSe t.Te ams )
e. Base ball Dat
Me . Tea msT able Ada pter .Fil l(M
ersT able Ada pter .Fil l(M e.B aseb allD ataS et.P laye rs)
Me. Play
End Sub

... ) Han dles btnC oun t.Cl ick


Priv ate Sub btnC oun t_ Clic k( et.P laye rs
Dim que ry From play er In Bas eba llD ataS
Bas eb a llDa taSe t.Te ams
Join team I n
er . team Equ als team .nam e
On play
Whe re team .lea gue = "Na tion
al"
Sel ect play er.n ame
umb er(q uery .Co unt, 0)
txtN atio nal. Tex t = Form atN
End Sub

ll . 10. 1 Exercise 33 I. = I [§) l,...g.,_.l

[ Count National League Pld"t ers )


11

39. film
d( . .. ) Han dles MyB ase. Loa d
41. Priv ate Sub frmM ovie s _ Loa
e.M ovie sDa taSe t.Li nes )
Me. Lin esT able Ada pter .Fil l(M
e.M ovie sDa taSe t.Ac tors )
Me. Act orsT able Ada pter .Fil l(M
iesD ataS et.L ines
Dim que ry = From line I n Mov
Sel ect line .fil m
Dis tinc t
oLi st
lstF ilms . Dat aSo urce = que ry.T
End Sub
Answ ers To Selected Odd-N umbe red Exe rcises
• 687
Priv ate Sub lstF ilms Sele cted inde
xCh ange d( ... ) Han dles
lstF ilms .Sel ecte dind exC hang ed
Dim quer y From line In Mov iesD ataS et.L ines
Join flic k In Mov iesD ataS et.A
ctor s
On line .film Equ als flic k.fi lm
Whe re line .film = lstF ilms .Tex
t
Sele ct flic k . male Lead
txtL ead. Tex t = que ry.F irst
End Sub

43. Priv ate Sub frmF ilms _ Load ( ..


. ) Han dles MyB ase.L oad
Me. Line sTab leAd apte r.Fil l(Me .Mo
vies Data Set. Line s)
Me . Acto rsTa bleA dapt er.F ill(M e.M
ovie sDa taSe t . Acto rs)
Dim quer y = From flic k In Mov
iesD ataS et.A ctor s
Sele ct flick .mal eLe ad
Dis tinc t
lstA ctor s.Da taSo urce = quer y.To
List
End Sub

Priv ate Sub lstF ilms Sele cted inde


xCh ange d( ... ) Han dles
lstA ctor s.Se lect edin dexC hang ed
Dim quer y From line In Mov iesD ataS et.L ines
Join flic k In Mov iesD ataS et.A
ctor s
On line .film Equ als flic k.fi lm
Whe re flick .mal eLe ad = lstA ctor
s.Te xt
Sele ct line .fam ousL ine
lstL ines .Dat aSo urce = quer y .ToL
ist
lstL ines .Sel ecte dite m = Noth ing
End Sub

a~ 10.1 Exerc ise 43 l = I @] l~tJ ,,~J


Actors Unes
---
~tmM
-
-
ul
c:f. • Serkis I could a been a conte nder.
:tmmt.
nt E.astv.•ood
Robe rt De Niro
Harrison Ford I
I'm gonna mak e him an offer he can 't refuse
.
l
Humphrey Bogart ~J
-

EXERCISES 10.2
7. Add a reco rd to the C ities table whose
name fi lei is emp ty or cont a ins the sa me nam
an already ex isting reco rd . e as

9. (Bin ding Sou rcel .Fin d("n ame ", strV ar)
= 0) And (strV ar <>" Bom bay" )
11. C reate a co ntro l named Bind ingSourc
e2 that has the Co untri es tab le as its Da taM
emb er.
Priv ate Sub Cou ntry Text Box_ Leav
e( .. . ) Han dles
Cou ntry Text Box .Lea ve, Bind ingN
avi gato rl .C lick
Bind ingS ourc e2.P osit ion = Bind
ingS ourc e2.F ind( "nam e",
Cou ntry Text Box . Text )
If (Cou ntry Text Box .Tex t <> "")
And
(Bin ding Sou rce2 .Pos ition = 0)
And
(Cou ntry Text Box .Tex t <> "Arg enti
na") Then
Mes sage Box. Show ("No t a vali d coun
try . ", "ERROR")
Cou ntry Text Box .Foc us()
End If
End Sub
Exercises
688 • Ans wers To Se lecte d Odd -Num bered

d( . . . ) Han dles MyB ase. Loa d


13. Priv ate Sub frmM ovie s_ Loa
e.M ovie sDa taSe t.Li nes )
Me .Lin esT able Ada pter .Fil l(M
End Sub
lick
k( ... ) Han dles btnU pda te.C
Priv ate Sub btnU pda te_ Clic on the hard driv e.
data bas e file
'The se two line s upd ate the
Bind ingS our cel. End Edi t()
ovie sDa taSe t . Lin es)
Line sTa bleA dap ter . Upd ate( M
End Sub

a':} 10.2 E e rcise 13

13 of 23 [ ] ~

Famo us line : Play it Sam.

Rim : Casablanca

Rul e of
key field of the Act o rs table. Thu s the
17. A poll o 13 does not appe ar in the
.
Refe rent ial Integrit y would be violated
lds name, address,
Rep lace th e tabl e with two tabl es. The first tabl e should con tain the fie
19. ital.
tain the fi elds city, state , and state Cap
and city. The seco nd table shou ld con

CH APT ER 11

EXERCISES 11.1
ll be reco rded
as 0 and any grad e grea ter than 100 wi
1. A ny nega ti ve grad e wi ll be reco rded
as 100.
l y from th e Mid term prop erty bloc
k and add the follow ing
3. Rem ove the keywo rd Wri teOn
Get prop e rty procedure to it:

Get
Ret urn m mid term
End Get
are writ e only.
5. The prope rties Mid term and Fin al
ed to the va lu e 999 -99- 999 9 .
7. The prop erty socS ecN um is init ializ
th ird line of the even t procedu re.
9. The keywo rd New is miss ing from the
lic and refe rred
vali d. m_n ame would need to be Pub
11. The state men t nom = m nam e is not
to by scholar.m_nam e.
= sch olar .Mi dter m and
13. The stat eme nts pup il. Mid term prop erty is writ e
idte rm) are not valid . The Mid term
lstG rad es. Item s .Add (pup il.M
a valu e.
o nly; it can be set, but cann ot retu rn
15. cou ntry : Can ada
Cap ital : Otta wa
Pop : 31 mil lion
Answ ers To Select ed Odd-N umbered Exercises
• 689

17 . C hange 20 to -20 in th e btnM ove_C lick eve nt proce


dure, and c reate a frmC ircle_ Load
event proced ure with the follow ing lines,

round .Xcoo rd picC irc le.W idth - 40


round .Ycoo rd picC irc l e. Heigh t - 40

a,. 11.1 Exercis e 17 l = I @) I.....ES "'J


[ Move and Show Orcle
1 EJ
\'--_()'~
~ +2
- '
tt~
\__ r'__.; \

~~ '\ )
-----

a'} 11.1 Exercise 21

Rrst die: 3
Go
Second die:

Sum : 7

21. clas s PairO fDice


Priva te m_ diel, m_ die2 As Integ er
Dim random Num As New Rando m()

Publi c ReadO nly Prop erty Diel( ) As Integ


er
Get
Retu rn m diel
End Get
End Prop erty

Publi c ReadO nl y Prop erty Die2( ) As Integ


er
Ge t
Retur n m die 2
End Get
End Pr ope r ty

Publi c ReadO nly Prop erty SumO fFace s()


As Integ er
Get
Retur n m diel + m die 2
End Get
End Prop erty
ises
690 • Answ ers To Selected Odd-N umbe red Exerc

Sub Roll ()
m diel rand omN um.N ext(l , 7)
m die2 rand omN um.N ext(l , 7)
End Sub
End Clas s 'Pair OfD ice

25. Pub lic Clas s frmC ashR egis ter


()
Dim regi ster As New Cash Reg ister
Han dles btnA dd.C lick
Priv ate Sub btnA dd_ Clic k( ... )
'Add an amou nt to the bala nce.
t))
regi ster. Add (CD bl(tx tAm ount .Tex
cy(r egis ter.B alan ce)
txtB alan ce.T ext = Form atCu rren
txtA mou nt.C lear ()
txtA mou nt.F ocus ()
End Sub

... ) Han dles btnS ubtr act. Clic k


Priv ate Sub btnS ubtr act_ Clic k(
nce.
'Sub trac t an amou nt from the bala
trac t(CD bl(tx tAm oun t.Te xt))
regi ster .Sub
alan ce.T ext = Form atCu rren cy(r egis ter.B alan ce)
txtB
txtA mou nt.C lear ()
txtA mou nt.F ocus ()
End Sub
End Clas s 'frm Cash Reg ister

Clas s Cash Reg ister


Priv ate m bala nce As Dou ble
) As Dou ble
Pub lic Read Only Prop erty Bala nce(
Get
Retu rn m bala nce
End Get
End Prop erty

Sub Add( ByV al amou nt As Dou ble) ive


'Ens ure bala nce stay s nonn egat
If (m_ bala nce + amou nt) >= 0 Then
m bala nce += amou nt
End If
End Sub
ble)
Sub Sub tract (ByV al amou nt As Dou ive
0 Then 'Ens ure bala nce stay s nonn egat
If (m_ bala nce - amou nt) >=
m bala nce m bala nce - amou nt
End If
End Sub
End Clas s 'Cas hRe gist er

EXERCISES 11.2
dles btnD ispl ay.C lick
1. Sub btnD ispl ay_ Clic k( ... ) Han
stud ents (las tStu dent Add ed)
ReDi m Pres erve
y = From pup il In stud ents
Dim quer
Let name = pupi l.Na me
Let ssn = pupi l.Soc SecN um
ade
Let semG rade = pupi l.Ca lcSe mGr
Whe re semG rade = "A"
um, pupi l.Ca lcSe mGr ade
Sele ct pupi l.Na me, pupi l.Soc SecN
Answer s To Selected Odd-N umbered Exercise
• 69 1

dgvGra des.Da taSourc e = query . ToList


dgvGra des.Cu rrentCe ll = Nothin g
dgvGra des.Col umns(" Name") . Header Text = "Stude nt Name"
dgvGra des.Col umns("S ocSecN um") .Heade rText = "SSN"
dgvGra des.Col umns(" CalcSem Grade" ) . Header Text = "Grade"
ReDim Preserv e student s(SO)
txtNam e. Focus ()
End Sub

7. Public Class frmCas hRegis ter


Dim WithEv ents registe r As New CashR egister ()

Private Sub btnAdd_ Click( ... ) Handle s btnAdd .Click


'Add an amount to the balanc e.
registe r.Add(C Dbl(txt Amoun t . Text))
txtBala nce . Text = Format Curren cy(regi ster.Ba lance)
txtAmo unt . Clear()
txtAmo unt.Foc us()
End Sub

Private Sub btnSub tract Click( ... ) Handle s btnSub tract.C


lick
'Subtra ct an amount from the balanc e.
registe r.Subtr act(CD bl(txtA mount. Text))
txtBala nce.Te xt = Format Curren cy(regi ster.Ba lance)
txtAmo unt . Clear()
txtAmo unt.Foc us()
End Sub

Privat e Sub Attemp tToOve rdraw(B yVal amt As Double )


Handle s
registe r.Attem ptToOv erdraw
Messag eBox.Sh ow("Yo u would have been overdra wn by "
&
Format Currenc y(amt) & " .", "Withd rawal Denied ")
End Sub
End Class 'frmCas hRegi ster

Class CashR egister


Private m balanc e As Double

Public Event Attemp tToOve rdraw(B yVal amt As Double )

Public ReadOn ly Proper ty Balanc e() As Double


Get
Return m balanc e
End Get
End Proper ty

Sub Add(ByV al amount As Double)


If (m_ balanc e + amount) >= 0 Then 'Ensure balanc e stays nonneg ative
m balanc e += amount
Else
RaiseE vent Attemp tToOve rdraw(a mount + m_ balance )
End If
End Sub

Sub Subtrac t(ByVa l amount As Double )


If (m_ balanc e - amount) >= 0 Then 'Ensure balanc e stays nonneg ative
m balanc e = m balanc e - amount
Else
RaiseE vent Attemp tToOve rdraw(a mount m_ balance )
692 • Answe rs To Se lected Odd -N umbered Exercises

End If
End Sub
End Class 'Cash Regis te r

I= @] ~ Vit drawal Denied


D 11.2 Exercise 7

Amount: 7 You w ould hav e been ov erdraw n by 5200 .00 .

dd
l [ Subtract
OK
Balance : S5

EXERCISES 11.3

1. 4 3. 64 5. Can move Has jointe d li mbs and no backb one


7. The keywo rd O verrid es hould be Inherits.
keywo rd in class H ello and with
9. The Hi functi on should be declared with the Overridable
the keywo rd Overr ides keywo rd in class Aussie.
11. The Hi functi on should be declared with the Ove rrides
keywo rd in class Cowb oy.
keywo rd , and the functi on Hi
13. The H ello class should be declared with the Mustl nherit
should be declared with the Mu tOverride keywo rd.
keywo rd, not MustO verrid e.
15. The He llo class should be declared with the Mustl nherit
19. Publi c Class frmRe gister
Di m to llBoo th As New FastT rackR egiste r()
btnPr ocess .Click
Priva te Sub btnPr ocess _ Cl i c k ( . .. ) Handl es
If radCa r.Che cked Then
t ollBo oth . Proce ssCar ( )
Else
tollB ooth.P roces sTruc k()
End If
alanc e)
txtRe v enue. Text = Forma tCurr ency( tollBo oth.B
tx tNumV ehicle s. Text = CStr(t ollBo oth.C ount)
End Sub
End Cl a s s 'frmR egi s te r

Cl a ss Ca s hReg ister
Priva te m balan ce As Doubl e

Sub Depo sit(By Val amoun t As Doubl e )


m bal ance += amoun t
End Sub

Sub WithD rawal( ByVal amoun t As Doubl e)


m b a lance m balan ce - amoun t
End Sub

e
Publi c ReadO nly Pr opert y Balan c e() As Doubl
Get
Retur n m balan ce
Answer s To Selected Odd-N umbered
Exe rci es • 693

End Get
End Pro per ty
End Cla ss 'Ca shR egi ster

Cla ss Fas tTr ack Reg iste r


Inh erit s Cas hRe gist er

Pri v ate m_ cou nt As Inte ger

Pub lic Rea dOn ly Pro per ty


Cou nt() As Inte ger
Get
Ret urn m cou nt
End Get
End Pro per ty

Sub Pro ces sCa r ()


m cou nt += 1 'Pro ces s a car : $1.0 0
Dep osi t(l)
End Sub

Sub Pro ces sTr uck ()


m cou nt += 1 'Pro ces s a truc k : $2 . 00
Dep osit ( 2 )
End Sub
End Cla ss 'Fa stT rac kRe gist er

a~ a st Trac k

Type of Vehicle

Car Truck

Proc ess Vehicle

Tota l Revenue : 5.

Number of vehicles :

CH AP TER 12
EXERCISES 12.1
1. Pro tec ted Sub btn Fin d_ Cli
ck( ... ) Han dles btn Fin d.C
Dim max As Dou ble = CD bl(t xtF irst Num lick
If CDb l ( txtS eco ndN um. Tex .Te xt)
t) >m ax The n
max = CD bl(t xtS eco ndN um.
Tex t)
End If
If CD bl(t xtT hird Num .Te xt)
> max The n
max = CD bl(t xtT hird Num . Tex
t)
End If
txtL arg estN um. Tex t = CSt
r(m ax)
End Sub
bered Exe rcises
694 • Answers To Selected Odd -N um

Cli ck( ... ) Han dle s btn Dis pla y.C lick
3. Pro t ec ted Sub btn Dis pla y_ t (tx tNu rnb er . Tex t)
Dim nurn As Int ege r= Cin
nurn - 1
For i As Int ege r = 1 To
t.It em s.A dd( i & " pot ato ")
ls t Ou tpu
Nex t
n)
lstO u t p ut . Item s.A dd( nur
End Sub
s btn Ca lcu late .Cl ick
late Cli ck( . . . ) Han dle
5. Pro te ct e d Sub btn Ca lcu t)
= CD bl( txtP urP rice . Tex
Dim p u r c h Pri ce As Dou ble edV alu e.T ext )
= CD bl(t xtR
Dim re dem Val ue As Dou ble pur chP rice ) I red emValu
e)
t Per cen t((r ede mV alu e-
t xtDi s c Rat e.T ext = For rna pur chP ric e ) I pur chP ric e )
P e rce nt( (re dem Va lue -
t xti ntR a t e.T ext = For mat
End Su b

EXERCISES 12.2
. .. ) Han dle s Me . Loa d
1. Pro tec ted Sub Pag e_ Loa d(
I f Not Is Pos tBa c k The n
=
Dim sta tes () As Str ing apP ath ("A pp_ Dat a \ Sta tes
.tx t") )
IO . Fil e . Re adA llL ine s(M
In sta tes
Dim que ry = Fro m s tat e
Ord er By s t ate
Sel ect sta t e
que ry
ls t Sta tes .Da taS our ce =
ls t Sta tes .Da taB ind ()
t)
t r(ls tSt ate s.It em s.C oun
tx tNu rnS tate s.T ext = CS
En d If
End Sub
De lete . Cli ck
_ Cli ck ( ... ) Han dle s btn
Pro tec t e d Sub btn De lete
(lst Sta tes .Te xt)
l s tSt ate s.It em s.R em ove t)
tr(l stS tate s.It em s.C oun
txtNurn Sta tes .Te xt = CS
End Sub

12.2 Exercise 3
~odel

Deluxe St.. per

lJ upg rad ed Video Card


I kte rna l ode!""' + V'li-r;:.

U 1 GS add itio nal rr1emory

Total cos~:

You mu st sel ect a mo del !

tie s wer e
Cau ses Va lida tion pro per
3. 'No te: The Au toP ostB ack and
ck box .
'set to Tru e for eac h che _
. . . ) Han dle s
_ Sel ect edi nde xC han ged (
Pro tec t e d Sub rblM ode l o .Ch eck edC han ged ,
Cha nge d, chk Upg rad edV ide
r blM ode l . Sel ect edi nde x cke dCh ang ed
chk Mem ory . Che
c hkMo dem . Che cke dCh ang ed,
Dim c ost As Dou b l e = 0
bas ed upo n sel ect ion s .
'Ad d amo unt s to the co st
lux e" The n
If r b l Mo del . Tex t = "De
c o st += 100 0
Answer s To Se lected Odd-N umbered Exerci es
• 695

Else
cost += 1500
End If
If chkUpg radedV ideo.Ch ecked Then
cost += 200
End If
If chkMod em.Che cked Then
cost += 30
End If
If chkMem ory . Checke d Then
cost += 120
End If
txtOut put.Te xt Format Curren cy(cost )
End Sub

9. 'In RangeV alidato r contro ls , Minimum is "a" and Maximum


is "zzzzz zz".
Protec ted Sub btnAlp habetiz e_ Click( . . . ) Handle s btnAlp
habetiz e . Click
Dim wordl = txtWor dl . Text
Dim word 2 = txtWord 2 . Text
Display Words (wordl , word2 )
End Sub

Sub Display Words( ByVal wordl As String , ByVal word2


As String)
lstOutp u t. Items.C lear()
If wordl <= word2 Then
lstOutp ut . Items . Add(wo rdl)
lst0utp ut.Item s.Add( word2)
Else
lst0utp ut.Item s.Add( word2 )
lstOutp ut.Item s.Add( wordl )
End If
End Sub

12.2 Exercise 91
F1rst ord:
Se:ond , ord:

Alphabetiz e W ords

First word missing! Second ord missing!


First letter of first word is not lower-case! First letter of second word is not lower-case!

11. Protec ted Sub btnDis play_ Click( ... ) Handle s btnDis
play.C lick
Dim justice s ( ) As String =
IO . File.Re adAllL ines(M apPath ("App_ Data\J ustice s.txt")
)
Dim stateAb brev As String = txtStat e.Text. ToUpp er
Dim query = From justice In justice s
Let data justice .Split( ","c )
Let name = data(O) & " " & data(l)
Let pres = data(2)
Let state = data ( 3 )
Let yrsServ ed = YearsS erved(d ata (4) , data(S ))
Where state = stateAb brev
696 • A nswer s To Selected Odd-N um bered Exe rcises

Selec t name, p r es, yrsSe rved


grvJu sti c es. DataS ource = qu ery
g rvJu sti ce s. DataB ind ( )
grvJu s t i c es. Heade rRow. Cell s (O) . Text "Just ice"
g rvJu stice s. Heade rRow . Cell s (l) . Text "Appo i nting Presi dent"
grvJu s t i c e s . Head erRow .Cell s (2) .Text "Year s Serv ed"
End Sub

le ,
Funct ion Years Serve d(ByVal enter As Doub
By Val l e ave As Doub le) As Doub le
If leave = 0 Then
Retu r n (Now. Year - ente r)
Els e
Re t u r n (l eave - enter )
End If
En d Func ti on

12.2 Exercise 11
State abiYev1a 10,... MD

[ Displ ay Justi ces ]

Justice Appo inting Presi dent Years Serve d


Sa'"'lL.el (hase George WashJ'Igton 15
Gab~;el =·~ al Ja'""'es "-~adJsor ::;
~

T'1ornas Jo 'nso.-. George Washington ~

John Rcberts Seorg e . 3 . . s~ J


~

Roger Taney .4. 'drew ac :>v -~

EXERCISES 12.3
Hand les btnD ispla y.Cli ck
7. Pro tecte d Sub btnD ispla y _ Click ( ... )
Dim mc DC As New Mega citie s DataC ontex t
Dim query = From city In mcDC . Citie s
coun try Equa ls
Join coun try In mcDC .Coun tries On city.
count ry.na me
Se l ect city.n ame, count ry.po p201 0
")
c h tMega ci ties.D ataBi ndTa ble(q uery, "name
ch tMega ci ties . Char t Areas ( O) .Axis X.Int erval =1
chtMe g a ci ties . Chart Ar eas ( O) .Axis X . Title = "City "
chtM egaci ties . Chart Areas ( O) .Axis Y.Tit le =
" 2 010 Pop. of Coun try in Milli ons "
End Sub
) Hand les btnD isp l ay . Click
17. Prote cted Sub btnD ispla y_ Cl ick ( . ..
Dim pizza DC As New Pizz a DataC ontex t
Dim query = From cha i n I n p iz zaDC .Pizz erias
Order By chai n.sal es200 8 Desce nding
Let amou nt = chain .sales 2008 I 10000 00
Se l ect chain . name, amoun t
chtPi zzaC hains .Da t aBind Table (quer y, "name ")
al = 1
chtP i zzaCh ains. Char tArea s (O) .Axis X. I nterv
X . Title "P i zzeri a"
chtPi zzaC hains .Char tArea s (O) .Axis
as (O ) . AxisY . Title = "2 0 08 Sa l es in Billi ons"
chtPi zzaC hains . Chart Are
End Sub
Answers To Selected Odd-N umbered Exe rci es • 697

25. Protec ted Sub btnDisplay _ Click( . .. ) Handles btnDisplay.Click


Dim pizzaDC As New PizzaDataContext
Dim query = From chain In pizzaDC . Pizzerias
Se le c t chain.numStores20 08
txtOutput . Text = FormatNumber(que ry . Sum, 0)
End Sub

12.3 Exercise 25
Display To al Number of S ores
Tota1 rumber o"" s ores 20,945
INDEX

Auto hide feature, 3 1


A Auto-implemented property, 502, 535
Abstract property, method, and class, 527 AutomaticDelay property, 413
Access key, 29, 415, 416 AutoPopDelay property, 413
Accumu lator va ri ab le, 22 1 AutoPostBack property, 558
Add Connection window, 459 Auto ize property, 29, 580
Add data to a file, 369 AutoSize setting, 414, 415
Add method, 54, 69, 98, 402 AutoSizeColumn property, 306
Add New Item dialog box, 425 Average method, 263, 283,341
Add ition operat i n , 54
AddYears method, 87 B
A lgorithm, 3, 7
A ligni ng contro ls, 3 1-33 BackColor property, 33, 581
A ll tab, 47 Backslash character, 589
A lphabet ic view of Properties window, 24 Barchart,442,560-64
Alt+F4 key combinatio n , 27 Ba e class, 518
Ampersand character, 29, 72, 85-87,385 Base name of a file, 5
And log ica l ope rator, 106 BASIC, 3
Animation, 443 bin folder, 45 , 263
Anonymous structu re type, 30 1 Binary search, 253-55, 288,3 4 1
ANSI va lues, 104,575- 76 Bind to a database tab le, 459, 463
Apostrophe character, 76 bin \Debug folder, 263
AppendText method, 369 BindingNavigator contro l, 48 1, 487
App lica tion, 6, 19 BindingSource contro l, 459, 486
A rgument, 160, 176, 178, 214, 598 BindingSource property, 48 1, 487
Arithmetic operatio ns, 54, 98 Block-leve l scope, 136, 194,223 ,23 1
leve l of precedence, 60 Body
Array, 258, 259, 340 of a Fo r ... Next loop, 230
ass ignment statement, 269 of an event procedure, 38
copy ing an, 269 Boo lean
declaring an , 259 data type, 107-8
higher-dimensional, 325 va lued function, 167
initial va lues, 259, 262, 320 variable, 107
of objects, 507 Break mode, 591
of structures, 297 Breakpoint, 592
passing an , 267 remov ing a, 592, 595
searching an , 268-69 setting a, 592, 595
size, 259, 262 Brushes object, 43 8
two-dimensiona l, 3 19,3 41 Brushes va riab le, 440
upper bound, 259,263 Bug, 8, 372,59 1
va riab le, 258, 259 Button co ntrol, 23, 28-29
A c function , 104, 154 By Ref keyword, 19 1
Ascending keyword, 286, 287 ByValkeyword, 161 , 190,2 14
ASCII. See ANSI
ASP.NET, 540
A signmenr statement, 37, 56, 58, 69, 98, 99, 269
c
Asterisk characte r, 4 7, 54 Ca ll statement, 180
Auto Correction, 71-72, 99 Ca mel cas ing, 56

699
700 • Ind ex

Caret character, 54 Code Editor, 39, 46, 47, 136


Case clause, 13 2 Declaration section , 78
Case keyword, 130 Code-behind , 543
Ca e stud y Cod ing, 8
Ana lyze a Loan, 332-40 Co llaps ible reg ion, 582
Recording C hecks and Deposits, 388-96 Color property, 438
Weekly Payroll , 206-1 4 Combo box control, 404-7, 450
Cast method, 325 DropDownSt y le property, 404-5
Catch block, 373-74 Text property, 405
Categorized view of Properties window, 24 Comment O ut button, 76
COate function, 87 Comment state ment, 76, 99, 180
CDbl funct ion, 70, 78, 99 Comments in XML, 383
Character map, 31, 587 Common tab, 4 7
C hart contro l, 560 Compiler, 2
Check box control, 148, 150, 557 Complete Word feature, 40
Checked property, 148 Component tray, 9 1,41 0
CheckedCha nged event, 149 Concat set ope rat ion , 355
Tex t property, 148 Concatenatio n ope rat ion, 72
Checked property, 14 7, 148 Condition, 104, 11 2, 154, 218
CheckedCha nged event, 149 Connect to a database, 459
Chi ld cl ass, 518 Con t statement, 90-91
C hild in XML, 383 Constant
Chr function, 104, 154 lifetime, 194
C lnt functi on, 70, 78, 99 scope, 194
C lass, 492, 493, 535 Constructor, 499
abstract, 527 Containm ent, 512, 518
base, 518 Co ntent of an XML element, 383
block, 492, 493 Continue keyword, 23 7, 271
child , 518 Co ntrol, 19, 20, 52, 552, 560
creating a, 498-99 align , 3 1- 33
de ri ved, 518 BindingNavigator, 481, 487
hierarchy, 5 19 BinclingSource, 459, 486
interface, 522 Button, 23, 28
parent, 518 center in a form, 579
C lass- leve l scope, 77, 194, 260, 426, 554 C hart, 560
C lean-up code, 374 C heck box, 148, 150, 557
Clear method, 54, 75, 98, 402 Combo box, 404
Clearing c reate uniform spac ing, 580
a list box, 54, 402 DataGridView, 301
a picture box, 446 G riciVi ew, 548
a text box, 75 Group box, 146
the C lipboard, 413 Ho rizonta l scroll bar, 41 8-20
the Immed iate wi ndow, 595 H ype rlink , 551
C lick event, 46, 244 Label, 23, 29, 580
C li ck with a mouse, 4 Li tbox, 23,29-30,5 4,62, 402-4
Client, 540 Masked text box, 85-87, 99
C lient area, 443 MenuS trip, 415- 18
C li entSi ze property, 443 move a, 579
Cl ipboard, 413,450, 579 OpenFileDia log, 359-60
Close Picture box, 413-15
a program, 578 position a, 31-33
button, 4, 27, 45 primary, 33
method, 366, 368, 426 PrintDocume nt, 91
Project command, 28, 33 PrintPreview Dialog, 92
C lustered bar chart, 565 Rad io button, 146, 150
Index
• 701

RadioButtonList, 555 management softwa re, 458


RangeValidator, 552 querying a, 464
related group of, 580 DataBind method, 548, 564
RequiredFieldValidator, 552 DataG ridView contro l, 301,3 50-52
resize a, 579 AutoS izeCo lumn property, 306
se lection of mu ltip le, 32 C urrent Ce ll property, 30 1, 351
setting properties of, 24-26 , 52, 58 1 DataSource method, 301,3 41 ,35 1
Table, 544-4 7 optim al sizing, 306, 581
Text box, 23-28 ,70 printin g a, 586
Timer, 4 10 Rowl:-leadersVisible property, 301,3 5 1,581
Too!Tip, 41 2-13 DataM ember property, 461
Vertica l scro ll bar, 41 8-20 DataSource property, 402, 459
Contro iToVe rify property, 552 for a DataG ridView contro l, 301, 34 1, 351
Conve rt class, 79 for a G ridView con tro l, 548
Coordinates of a point, 438 for a list box, 287, 341
Copying text, 413 Date data type, 87, 99
Coun t method, 263, 283, 341 DateDiff function, 87, 93
Coun t property, 243 , 402 DateFormat. LongDate argum ent, 87
Coun ter variab le, 22 1, 230, 234, 237, 25 1 DateFormat.ShorrDate argum ent, 87
Cou rier New font, 31 Dateln terva l. Day argument, 87
C reateG raphic s metho d, 414, 43 7 Debug fo lder, 45 , 263
C reateText metho d, 367 Debugging, 8, 195, 59 1-99
CSng function, 440 Decision fl owcha rt symbo l, 9
CStr functi on, 70, 99
Decision structure, 12, 203
CSV format, 297,3 50
Decla ration statem ent, 56, 90
Ctrl+ A lt+Break key combi nation, 592
Declarations sectio n, 78
Ctrl+ C key combi nation, 27
Declarative code, 108
Ctrl+F 5 key combination, 544, 549
Decla ring
Ctrl+F8 key combi nation, 592
consta n ts, 90, 214
Ctrl+S hift+F8 key combination, 592
objects, 493
Ctrl + V key comb inatio n, 27
variab les, 56, 60, 62, 68, 75
Ctrl +Z key combinati on , 34, 579
Defa ult event, 46
CType fu nction , 79
Defau lt va lue, 57, 75
C urrcnt Ccll property, 301, 35 1
Default. aspx, 543
DEL ke y, 24
De lete metho d, 369
D Deleting a form , 427
De li miter, 270
Data
Derived class, 5 18
convers ion, 70, 78-79 Descending keywo rd , 286
hiding, 492
Descri ption pane, 24, 25, 58 1
type Design
Boolea n , 107-8 mode , 59 1
Date, 87 modul ar, 180, 202-5
Double, 56 top-do wn , 180, 202
Intege r, 59 Desk-c heckin g, 15, 591
Single, 440 Dialog box
String, 69 Add New Item, 425
va lidatio n, 373 Erro r, 46
Data Source Confi gurati on W izard, 45 9
Font, 26
Database, 458, 459, 560
Input, 88-90
alterin g a, 479-8 1 Message, 90
brows ing a, 463 New Proj ect, 21
designing a, 483-8 4 Open Project, 28
Explorer, 463, 486 Dim statement, 56, 57, 68, 75, 259, 320, 340
702 • Index

dialog box, 46
Directory, 5, 589
file not found, 369
Disk, 4, 589
index out of range, 271
Displaying file exten sions, 5-6, 585
logic, 61
Di tinct query operator, 284, 341
runtim e, 61
Divide and conq uer meth od, 11
syntax, 61
Division opera tion, 54
Error Corre ct ion Options box, 71
Dolo op,21 8, 221,2 5 1
Error List window, 61, 99
flowchart, 218
ErrorMessage property, 552
pass throu gh a, 218
Esc key, 580
posttest form, 221
Event, 37-4 4, 535
prete st form, 218
declare an, 510
stepp ing throu gh a, 599
default, 46
Docu ment window, 22, 586
hand ler, 38
Docu ment ation , 8, 76-77
procedure, 19, 38, 52
Double data type, 56
user-defined, 509, 536
Doub leCli ck event , 244
Events butto n, 25, 42
Double-click with a mouse, 4
Except set opera t ion, 355
Double-subscripted variable, 319
Exception, 61,37 2
DP! settin g for monitor, 437, 584-8 5
Argu ment OutO fRan ge, 374
Drag with a mouse, 4
Catch block, 373-7 4
DrawEllipse meth od, 414
Finally block, 373- 74
DrawLine meth od, 438
lndex OutO fRan ge, 3 74
DrawRectangle meth od, 414
lnvalidCast, 372- 73,37 4
DrawString meth od, 9 1, 438
IO.D i recto ryNo tFoun d , 374
Driver, 205
IO.FileNot Found, 374
Drop Down comb o box, 404-5
10 .10, 374
DropDownList comb o box, 404-5
Nu llRefe rence, 374
DropDownStyle property, 404-5
Overflow, 3 74
Duck typing, 237
Try block, 373- 74
Exists meth od, 369
Exit Do statem e nt, 223
E Exit For state ment , 237, 27 1
e parameter, 44 Exiting Visual Basic, 577
Elem ent in XML, 383 Expo nent, 62
Elem ent of an array, 259 Expo nenti ation opera tion, 54
Else keyword, 112 Expression
Elself clause, 117 num eri c, 57
string, 72
Empty string, 7 5
Enabled property, 33, 410 Extension of a file name, 5, 585, 589
End displaying in 'Wind ows 7', 5, 585
Cia s, 492 displaying in Windows Vista, 5, 585
Func tion, 160, 16 1 displaying in Windows XP, 5-6, 585
If, 112
key, 27 F
Select, 132
F4 key, 24
Struc ture, 295
F5 key, 27, 577,5 92
Sub,3 8, 175
F8 key, 592
tag in XML, 383
F9 key, 592
EndO fStre am property, 366
Field, 297, 350
Ends With meth od, 108
of a database table, 45 8, 486
Enter event , 45
File, 589
Enter key, 580
add data to, 369
Error
closing a, 366, 368
detec tion, 46
Ind ex • 703

De lete metho d, 369 import ing a, 427


Ex ists method, 369 modal, 426
modes , 369 multip le, 425-26
Move metho J , 369 N ame proper ty, 30
name, 5, 589 printing a, 586
openin g fo r appe nd, 369 renami ng a, 30, 580
ope ning fo r input, 366 Text property, 30
ope ning for o utput, 367 Forma t menu , 31 , 32
sequen t ial, 3 76 Forma tC urrenc y functi on, 85, 99
text, 350, 366 Forma tDateTime functio n, 87
writing to a, 367 Forma tNumb er functio n, 85 , 99
Filenam e, 5, 589 Forma tPerce nt functio n , 85, 99
FileNa me proper ty, 360 FormC losing event, 427
Filespec, 5, 366, 589 From query operator, 282 , 341
FiliElli p e method, 439 Functi on
FillPie metho d, 439-40
argume nt, 160
FillRec tangle metho d , 438-39
array-va lued , 267- 68
Filter property, 360
Asc, 104, 154
Fina ll y block, 373- 74
Boolea n-va lued, 167
First me thod, 263, 283 , 341
built-in, 160
Flag va ri able, 245, 25 1, 266
ca lling a, 160
Flowch art, 9, 15, 25 4
C Dbl , 70, 78, 99
binary sea rch , 25 4
C hr, 104, 154
Do loop tested at bo tto m, 22 1
C lnt, 70, 78, 99
Do loop testeJ at top, 21 8
CS ng, 440
Fo r. .. Next loop, 23 1
CStr, 70, 99
If block, 11 2
definin g a, 160
Se lect Case bl ock, 133
Fo rmatC urrency, 85, 99
Flow li ne, 9
Fo rm atN umber, 85, 99
Foc us, 27
Forma tPerce nt, 85, 99
meth od, 45
1n t, 58, 99
Folder, 5, 589
in voking a, 16 1
Font, 26, 30, 52
Join , 27 1
Couri er New, 3 1
Math .Round, 58, 62 , 99
dialog box , 26
Math. Sq rt, 58, 99
d isp lay ing charac ters, 587
numeri c, 58
Micros oft Sa ns Seri f, 30
parame ter, 16 1
sett ing properties of a, 4 7
parame terless , 166
va riable, 92, 440, 445
proced ure, 160, 214
W ingd ings, 3 1
renaming a, 58 1-8 2
For Each loop, 266-6 7, 341
user-de fined, 160, 161
For... Nex t loop, 230-3 7, 251
body, 230
counte r va riab le, 230, 251
G
fl owcha rt, 23 1 G eneral group, 40
in itial va lu e, 230, 23 1 G eneral proced ure, 160
nested, 23 5 GetTex t meth od, 413
te rminat ing value, 230, 23 1 G etUppe rBound metho d, 322
Fo reCo lo r property, 25, 26, 38, 58 1 G o To state ment, 203
Foreign key, 468, 487 Graph ical user interface (GUI) , 2, 18
Fo rm,4 , 20,22, 43,52 Graph ics , 43 7- 46, 451
centering at run time, 580 object, 91 , 43 7
clos ing a, 427 printing, 444
deletin g a, 427 Greatest comm on divisor, 22 7- 28
Design er, 22, 39 GridVi ew contro l, 548
704 • Index

Integer data type, 59


Grou p box cont ro l, 146
Integer div ision ope rato r, 60
GU I, 2, 18 ) , 21, 586
Integrated Deve lopment Env ironment (IDE
lnte lli Sense, 37, 40, 47, 52, 57, 582
H Auto Corr ectio n , 71
Para mete r Info, 89, 168- 69, 180
H and les keyword, 38, 43 Quic k Info, 78
H ard ware, 2 Word o mple tion, 40, 168- 69, 180
H eader, 38, 43 Inte rface, 522
H eade rRow property, 548, 564 Inte rsec t set operation , 3 55
H eade rTex t prop erty, 301- 2, 35 1 Inte rva l property, 41 0
Hi erarc hy cha rt, 9, 11 Inva lid cast erro r, 372- 73
Hierarch y of classes, 519 Invo king Visua l Basic, 577
Hom e key, 27 Is keyword, 132, 136
, 45 1
H o rizon tal scro ll ba r cont ro l, 41 8-20 !SA test, 5 19
Hov er with a mouse, 4 IsNu meri c func tion, 108
H yper link cont rol, 55 1 Item of a list box, 402
Itera tion , 203
I
J
IDE, 21 , 586
Id entifier, 62 Jo in
lf block, 112, 154 func t ion , 27 1,34 1
flowchart, 1 12 of two tables, 468- 69, 4 71
step ping through an, 596 query operator, 469, 487
I mage property, 415
Imm edia te window, 593, 595
Impl icit line cont inua tion , 77
K
Impo rting a form, 427 Key
Imports Syst em.I O, 370 acce s, 29
58
Increme ntin g the va lue of a vari able, Enter, 580
Inde ntati on, 45, 582
Esc, 580
Index, 259 fore ign , 468, 487
number, 243, 251 ,402 of an array of struc tures, 302
of a For... Nex t loop, 233 prima ry, 468, 487
out of range exce ptio n , 2 71 Keyword, 38, 62
403
Inde xOf meth od, 73-7 4, 98, 268- 69,
Ineq ua lity sign in XM L, 385
Infin ite loop, 223 L
Infin ity, 62
Labe l cont ro l, 23, 29, 580
Inh erita nce, 5 18, 536
Larg eCh ange prop e rty, 41 9
Inherits keyword, 519
Last meth od, 263, 283, 34 1
Ini rial va lu e
Leav eeve nt, 42,4 5
of a For... Nex t loop, 230, 23 1
Leng th property, 73
of a num eric varia ble, 57
Let que ry ope rato r, 285
of a strin g varia ble, 75 at ions, 60
Level of prec eden ce for ari thm et ic oper
Inpu t, 2, 7,23 , 70,8 5,88 riable, 194, 214
Lifet ime of a va
dialog box, 88-9 0, 99
Line cont inu ati on, 77, 99
flow char t symbo l, 9
L!N Q, 28 1, 341, 396, 464, 486, 548
val idation, 108, 120
to XML, 383 -84
lnpu tBox func tion, 88-9 0
with 2D arrays, 325
Inse rt meth od, 403
with arrays, 28 1
Inse rtion po int, 543 243,
List box cont ro l, 23, 29- 30, 54, 62, 143,
Insta nce, 492, 493
402- 4, 450
variable, 494
ount prop erty, 243
lnt func tion, 58, 99
Index • 705

DataS o urce prope rty, 287, 341 Memory, 56, 190, 194
fill at des ign time, 143-4 4, 402 Menu bar, 20, 21, 22
fill with an array or query, 402 Menu Strip contr ol, 415- 18
index numb er, 243, 25 1 Message dialog box, 90, 99
print conte nts of, 586 MessageBox . how method, 90
search, 247 Meth od, 54, 495, 535
Se lected lndex property, 243 abstract, 527
Selec ted lndex Chan ged event , 243 Add, 54,98
Se lected ltem property, 287 Appe ndTex t, 369
Sorted prope rty, 244 C lea r, 54, 75, 98, 402
String Co llectio n Ed ito r, 143-4 4 C lose, 368
Text property, 143 , 244 C reateText, 367
Listl tem ollection Edito r, 555, 556 Exi ts, 369
Litera l, 98 icon, 40
nume ric, 54 lndex Of, 73-74 , 98
string, 68 plit, 270
Load event procedure, 26 1 S ubstri ng, 73, 98
Loca l ToLower, 73, 98
const ant, 194 ToString, 79
scope, 77, 194, 214,4 26 ToU pper, 73, 98
type infere nce, 236, 25 1 Trim , 73, 78, 98
variab le, 194, 2 14, 260 Write Line, 368
Loca ls window, 594, 598 Microsoft Access database fil e, 461
Log ic error, 61 Microsoft Sans Se rif font, 30
Logica l ope rator, 104, 106, 154 Min metho d, 263, 283 ,341
Loop Minim ize button , 4
Do, 218, 22 1, 25 1 Minim um prope rty, 419
For Each, 266-6 7 Mod opera tor, 60
For. .. Next, 230-3 7, 25 1 Moda l fo rm , 426
infin ite, 223 Mode, 369
keywo rd, 218 Modular design , 180, 202-5
nested, 235 Modu le, 11, 202
struct ure, 13, 203 Mo use
Loopi ng variab le, 267 cli ck with a, 4
doub le-c li ck with a, 4,
M d rag with a, 4
hove r with a, 4
Mach ine language, 2 right-cl ick with a, 4
Main Cont ent region, 540 Move method, 369
MainMenu contr ol, 451 Mov ing text, 579
Managing progra ms, 577-7 8 Mu ltiLin e property, 580
Mask property, 85-87 Mu lt iple
Mask ed tex t box contro l , 85-87 , 99 contro ls, 32
Math .Roun d funct ion, 58, 62, 99 decla ration s, 60
Math .Sqrt functi on, 58, 99 forms, 425-2 6, 451
Math ematica l notat ion, 54 Web page , 551
Max method, 263, 283,3 41 Multi plica tion opera tion, 54
Maximize butto n, 4 Mustl nherit keyword, 527
Maxim um prope rty, 41 9 MustO ve ride ke yword , 527
Me keywo rd , 43 , 438 MyBase keyword, 523
Me.C lose () statem ent, 45
Megaciti esData et, 46 1
Memb er
N
of a structure, 295 Name prope rty, 30
va ri ab~,494,4 98, 529 N amed const ant, 90-9 1, 99
706 • Index

Name space -levcl scope, 426 Options di alog box, 69 , 70


NaN (Not a Numb er), 62 O r logica l operator, 106
Narrowing, 75-76 O rder By que ry operator, 286, 341
Navig ateUr l property, 55 1 O utput , 2, 6, 23, 70, 85, 90
Navig ation toolbar, 479-8 1,487 fl owch art ymbo l, 9
Neste d ro a prin ter, 9 1-93, 444
For. .. Next loops, 235 Overridab le keywo rd, 523
lf blocks, 11 5 Ove rrides keyword, 523
loops , 237
New p
keyword, 493
procedure, 499 Page Load event , 55 4
program, 28, 577 Parameter, 161,1 76, 178,2 14, 598
Projec t butto n , 2 7 Info, 89, 168-6 9, 180
Projec t d ialog box, 21 Param eterless funct ion, 166
Next Paren t cl as, 518
keyword, 230 Paren t in XML, 383
metho d of Ra ndom class, 411 Paren theses, 60
Norm al code, 374 Parse metho d, 79
Not log ical operator, 106 Pass of a Do loop, 218
Notat ion Passin g, 176, 178
mathe matic al, 54 an array, 267
sc ientific, 62 by refere nce, 19 1, 195
Visual Basic, 54 by va lue, 190, 19 1, 195
Noth ing keyword, 75 Path, 5, 589
Nume ric Pens object, 438, 445
expression, 57 Pens va riable, 440
function, 58 Picture box control, 413-1 5, 451
literal, 54 Pie chart, 440
va ri able, 56-58 Pi xe l, 414,4 38
Point, 92
0 Polym orphism, 523, 536
Objec t, 42, 535 Pos iti on in a string, 73
box, 24 Pos iti oning contro ls, 3 1-33
code, 492 Postb ack, 55 4, 572
con tructor, 499 Prefi x of a contr ol nam e, 30
o riente d progra mming, 205 , 492 Prese rve keywo rd , 265,3 22,3 41
settin g properties of an, 40 Primary contr ol, 33
usea n, 518 Prima ry key, 468, 487
Open a file fo r Prime facto rizatio n, 22 7-28
appen d,369 PrintDocum ent contro l, 91, 99
in put, 366 Printi ng a fo rm , 586
outpu t, 367 Printi ng a progra m, 585
O pen a Visua l Basic program, 44-45 , 578 PrintP age event proced ure, 9 1
Open a Web program, 548 PrintP rev iewDialog contr ol, 92
Ope n Projec t dia log box , 28 Pri vate keywo rd, 38, 498
OpenFileD ialog contro l , 359-6 0 Proble m solving, 3
Filter prope rty, 360 Procedure
Opera tor event , 38, 52
logica l, 106, 154 Funct ion, 160, 214
rel ationa l, 104, 105, 154 ge neral, 160, 214
Optio n heade r, 38, 43
Exp licit, 69, 99 hiding a, 582
Infer, 69, 236, 288 name , 43, 180
Strict, 69, 76, 99 renam ing a, 58 1-82
Index • 707

step, 592 C heckedC hanged event, 149


Sub, 160, 175 Text property, 146
Process ing, 2, 7 RadioButtonList control, 55 5
Program, 2, 6, 19, 20 RaiseEvent statement, 509-10
clos ing a, 33, 578 Random class , 411 , 4 50
development cycle, 6-8 Range variable, 282
documentation, 76-77 Range , specifying in a Case clause, 13 2
modes, 59 1 RangeValidator control , 55 2
opening a, 28, 44-45 , 578 ReadA llLines method, 262, 341 , 361, 54 7
open ing a Web, 548 Recent Projects, 28
printing a, 585 Record , 29 7, 350
region, 39 of a database table, 458, 486
renaming a, 549, 578 ReDim statement, 264, 265, 322, 325, 340
run ning a, 2, 27 , 577 Reference, passing by, 19 1,1 95
sav ing a, 27, 577- 78 Referential integrity, 468
starting a new, 28 Refresh button , 44
terminating a, 27 Refresh method, 446
Programmer, 2 Relational
Project, 6, 19 database, 458, 468
Prompt parameter, 88-90 operator, 104, 105, 154
Properties Remove method, 403
button, 25 RemoveAt method, 403
icon, 40 Remov ing a breakpoint, 592 , 595
simplify setting of, 58 1 Rename
window, 22 , 24-26 a form , 580
Property a variable or general procedure, 58 1-82
abstract, 527 a VB prog ram , 578
block, 494,498-99,535 a VWD program, 549
Get, 494, 498-99, 535 Repetition
read on ly, 494 sentinel contro lled, 221
Set, 494, 498-99,535 structure, 13
setting a, 58 1 RequiredFieldValidator contro l, 552
window, 58 1 Reserved word , 38, 62
write only, 494 Restore original layout of IDE, 586
Prox imity line, 3 1, 32 Retu rn a valu e, 58
Pseudocode, 9, 10-11 , 16 Return keyword, 161
Pu blic keywo rd , 426, 498 Reusable code, 204
Push pin, 22, 23, 3 1 Reuse code, 586
Right-click with a mouse, 4
Roo t folder (d irectory), 5, 589
Q RowHeadersVisible property, 301, 35 1, 581
Ru le of Entity Integrity, 471,487
Query, 282 Ru le of Referential Integrity, 468, 487
clause, 282 Run
expression, 282 a program, 27 , 54 , 577
operator, 282 mode, 591
range variab le, 282 to cursor, 592
sou rce data, 282 without debugging, 549
Q ui ck Info feat ure, 78 Runtime error, 61
Q uotation mark character, 69, 105

s
R
Save a program, 27, 47 , 577- 78
Rad io button control, 146, 150 Save A ll button, 27,5 77
C hecked property, 14 7 Sc ientific notation, 62
708 • Index

Scope of a variab le or constant, 77-78,99, 161, oftware, 2


194,214,426 So luti on, 6
block-leve l, 136, 194, 223 , 23 1 So lution Explorer window, 22 , 262, 578
class- level, 77, 194,4 26 Sort method, 288
loca l, 77, 194,426 Sorted prope rty, 244 , 402
namespace- level, 426 So rting, 286
Scroll Sorting a text file, 352
bar controls, 4 18-20 Spaghetti code, 203
box,41 8, 419 Split method, 270, 34 1, 350
event, 419 Sta rt angle, 439
Searching a text file, 358 Start Debugging button, 27, 549, 577
Second-level menu item, 415 Start page, 20, 21
Se lect Case block, 130, 132, 136, 154 Start tag in XM L, 383
flowchart, 133 Sta rtsWith method, 108
stepp ing through a, 596-97 Sta rtup form, 425
Select query operator, 282, 284, 285, 300, 306, tatic text, 543
341,350 Step keyword , 233, 237
Se lected control, 24 Stepp ing to deb ug, 592
Se lected lndex property, 243, 402 Stepwise refinement , 202
Se lectedl ndexChanged event, 149, 243, 402 Stop Debugging button, 27
Selected ltem property, 287 Store frequently u ed code, 586
Se lectedText property, 413 StreamReader object, 366
Se lect ing Strea mWriter obj ect, 367
mu ltiple controls, 32, 580 Stretchlmage setting, 414
text, 579 String, 68-75
Selector, 130, 132, 136, 154 data type, 69
Se lf-ev ident code, 108 defau lt va lue, 75
Sender parameter, 44 empty, 75
Sentinel va lue, 22 1 express ion, 72
Sequence structure, 11, 203 literal, 68
Sequential file, 3 76 substring, 73, 98
Server, 540 variable, 68
Server Explore r, 464, 486 zero- length, 75
Set operations, 355 String Co llection Ed itor, 143-44
SetTex t method, 4 13 Structure, 295,3 41
Setting a breakpoint, 592, 595 complex, 305
Settings box, 25 dec ision, 12, 203
Sh ift+ A lt+ Backspace key combination, 5 79 loop, 13, 203
Shift+ F8 key combination, 592 pass ing a, 304
Shift+ Tab key comb ination, 28 repetition, 13
Shortcut key, 41 5 equence, 11, 203
Show A ll Files button, 44 , 262 variable, 295
ShowDialog method, 360, 426 Structured exception handling, 372-74, 396
Sibling in XML, 383 Structured progra mming, 203-5, 214
Simp le tub programm ing, 205
combo box style, 404-5 Sty le of a combo box, 404- 5
va ri able, 258 Sub
Simulation, 411 compared to Function procedure, 175
Single data type, 440 keyword , 38, 175
Single-subscripted variable, 3 19 proced ure, 160, 175 ,2 14
Size of an array, 259, 262 Subfolder, 5, 589
SizeMode property, 414 , 415 Subroutine, 38
Sizing handle, 22, 23, 24 Subscript, 259
ma ll hange prope rty, 41 9 ubscripted variable, 259
Snap line, 31,32 Substring method, 73, 98
Index • 709

Subtra ction operat ion, 54 ToArray metho d, 284


Su m method, 263, 283,34 1 ToLowe r meth od, 73, 98
weep angle, 439 Too lbar, 20, 21, 22
Symbo lic rename, 58 1-82 Too lbox , 23, 3 7
Syntax error, 61, 169 tab, 22
System. IO, 3 70 Tooltip , 22
ToolTi p contro l, 41 2-13, 45 0
ToolTi p on Too lTi p1 property, 413
T Top leve l menu item, 41 5
Top-down
Tab chart, 11
index, 33 design, 180, 202
key, 28 ToStri ng metho d, 79
order, 33, 52 ToUpp er method, 73, 98
Tab lndex property, 58 1 Trim method, 73, 78, 98
Table Truth value, 109
ANS I, 104, 575-76 Try-Ca tch-Fin ally bl ock, 373-74
contro l, 544-4 7 Two-d imensional array, 3 19
ed iting a, 479-8 1 Type property, 552
of a database, 458, 486 Typecasting, 70, 78-79
Tasks button , 23 TypeO f keyword, 529
Termin ating an infinite loop, 223
Termin ating va lu e, 230, 231
Testing a progra m, 8
Tex t u
box contro l, 23-28, 70 Uncom ment button , 76
copying, 579 Undersco re charac te r, 77
manip ulation, 578-79 Undo a change, 579
moving, 579 Union set operat ion, 355
property, 25, 28, 32, 143, 146, 148, 244, 402, Until keyword , 221, 223
405,41 6 Upper bound of an array, 259, 263
resizing, 5 79
User, 3
se lecting a block of, 578, 579 User-defined
undoin g a change, 579
event, 509, 536
Text file, 262, 350,36 6,547, 583
function, 160, 161
close a, 583
type (UDT) , 295
crea te a, 583
de lete a, 584
eli play a, 583
import into a progra m, 583
v
mod ify a, 584 Valida t ion contro l , 552
reorga nize a, 353 Value
save a, 583 ANSI, 104, 575-76
search a, 358 default, 57 , 75
sort a, 352 initi al, 57, 230, 23 1
TextA iign property, 29 list, 130
TextC hanged event, 41 pass ing by, 190, 191, 195
Then keyword, 11 2 property, 419
Ti ck event, 410 step, 233
Timer contro l, 410, 450 termin ating, 230, 23 1
Title ba r, 4 tru th, 109
Title parameter, 90 Variable, 98, 258
To keywo rd accumulator, 22 1
in a Case clause, 132, 136 array, 258
in a For .. . Next loop, 230 Brushes, 440
710 • Index

Variab le (Continued) introd uction to, 18-20


class- leve l, 194, 260 invo king, 21, 577
count er, 22 1, 230, 234, 23 7, 251 printin g progra ms, 585
declar ing a, 68, 75 versions, 20
determ ining type of a , 78 Vi sual Web Devel oper (VWD ), 540, 571
Doubl e, 56
double-subsc ripted, 3 19 w
flag, 245,2 5 1, 266
increm enting the value of a, 58 Watch windo w, 593, 599
instan ce, 494 Web app licatio n , 540- 73
Intege r, 59 Where query operat o r, 282, 285, 341
lifetim e of a, 194 While keywo rd , 218, 223
loca l, 194, 214, 260 Widen ing, 75-76
memb er, 494, 498 Windows , 4
namin g a, 56 '7', 3
numeri c, 56-58 config uring enviro nment , 584
passin g a, 190, 19 1, 195 Exp lorer, 5, 587
Pens, 440 Vista, 3
renam ing a, 581-8 2 XP, 3
scope of a, 77-78 , 194, 426 Wingd ings font, 3 1
sim ple, 258 With Events keywo rd, 5 10
single-subsc ripted, 319 Word Comp letion fea ture, 40, 168-6 9, 180
String, 68 Word wrap, 582
subscr ipted, 259 Write AllLin es metho d, 352, 396
with unassigned va lue, 62-63 WriteL ine metho d, 368
Vertic al croll bar contro l, 418-2 0, 451 Writin g to a file, 367
View Code button , 44
View Design er button , 44
View menu, 22, 24 , 40
X
Visib le property, 33,3 7 XElem ent object , 383
Visua l Ba ic, 2, 3 XML fi le, 382
contro ls, 20
creatin g a progra m, 37
design ing a program, 19 z
events , 37
Zero-based numbe ring, 73
exitin g, 577
Zero-length string, 75
H ow Tos, 577-8 7
Save money. Lighten your backpack.
Access your textbooks anytime, from anywhere.
This title is available as an eTextbook from CourseSmart.
Purchase your assigned textbook as a CourseSmart eTextbook, and
stop lugging books around campus! You can also access CourseSmart
eTextbooks from your iPhone.

Instructors, request your exam copies online and get instant access.
Learn more at coursesmart.com

eed e
This textbook is enhanced with VideoNotes-step-by-step tutorials
available whenever you need them! Whether you are studying for an
exam or need help with a difficult topic, VideoNotes give you additional
examples of key concepts and walk you through the entire problem-
solving process, making sure that you understand each step-just
as if you were in your instructor's office. Throughout the book, you'll
see icons placed in the margin that let you know that a VideoNote is
available to expand on a programming example or problem solution .

With the purchase of a new copy of this textbook, you have access
to VideoNotes. Why not use them? To use VideoNotes, just follow the
directions on the access card at the front of the book.

Prentice Hall
m
is an imprint of )>
z

-------
PEARSON
www.pearsonhighered.com

You might also like