Table Of Contentbra17208_fm_i-xxviii 4/11/08 9:17PM Page i ntt MHBR:MH-BURR:MHBR023:MHBR023-FM:
P
ROGRAMMING IN
V B 2008
ISUAL ASIC
Julia Case Bradley
Mt. San Antonio College
Anita C. Millspaugh
Mt. San Antonio College
bra17208_fm_i-xxviii 4/11/08 9:17PM Page ii ntt MHBR:MH-BURR:MHBR023:MHBR023-FM:
PROGRAMMING IN VISUAL BASIC 2008
Published by McGraw-Hill, a business unit of The McGraw-Hill Companies, Inc., 1221 Avenue of
the Americas, New York, NY, 10020. Copyright © 2009 by The McGraw-Hill Companies, Inc.
All rights reserved. Previous editions © 1996, 1998, 1999, 2003, 2005, and 2006. No part of this
publication may be reproduced or distributed in any form or by any means, or stored in a database or
retrieval system, without the prior written consent of The McGraw-Hill Companies, Inc., including, but not
limited to, in any network or other electronic storage or transmission, or broadcast for distance learning.
Some ancillaries, including electronic and print components, may not be available to customers
outside the United States.
This book is printed on acid-free paper.
1 2 3 4 5 6 7 8 9 0 CUS/CUS 0 9 8
ISBN 978-0-07-351720-9
MHID 0-07-351720-8
Vice President/Editor in Chief: Elizabeth Haefele
Vice President/Director of Marketing: John E. Biernat
Senior sponsoring editor:Scott Davidson
Developmental editor II:Alaina Grayson
Lead media producer: Damian Moshak
Marketing manager: Tiffany Wendt
Director, Editing/Design/Production: Jess Ann Kosic
Project manager:Marlena Pechan
Senior production supervisor:Janean A. Utley
Senior designer:Srdjan Savanovic
Media developmental editor:William Mulford
Media project manager:Mark A. S. Dierker
Typeface: 11/13 Bodoni
Compositor:Aptara, Inc.
Printer:R. R. Donnelley
Cover credit: Image:Epoxy/Getty Images
Library of Congress Cataloging-in-Publication Data
Bradley, Julia Case.
Programming in Visual Basic 2008 / Julia Case Bradley, Anita C. Millspaugh.—7th ed.
p. cm.
Includes index.
ISBN-13: 978-0-07-351720-9 (alk. paper)
ISBN-10: 0-07-351720-8 (alk. paper)
1.Microsoft Visual BASIC. 2.BASIC (Computer program language)I. Millspaugh, A. C.
(Anita C.) II. Title. III. Title: Visual Basic 2008.
QA76.73.B3B6967 2009
005.2'762—dc22
2008012904
The Internet addresses listed in the text were accurate at the time of publication. The inclusion of a Web
site does not indicate an endorsement by the authors or McGraw-Hill, and McGraw-Hill does not
guarantee the accuracy of the information presented at these sites.
www.mhhe.com
bra17208_fm_i-xxviii 4/11/08 9:17PM Page iii ntt MHBR:MH-BURR:MHBR023:MHBR023-FM:
P
REFACE
Visual Basic (VB) has become such a popular programming language for sev-
eral reasons. VB is easy to learn, which makes it an excellent tool for under-
standing elementary programming concepts. In addition, it has evolved into
such a powerful and popular product that skilled Visual Basic programmers are
in demand in the job market.
Visual Basic is fully object-oriented and compatible with many other
languages using the .NET Framework. This book incorporates the object-
oriented concepts throughout, as well as the syntax and terminology of the
language.
Visual Basic is designed to allow the programmer to develop applications
that run under Windows and/or in a Web browser without the complexity gener-
ally associated with programming. With very little effort, the programmer can
design a screen that holds standard elements such as buttons, check boxes, radio
buttons, text boxes, and list boxes. Each of these objects operates as expected,
producing a “standard” Windows or Web user interface.
About This Text
This textbook is intended for use in an introductory programming course, which
assumes no prior knowledge of computer programming. The later chapters are
also appropriate for professional programmers who are learning a new language
to upgrade their skills.
This text assumes that the student is familiar with the Windows operating
environment and can use an Internet browser application.
Approach
This text incorporates the basic concepts of programming, problem solving,
programming logic, as well as the design techniques of an object-oriented,
event-driven language. VB is a fully object-oriented language, which includes
inheritance and polymorphism. Object-oriented programming (OOP) is intro-
duced in Chapter1, and its features appear in every chapter of the book.
Chapter topics are presented in a sequence that allows the programmer to
learn how to deal with a visual interface while acquiring important program-
ming skills such as creating projects with objects, decisions, loops, and data
management.
A high priority is given to writing applications that are easy for the user to
understand and to use. Students are presented with interface design guidelines
throughout the text.
iii
bra17208_fm_i-xxviii 4/12/08 2:58PM Page iv ntt Os9:Desktop Folder:TEMPWORK:Don't Delete (Jobs):MHBR023/Bradley:
Bradley_Walkthru.indd Page 2 4/12/08 2:47:49 PM user-s175 /Users/user-s175/Desktop/TEMPWORK/APRIL/12:04:08/MHBR023
Text Features
Object-Oriented Concepts
are presented throughout the text to offer
students an introduction to object-oriented
design before learning to create their own
classes.
Try
' Convert quantity to numeric variable.
C QuHantAityIPnteTger E= IRnteger.Parse(QuantityTex
2Try
' Convert price if quantity was successf
PriceDecimal = Decimal.Parse(PriceTextBo
' Calculate values for sale.
ExtendedPriceDecimal = QuantityInteger *
DiscountDecimal = Decimal.Round((Extende
UsDeisrc oIunntetdePrrifceaDecceim al = ExtendedPriceDe
‘ Calculate summary values.
DeQsuaingtintySumInteger += QuantityInteger
DiscountSumDecimal += DiscountDecimal
DiscountedPriceSumDecimal += DiscountedP
SaleCountInteger += 1
AverageDiscountDecimal = DiscountSumDeci
at the completion of this chapter, you will be able to . . .
1.Use text boxes, masked text boxes, rich text boxes, group boxes, check
boxes, radio buttons, and picture boxes effectively.
2.Set the BorderStyle property to make controls appear flat or three-dimensional.
3.Select multiple controls and move them, align them, and set common properties.
4.Make your projects easy for the user to understand and operate by defining
access keys, setting an Accept and a Cancel button, controlling the tab
sequence, resetting the focus during program execution, and causing
ToolTips to appear.
5.Clear the contents of text boxes and labels.
6.Make a control visible or invisible at run time by setting its Visible property.
7.Disable and enable controls at design time and run time.
8.Change text color during program execution.
9.Code multiple statements for one control using the Withand EndWith
statements.
10.Concatenate (join) strings of text.
11.Download the Line and Shape controls, add them to the toolbox, and use the
controls on your forms.
100 V I S U A L B A S I C User Interface Design
Good Programming Habits
1.Always test the tab order on your forms. Fix it if necessary by changing
the TabIndex properties of the controls.
2.Provide visual separation for input fields and output fields and always
make it clear to the user which are which. Interface Guidelines
3.Make sure that your forms can be navigated and entered from the key-
board. Always set an Accept button (AcceptButton property) for every
form.
4.To make a label maintain its size regardless of the value of the Text
property, set AutoSize to False. are presented to offer students a better
5.To make the text in a text box right justified or centered, set the
6.TYeoxut Acalnig uns per tohpee rCtyh.ecked property of a check box to set other properties understanding of meeting user needs
that must be True or False.
and employing industry standards.
bra17208_fm_i-xxviii 4/12/08 2:58PM Page v ntt Os9:Desktop Folder:TEMPWORK:Don't Delete (Jobs):MHBR023/Bradley:
Bradley_Walkthru.indd Page 3 4/12/08 2:47:59 PM user-s175 /Users/user-s175/Desktop/TEMPWORK/APRIL/12:04:08/MHBR023
304 V I S U A L B A S I C Lists, Loops, and Printing
➤
Feedback 7.3
1.Identify the statements that are correctly formed and those that have er-
rors. For those with errors, state what is wrong and how to correct it.
(a)For IndexDecimal = 3.5D To 6.0D, Step 0.5D
Next IndexDecimal
(b)For IndexInteger = BeginInteger To EndInteger Step IncrementInteger Feedback Questions
Next EndInteger
(c)For 4 = 1 To 10 Step 2
Next For
(d)For IndexInteger = 100 To 0 Step –25 give students time to reflect on the
Next IndexInteger
(e)For IndexInteger = 0 To –10 Step –1
Next IndexInteger current topic and to evaluate their
(f) For IndexInteger = 10 To 1
2.How Nmeaxnty Itinmdeesx wIniltl ethgee rbody of the loop be executed for each of these understanding of details.
examples? What will be the value of the loop index after normal com-
pletion of the loop?
(a)For CountInteger = 1 To 3
(b)For CountInteger = 2 To 11 Step 3
(c)For CountInteger = 10 To 1 Step –1
(d)For CounterDecimal = 3.0D To 6.0D Step 0.5D
(e)For CountInteger = 5 To 1
Making Entries Appear Selected
You can use several techniques to make the text in a text box or list appear
selected.
Selecting the Entry in a Text Box Tips
in the margins help students avoid
potential trouble spots in their
programs and encourage them to
develop good programming
habits.
172 V I S U A L B A S I C Decisions and Conditions
142 V I S U A L B A S I C Variables, Constants, and Calculations
➤
Feedback 4.2
Fortunately, the Visual Studio smart editor helps you enter the arguments;
you don’t have to memorize or look up the argument lists. Type Assume that FrogsInteger=10,ToadsInteger=5, and PolliwogsInteger TIP
bst“fhohMlreeo ewtlfhTseoeseofrdatm Ss ge4eshen lBoodoefwfco ottxthmf h. teStheeh h e2teaho 1 rswoI gisndg(ui”t ngme( naFaleltaniiungtSdurtuee rrlIn eientsssh tte 3e,ai n.lpto8l ioryt)Sh .po2 eeNuu1n p po sws.rte iieaF gcvnponeitor oa iptutenoussx rt uaueehmspxsee a pf,wfm oliueigrpts ,uht lethre o ete,th h stteSoeeh h lafsueioitrcpm wstt ht pomt ehorlir efefde ty t ohsh atiwoehgrden nes. a i2ac(gtW1orunrn roaepecwt o euotsspnhrs etalai.ys-)tt TIP = 6.1 W.hIEEaflnt sd wFe rIFFilofrrl goobsggeIss dnRRitaaseddpgiilaeooyrBBe uud>tt f ttoPooronn el..alCCcihhhwee ooccfgkk tseehIdden ft==oe llgTFoerawruli esnT egh setantements? IraInonfdrserE.e nlgVtasaitseiruodanlwel sciBstah aon sf ti hhcthe ee alp llaiw nsydato eyuuns n tcammatiaatocttnchch. heee■drs-
nmaybnoeoauedltdd t(a syFa pndiogedenu s lttrychhe rete ih3 p tde.et9ei xto)set.nc xoT rtofih pofte hftt iheatoh arnmget u ceamhmsrsgeaeausnngsmgtaee eg tsahne nta toad ta n typaedo pl culte oh yaameorr uesmti tieaalnxbe, p ottbhheuaecetr t t slechaedaasc pttto otalni iroedngnn eua,t ermosgrfee u iltnsmeh tces et(h n Fptothiow geapun pu1r ppie4ne. t3 ahAb.r 1osffotl0 eidr)nr-,. Yatshingoednu a mdtuocorauwens.en ■uatosr ero vwieth wek eayknse dyr abstoehaleerrcd t t htauhpne 2.IEEfln sdFe rIRRofeegsssuuIllntttTTeeegxxettrBB oo>xx ..TTToeeaxxdtts I==n t""eIIgtte''rss +tt hhPeeo lftlroioawgdossg. s"aInndt etgheer pTohlelniwogs."
3.If PolliwogsInteger > ToadsInteger And FrogsInteger <> 0 _
Figure 3.8 Or ToadsInteger = 0 Then
ResultTextBox.Text = "It's true."
IntelliSense pops up the first of 21 signatures for the Showmethod. Use the up and down arrows to see the other possible Else
argument lists. ResultTextBox.Text = "It's false."
End If
4.Write the statements necessary to compare the numeric values stored
inApplesTextBox.Text and OrangesTextBox.Text. Display in Most-
TextBox.Text which has more, the apples or the oranges.
5.Write the Basic statements that will test the current value of Bal-
anceDecimal. When BalanceDecimal is greater than zero, the check
box for Funds Available, called FundsCheckBox, should be selected,
theBalanceDecimal set back to zero, and CountInteger incremented by
one. When BalanceDecimal is zero or less, FundsCheckBox should not
be selected (do not change the value of BalanceDecimal or increment
the counter).
Using If Statements with Radio Buttons
andCheckBoxes
In Chapter2 you used the CheckedChanged event for radio buttons and check
boxes to carry out the desired action. Now that you can use Ifstatements, you
should not take action in the CheckedChanged event procedures for these con-
l I d d i hih i l d
bra17208_fm_i-xxviii 4/12/08 2:58PM Page vi ntt Os9:Desktop Folder:TEMPWORK:Don't Delete (Jobs):MHBR023/Bradley:
Bradley_Walkthru.indd Page 4 4/12/08 2:48:07 PM user-s175 /Users/user-s175/Desktop/TEMPWORK/APRIL/12:04:08/MHBR023
Text Features
3.The PrintPage event.
4.The DrawStringmethod.
5.System.Drawing.Printing.PrintPageEventArgs.
6.MarginBounds.Left.
7.The PrintPreviewDialog component.
Your Hands-On Programming Example
Your Hands-On
Create a project for R ’n R—for Reading ’n Refreshment that contains a drop-
down combo box of the coffee flavors and a list box of the syrup flavors. Adjust
the size of the boxes as needed when you test the project. The controls should Programming Examples
have labels above them with the words Coffeeand Syrup. Enter the initial val-
ues for the syrup flavors and coffee flavors in the Properties window. Set the
Sorted property of both lists to True. The user will be able to add more coffee
flavors to the list at run time by typing in the top portion of the combo box and
selecting a menu item. guide students through the process of
Coffee Flavors Syrup Flavors
Espresso Roast (None) planning, writing, and executing Visual Basic
Jamaica Blue Mountain Chocolate
Kona Blend Hazelnut programs.
Chocolate Almond Irish Cream
Vanilla Nut Orange
C H A P T E R 6 283
Key Terms
access level 268 Public 268
About box 257 scope 267
Friend 268 Showmethod 262
Hidemethod 263 ShowDialogmethod 262
Programming mmooddaelless262262 ssptalratsuhp sfcorremen252460
namespace 269 Static 268
Private 268
Exercises Review Questions
1.List some of the items generally found in an About box.
2.What is the purpose of a splash screen?
3.What is the term used for the first form to display in a project?
4.How can you choose a different form as the startup form after the project
test students' understanding of the has been created?
5.Explain how to include an existing form in a new project.
6.What is the assembly information? How can you change the information?
How can you use the information?
specific programming skills covered in 7.Explain the difference between modaland modeless.
8.How does the Showmethod differ from the ShowDialogmethod?
9.Explain when the form’s Load event and Activated event occur. In which
that chapter. eanveswnte rp raolwceadyus rteh es hsoaumled? you place code to initialize screen fields? Is the
10.Explain the differences between Public, Private, and Friendaccess
levels.
11.What is a static variable? When would it be useful?
12.How can you run a compiled VB program outside the Visual Studio IDE?
Programming Exercises
Note:For help in basing a new project on an existing project, see “Copy and
Move a Project” in AppendixC.
6.1 Modify Programming Exercise 5.5 (the flag viewer) to include a splash
screen and an About box.
Menus
File Country Display Help
Exit United States Title About
Canada Country Name
Japan Programmer
Mexico
6.2 Create a project that will produce a summary of the amounts due for Pat’s
Auto Repair Shop. Display a splash screen first; then display the main form,
which has only the menus. If you wish, you can add a graphic to the form.
286 V I S U A L B A S I C Multiform Projects
Case Studies
VB Mail Order
Modify the VB Mail Order project from Chapter5 to
include a splash screen, an About box, and a summary
form. Include an image on both the Splash form and
the About box.
VB Auto Center
Create a project that uses four forms. Add the form Main Form Menus
bfmMreoaalmi inwn tifFhtohero m rtCmh, he:a a Twsphptoeelrar dmss5h:a Vis“ncVB rafe olAelrenmuy,t oasB hncoodauu salleend v sAdaturibsddop yuAl atau ybnt ooad x Clc.areregnaette elra a-- FIiEnlxpieutt Sale ECdFoioltnotr...... HAelbpout
Mimeaegtein(sg) .all your vehicle’s needs” and appropriate chanTghee t hCeo lloarrgaen dla Fboenl tointe tmhes fsohromu.ld allow the user to
The Input Saleitem should display the form from
Chapter5.
Video Bonanza
Mseopdairfayt et hteh eV ipdreooj eBcot nianntoz am puroltjiepclte frfoormm Cs.h Ianpctelurd5e toa Case Studies
summary form, a splash screen, and an About box.
Very Very Boards provide continuing-theme exercises that
Modify the Very Very Boards project from Chapter5 to
ssuepmamraatrey tfhoerm p, rao jsepclta sihn tsoc rmeeunlt,i apnled faonr mAsb.o uInt cblouxd.e a may be used throughout the course,
providing many opportunities to expand
on previous projects.
bra17208_fm_i-xxviii 4/12/08 2:58PM Page vii ntt Os9:Desktop Folder:TEMPWORK:Don't Delete (Jobs):MHBR023/Bradley:
Bradley_Walkthru.indd Page 5 4/12/08 2:48:15 PM user-s175 /Users/user-s175/Desktop/TEMPWORK/APRIL/12:04:08/MHBR023
For the Student
Student Data
,
available on the texts Web
site offers a debugging
project, database files for the
programming exercises and
case studies, graphics, and
sound files.
Visit the VISUAL BASIC 2008 Web site at:
http://www.mhhe.com/VB2008/ for
instructor and student resources.
bra17208_fm_i-xxviii 4/12/08 2:58PM Page viii ntt Os9:Desktop Folder:TEMPWORK:Don't Delete (Jobs):MHBR023/Bradley:
Bradley_Walkthru.indd Page 6 4/12/08 2:48:22 PM user-s175 /Users/user-s175/Desktop/TEMPWORK/APRIL/12:04:08/MHBR023
For the Instructor
Instructor Web Site
includes: Instructor Manual with teaching hints,
outlines, and a matrix of the chapter features
required for each programming exercise;
PowerPoint Slides; Testing Files (using EZ Test
and in Word files); as well as Solutions to End-
of-Chapter Exercises.
bra17208_fm_i-xxviii 04/18/2008 3:07 pm Page ix pinnacle OSX:Desktop Folder:TEMPWORK:Don't Delete (Jobs):MHBR023/Bradley:
Bradley_Walkthru.indd Page 7 4/18/08 3:08:52 PM user-s175 /Users/user-s175/Desktop/TEMPWORK/APRIL/18:04:08/MHBR023
PowerPoint Presentations
provide instructors with complete, detailed
presentations that walk students through the
important concepts covered in each chapter.
Visit the VISUAL BASIC 2008 Web site at:
http://www.mhhe.com/VB2008/ for
instructor and student resources.
Description:The author team of Julia Bradley and Anita Millspaugh remain the guiding light in Programming with Visual Basic 2008 for countless students around the world. How better to master the most popular object-oriented programming language than to use the bestselling textbook? Be at the cutting edge of tec