Você está na página 1de 576

PUBLISHED BY

Microsoft Press
A Division of Microsoft Corporation
One Microsoft Way
Redmond, Washington 98052-6399
Copyright 2010 by Michael Halvorson
All rights reserved. No part of the contents of this book may be reproduced or transmitted in any form or by any means
without the written permission of the publisher.
Library of Congress Control Number: 2010924441
Printed and bound in the United States of America.
1 2 3 4 5 6 7 8 9 QWT 5 4 3 2 1 0
Distributed in Canada by H.B. Fenn and Company Ltd.
A CIP catalogue record for this book is available from the British Library.
Microsoft Press books are available through booksellers and distributors worldwide. For further information about
at fax (425) 936-7329. Visit our Web site at www.microsoft.com/mspress. Send comments to mspinputmicrosoft.com.
Microsoft, Microsoft Press, Access, ActiveX, Arc, Azure, DataTips, Excel, Expression, Halo, IntelliSense, Internet Explorer,
MS, MSDN, MS-DOS, PowerPoint, SharePoint, Silverlight, SQL Server, Visual Basic, Visual C#, Visual C++, Visual
InterDev, Visual Studio, Windows, Windows Azure, Windows Server, Windows Vista and Zoo Tycoon are either registered
trademarks or trademarks of Microsoft Corporation in the United States and/or other countries. Other product and company
names mentioned herein may be the trademarks of their respective owners.
The example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted
person, place, or event is intended or should be inferred.
This book expresses the author`s views and opinions. The information contained in this book is provided without any
express, statutory, or implied warranties. Neither the authors, Microsoft Corporation, nor its resellers, or distributors will
be held liable for any damages caused or alleged to be caused either directly or indirectly by this book.
Acquisitions Editor: Ben Ryan
Developmental Editor: Devon Musgrave
Project Editor: Valerie Woolley
Editorial Production: Christian Holdener, S4Carlisle Publishing Services
Technical Reviewer: Technical Review services provided by Content Master, a member of CM Group, Ltd.
Cover: Tom Draper Design
Body Part No. X16-88509
For Henry
v
Contents at a GIance
Part I Getting Started with Microsoft VisuaI Basic 20l0
l fxpIorng the VsuaI Studo Integrated DeveIopment
fnvronment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2 Wrtng Your frst Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
3 Workng wth 1ooIbox ControIs . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
4 Workng wth Menus, 1ooIbars, and DaIog oxes . . . . . . . . . . . 97
Part II Programming lundamentaIs
5 VsuaI asc VarabIes and formuIas,
and the .Nf1 framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . l23
6 Usng Decson Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . l59
7 Usng Loops and 1mers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . l8l
8 Debuggng VsuaI asc Programs . . . . . . . . . . . . . . . . . . . . . . . . 209
9 1rappng frrors by Usng Structured frror HandIng. . . . . . . . . 227
l0 Creatng ModuIes and Procedures . . . . . . . . . . . . . . . . . . . . . . . . 247
ll Usng Arrays to Manage Numerc and Strng Data . . . . . . . . . . 273
l2 Workng wth CoIIectons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
l3 fxpIorng 1ext fIes and Strng Processng . . . . . . . . . . . . . . . . . 3l3
Part III Designing the User lnterface
l4 Managng Wndows forms and ControIs at Run 1me . . . . . . . 35l
l5 Addng Graphcs and Anmaton fffects . . . . . . . . . . . . . . . . . . . 375
l6 Inhertng forms and Creatng ase CIasses . . . . . . . . . . . . . . . . 393
l7 Workng wth Prnters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4l5
Part IV Database and web Programming
l8 Gettng Started wth ADO.Nf1 . . . . . . . . . . . . . . . . . . . . . . . . . . . 44l
l9 Data Presentaton Usng the DctcCridView ControI . . . . . . . . . 467
20 Creatng Web Stes and Web Pages by Usng VsuaI
Web DeveIoper and ASP.Nf1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49l
vii
1abIe of Contents
AcknowIedgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv
Introducton . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv
Part I Getting Started with Microsoft VisuaI Basic 20l0
l fxpIorng the VsuaI Studo Integrated DeveIopment
fnvronment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1he visual SLudio DevelopmenL FnvironmenL. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1he visual SLudio 1ools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1he Designer. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 0
Running a visual 8asic Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1he ProperLies Window. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Moving and Resizing Lhe Programming 1ools . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Moving and Resizing 1ool Windows. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Docking 1ool Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Hiding 1ool Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
SwiLching Among Open Files and 1ools
by Using Lhe lDF NavigaLor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Opening a Web 8rowser WiLhin visual SLudio . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
CeLLing Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Managing Help SeLLings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Using F Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
CusLomizing lDF SeLLings Lo MaLch
SLep-by-SLep Fxercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
SeLLing Lhe lDF or visual 8asic DevelopmenL . . . . . . . . . . . . . . . . . . . . . . 29
Checking ProjecL and Compiler SeLLings . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
One SLep FurLher. FxiLing visual SLudio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
ChapLer uick Reerence. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
Mcrosoft s nterested n hearng your feedback so we can contnuaIIy mprove our books and Iearnng
resources for you. 1o partcpate n a bref onIne survey, pIease vst:
www.microsoft.com/Iearning/booksurvey/
what do you think of this book? we want to hear from you!
viii 1abIe of Contents
2 Wrtng Your frst Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
Lucky Seven. our FirsL
visual 8asic Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
Programming SLeps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
CreaLing Lhe User lnLerace. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
SeLLing Lhe ProperLies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
1he PicLure 8ox ProperLies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
WriLing Lhe Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
A Look aL Lhe 3uttcn1_Clicl
Procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
Running visual 8asic ApplicaLions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
Sample ProjecLs on Disk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
8uilding an FxecuLable File. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
Deploying our ApplicaLion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
One SLep FurLher. Adding Lo a Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
ChapLer 2 uick Reerence. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
3 Workng wth 1ooIbox ControIs . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
1he 8asic Use o ConLrols. 1he Hello
World Program. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
Using Lhe Dcte1imePicler ConLrol. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
1he 8irLhday Program. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
ConLrols or CaLhering lnpuL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
Using Croup 8oxes and Radio 8uLLons . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Processing lnpuL wiLh LisL 8oxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
A Word AbouL 1erminology. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
One SLep FurLher. Using Lhe linllcbel ConLrol. . . . . . . . . . . . . . . . . . . . . . . . . . . 9
ChapLer 8 uick Reerence. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
4 Workng wth Menus, 1ooIbars, and DaIog oxes . . . . . . . . . . . 97
Adding Menus by Using Lhe MenuStri ConLrol . . . . . . . . . . . . . . . . . . . . . . . . . . 97
Adding Access Keys Lo Menu Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
Processing Menu Choices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 02
Adding 1oolbars wiLh Lhe 1cclStri ConLrol. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 07
Using Dialog 8ox ConLrols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 0
FvenL Procedures 1haL Manage Common
Dialog 8oxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
One SLep FurLher. Assigning ShorLcuL Keys Lo Menus. . . . . . . . . . . . . . . . . . . . 7
ChapLer 4 uick Reerence. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1abIe of Contents ix
Part II Programming lundamentaIs
5 VsuaI asc VarabIes and formuIas,
and the .Nf1 framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . l23
1he AnaLomy o a visual 8asic Program SLaLemenL . . . . . . . . . . . . . . . . . . . . . . 28
Using variables Lo SLore lnormaLion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
SeLLing Aside Space or variables. 1he Dim SLaLemenL . . . . . . . . . . . . . . 24
lmpliciL variable DeclaraLion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
Using variables in a Program. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Using a variable Lo SLore lnpuL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
Using a variable or OuLpuL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
ConsLanLs. variables 1haL Don'L Change . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Working wiLh visual 8asic OperaLors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
8asic MaLh. 1he -, -, *, and / OperaLors . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Using Advanced OperaLors. \, McJ, , and &. . . . . . . . . . . . . . . . . . . . . . 47
Working wiLh MaLh MeLhods in Lhe .NF1 Framework . . . . . . . . . . . . . . . . . . . . 52
One SLep FurLher. FsLablishing Order o Precedence . . . . . . . . . . . . . . . . . . . . 55
Using ParenLheses in a Formula . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
ChapLer 5 uick Reerence. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
6 Usng Decson Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . l59
FvenL-Driven Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
Using CondiLional Fxpressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
lj . . . 1hen Decision SLrucLures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1esLing Several CondiLions in an lj . . . 1hen
Decision SLrucLure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
Using Logical OperaLors in CondiLional Fxpressions . . . . . . . . . . . . . . . . 67
ShorL-CircuiLing by Using AnJAlsc and Orllse . . . . . . . . . . . . . . . . . . . . . 69
Select Ccse Decision SLrucLures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Using Comparison OperaLors wiLh a SelecL
Case SLrucLure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
One SLep FurLher. DeLecLing Mouse FvenLs . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
ChapLer 6 uick Reerence. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
7 Usng Loops and 1mers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . l8l
WriLing lcr . . . Next Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Using a CounLer variable in a MulLiline 1ext3cx ConLrol. . . . . . . . . . . . . . . . . . 88
CreaLing Complex lcr . . . Next Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
Using a CounLer 1haL Has CreaLer Scope . . . . . . . . . . . . . . . . . . . . . . . . . 89
x 1abIe of Contents
WriLing Dc Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
Avoiding an Fndless Loop. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
1he 1imer ConLrol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
CreaLing a DigiLal Clock by Using a 1imer ConLrol . . . . . . . . . . . . . . . . . . . . . . . 97
Using a 1imer ObjecL Lo SeL a 1ime LimiL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
One SLep FurLher. lnserLing Code SnippeLs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
ChapLer 7 uick Reerence. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
8 Debuggng VsuaI asc Programs . . . . . . . . . . . . . . . . . . . . . . . . 209
Finding and CorrecLing Frrors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
1hree 1ypes o Frrors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
ldenLiying Logic Frrors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Debugging 0. Using Debugging Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
1racking variables by Using a WaLch Window . . . . . . . . . . . . . . . . . . . . . . . . . . 27
visualizers. Debugging 1ools 1haL Display DaLa. . . . . . . . . . . . . . . . . . . . . . . . . 220
Using Lhe lmmediaLe and Command Windows . . . . . . . . . . . . . . . . . . . . . . . . . 22
SwiLching Lo Lhe Command Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
One SLep FurLher. Removing 8reakpoinLs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
ChapLer 8 uick Reerence. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
9 1rappng frrors by Usng Structured frror HandIng. . . . . . . . . 227
Processing Frrors by Using Lhe 1ry . . . Cctch SLaLemenL . . . . . . . . . . . . . . . . . . 227
When Lo Use Frror Handlers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
SeLLing Lhe 1rap. 1he 1ry . . . Cctch Code 8lock . . . . . . . . . . . . . . . . . . . . . 229
PaLh and Disc Drive Frrors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
WriLing a Disc Drive Frror Handler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288
Using Lhe linclly Clause Lo Perorm Cleanup 1asks . . . . . . . . . . . . . . . . . . . . . . 284
More Complex 1ry . . . Cctch Frror Handlers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
1he lxceticn ObjecL. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
Speciying a ReLry Period. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
Using NesLed 1ry . . . Cctch 8locks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242
Comparing Frror Handlers wiLh Deensive
Programming 1echniques. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242
One SLep FurLher. 1he lxit 1ry SLaLemenL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248
ChapLer 9 uick Reerence. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244
l0 Creatng ModuIes and Procedures. . . . . . . . . . . . . . . . . . . . . . . . 247
Working wiLh Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247
CreaLing a Module. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248
Working wiLh Public variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
1abIe of Contents xi
CreaLing Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
WriLing FuncLion Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
FuncLion SynLax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
Calling a FuncLion Procedure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
Using a FuncLion Lo Perorm a CalculaLion . . . . . . . . . . . . . . . . . . . . . . . . 258
WriLing Sub Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
Sub Procedure SynLax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
Calling a Sub Procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268
Using a Sub Procedure Lo Manage lnpuL. . . . . . . . . . . . . . . . . . . . . . . . . . 264
One SLep FurLher. Passing ArgumenLs by value
and by Reerence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268
ChapLer 0 uick Reerence. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
ll Usng Arrays to Manage Numerc and Strng Data . . . . . . . . . . 273
Working wiLh Arrays o variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
CreaLing an Array. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274
Declaring a Fixed-Size Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
SeLLing Aside Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
Working wiLh Array FlemenLs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
Declaring an Array and Assigning lL lniLial values . . . . . . . . . . . . . . . . . . 278
CreaLing a Fixed-Size Array Lo Hold 1emperaLures . . . . . . . . . . . . . . . . . 279
CreaLing a Dynamic Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288
Preserving Array ConLenLs by Using ReDim Preserve . . . . . . . . . . . . . . . . . . . . 287
Using ReDim or 1hree-Dimensional Arrays . . . . . . . . . . . . . . . . . . . . . . . 288
One SLep FurLher. Processing Large Arrays
by Using MeLhods in Lhe Arrcy Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288
1he Arrcy Class. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288
ChapLer uick Reerence. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
l2 Workng wth CoIIectons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
Working wiLh ObjecL CollecLions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
Reerencing ObjecLs in a CollecLion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
WriLing lcr lcch . . . Next Loops. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
FxperimenLing wiLh ObjecLs in Lhe Ccntrcls CollecLion. . . . . . . . . . . . . . 299
Using Lhe Ncme ProperLy in a lcr lcch . . . Next Loop . . . . . . . . . . . . . . 802
CreaLing our Own CollecLions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 804
Declaring New CollecLions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 804
One SLep FurLher. v8A CollecLions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 809
FnLering Lhe Word Macro. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
ChapLer 2 uick Reerence. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
xii 1abIe of Contents
l3 fxpIorng 1ext fIes and Strng Processng . . . . . . . . . . . . . . . . . 3l3
Reading 1exL Files. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
1he My Namespace. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
1he StrecmRecJer Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
Using Lhe RecJAll1ext MeLhod . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
WriLing 1exL Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
1he WriteAll1ext MeLhod . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
1he StrecmWriter Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 822
Using Lhe WriteAll1ext MeLhod. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 828
Processing SLrings wiLh Lhe Strin Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 826
SorLing 1exL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 829
Working wiLh ASCll Codes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 880
SorLing SLrings in a 1exL 8ox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
Fxamining Lhe SorL 1exL Program Code. . . . . . . . . . . . . . . . . . . . . . . . . . . 884
ProLecLing 1exL wiLh 8asic FncrypLion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 886
One SLep FurLher. Using Lhe Xcr OperaLor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 840
Fxamining Lhe FncrypLion Program Code . . . . . . . . . . . . . . . . . . . . . . . . . 842
ChapLer 8 uick Reerence. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 845
Part III Designing the User lnterface
l4 Managng Wndows forms and ControIs at Run 1me . . . . . . . 35l
Adding New Forms Lo a Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
How Forms Are Used. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 852
Working wiLh MulLiple Forms. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 852
Using Lhe DiclcResult ProperLy in Lhe Calling Form . . . . . . . . . . . . . . . 858
PosiLioning Forms on Lhe Windows DeskLop . . . . . . . . . . . . . . . . . . . . . . . . . . . 859
Minimizing, Maximizing, and ResLoring Windows. . . . . . . . . . . . . . . . . . 864
Adding ConLrols Lo a Form aL Run 1ime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 864
Organizing ConLrols on a Form. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 867
One SLep FurLher. Speciying Lhe SLarLup ObjecL . . . . . . . . . . . . . . . . . . . . . . . . 87
ChapLer 4 uick Reerence. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 878
l5 Addng Graphcs and Anmaton fffects . . . . . . . . . . . . . . . . . . . 375
Adding ArLwork by Using
Lhe System.Drcwin Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 876
Using a Form's CoordinaLe SysLem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 876
1he System.Drcwin.Crchics Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 876
Using Lhe Form's PainL FvenL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 878
1abIe of Contents xiii
Adding AnimaLion Lo our Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 880
Moving ObjecLs on Lhe Form. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 880
1he lcccticn ProperLy. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
CreaLing AnimaLion by Using a 1imer ObjecL . . . . . . . . . . . . . . . . . . . . . . 882
Fxpanding and Shrinking ObjecLs While a Program ls Running . . . . . . . . . . . 886
One SLep FurLher. Changing Form 1ransparency . . . . . . . . . . . . . . . . . . . . . . . . 888
ChapLer 5 uick Reerence. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 890
l6 Inhertng forms and Creatng ase CIasses . . . . . . . . . . . . . . . . 393
lnheriLing a Form by Using Lhe lnheriLance Picker . . . . . . . . . . . . . . . . . . . . . . . 898
CreaLing our Own 8ase Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 899
Adding a New Class Lo our ProjecL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
One SLep FurLher. lnheriLing a 8ase Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408
ChapLer 6 uick Reerence. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
l7 Workng wth Prnters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4l5
Using Lhe PrintDccument Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
PrinLing 1exL rom a 1exL 8ox ObjecL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420
PrinLing MulLipage 1exL Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424
One SLep FurLher. Adding PrinL Preview and Page SeLup Dialog 8oxes. . . . . 480
ChapLer 7 uick Reerence. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
Part IV Database and web Programming
l8 Gettng Started wth ADO.Nf1 . . . . . . . . . . . . . . . . . . . . . . . . . . . 44l
DaLabase Programming wiLh ADO.NF1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
DaLabase 1erminology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442
Working wiLh an Access DaLabase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444
1he DaLa Sources Window. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452
Using 8ound ConLrols Lo Display
DaLabase lnormaLion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 458
One SLep FurLher. SL SLaLemenLs, LlN,
and FilLering DaLa. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
ChapLer 8 uick Reerence. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466
l9 Data Presentaton Usng the DctcCridView ControI . . . . . . . . . 467
Using DctcCriJview Lo Display DaLabase Records. . . . . . . . . . . . . . . . . . . . . . . 467
FormaLLing DctcCriJview Cells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 479
Adding a Second DaLa Crid view ObjecL. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 482
One SLep FurLher. UpdaLing Lhe Original DaLabase. . . . . . . . . . . . . . . . . . . . . . 485
ChapLer 9 uick Reerence. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488
xiv 1abIe of Contents
20 Creatng Web Stes and Web Pages by Usng VsuaI
Web DeveIoper and ASP.Nf1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49l
lnside ASP.NF1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
Web Pages vs. Windows Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 498
Server ConLrols. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 498
H1ML ConLrols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494
8uilding a Web SiLe by Using visual
Web Developer. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495
Considering SoLware RequiremenLs
or ASP.NF1 Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495
Using Lhe Web Page Designer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 498
Adding Server ConLrols Lo a Web SiLe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
WriLing FvenL Procedures or Web Page ConLrols . . . . . . . . . . . . . . . . . . 504
CusLomizing Lhe Web SiLe 1emplaLe. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 509
Displaying DaLabase Records on a Web Page. . . . . . . . . . . . . . . . . . . . . . . . . . . 52
One SLep FurLher. SeLLing Web SiLe 1iLles
in lnLerneL Fxplorer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
ChapLer 20 uick Reerence. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 522
Appendx: Where to Go for More Informaton . . . . . . . . . . . . . . . . . . . . . . . . . 523
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 529
Mcrosoft s nterested n hearng your feedback so we can contnuaIIy mprove our books and Iearnng
resources for you. 1o partcpate n a bref onIne survey, pIease vst:
www.microsoft.com/Iearning/booksurvey/
what do you think of this book? we want to hear from you!
xv
AcknowIedgments
WriLing a compuLer programming book is ascinaLing because Lhe whole process begins well
. AuLhors meeL wiLh soLware developers and compuLer
soLware, review
Lhe commenLs and suggesLions LhaL readers o previous ediLions have oered, develop
a wriLing plan and schedule, and begin LesLing Lheir ideas wiLh beLa versions o Lhe producL.
1his iLeraLive process produces imporLanL insighLs and conLinues (wiLh mounLing ervor) unLil
.
MicrosoL Press is a anLasLic place Lo wriLe a compuLer programming book. AL each sLage in
Lhe publishing process, LalenLed Leam members work LogeLher Lo culLivaLe valuable Lechnical
conLacLs and resources, build visionary producL deploymenL sLraLegies, explore Lhe hidden
.
Micrcscjt visucl 3csic 2919 Ste by Ste
rom Lhis dynamic and innovaLive publishing environmenL over Lhe years.
l graLeully acknowledge Lhe supporL and assisLance o Lhe ollowing people who helped
Lo plan, ediL, LesL, produce, and markeL our book Lhis Lime (in Lhe order LhaL l worked wiLh
Lhem). 8en Ryan, Devon Musgrave, valerie Woolley, Susan McClung, and ChrisLian Holdener.
ln parLicular, valerie Woolley enLhusiasLically kepL my wriLing on schedule and insured LhaL
Ste by Ste series LhaL MicrosoL Press is so well known or. l
am also very graLeul Lo Lhe MicrosoL visual SLudio 200 developmenL Leam or providing me
wiLh beLa and release candidaLe soLware Lo work wiLh.
As always, l oer my deepesL graLiLude and aecLion Lo my amily or Lheir conLinued
supporL o my wriLing projecLs and various academic pursuiLs.
xvii
Introducton
MicrosoL visual 8asic 200 is an imporLanL upgrade and enhancemenL o Lhe popular visual
8asic programming language and compiler, a Lechnology LhaL enjoys an insLalled base o
millions o programmers worldwide. visual 8asic 200 is noL a sLand-alone producL buL
a key componenL o MicrosoL visual SLudio 200-a comprehensive developmenL sysLem
LhaL allows you Lo creaLe powerul applicaLions or Windows, Lhe Web, handheld devices,
and a hosL o oLher environmenLs. WheLher you purchase one o Lhe commercial ediLions o
visual SLudio 200 (described laLer in Lhis lnLroducLion) or you download visual 8asic 200
Fxpress or a ree LesL-drive o Lhe soLware, you are in or an exciLing experience. 1he laLesL
eaLures o visual 8asic will increase your producLiviLy and programming prowess, especially
i you enjoy using and inLegraLing inormaLion rom daLabases, enLerLainmenL media, Web
pages, and Web siLes.
SLudio lnLegraLed DevelopmenL FnvironmenL (lDF) is LhaL you can use many o Lhe same
Lools Lo wriLe programs or MicrosoL visual C-- 200, MicrosoL visual C# 200, MicrosoL
visual Web Developer 200, and oLher popular producLs.
Micrcscjt visucl 3csic 2919 Ste by Ste is a comprehensive inLroducLion Lo visual 8asic
programming using Lhe visual 8asic 200 soLware. l've designed Lhis pracLical, hands-on
LuLorial wiLh a varieLy o skill levels in mind and by ollowing Lhe premise LhaL programmers
learn by doing. ln my opinion, Lhe besL way Lo masLer a complex Lechnology like visual 8asic
is Lo learn essenLial programming Lechniques Lhrough careully prepared LuLorials LhaL can
be compleLed on your own schedule and aL your own pace.
experience wiLh college Leaching and corporaLe projecL managemenL, Lhis book is noL
a dry LexLbook or an "A Lo Z" programmer's reerence. lnsLead, iL is a pracLical hands-on
programming LuLorial LhaL puLs ycu in charge o your learning, developmenLal milesLones,
and achievemenLs. 8y using Lhis book, programmers who are new Lo Lhis Lopic will learn
visual 8asic soLware developmenL undamenLals in Lhe conLexL o useul, real-world
applicaLions, and experienced visual 8asic programmers can quickly masLer Lhe essenLial
Lools and Lechniques oered in Lhe visual 8asic 200 upgrade.
ComplemenLing Lhis comprehensive approach is Lhe book's sLrucLure-4 Lopically organized
parLs, 20 chapLers, and 56 sLep-by-sLep exercises and sample programs. 8y using Lhis book,
you'll quickly learn how Lo creaLe proessional-qualiLy visual 8asic 200 applicaLions or Lhe
Windows operaLing sysLem and a varieLy o Web browsers. ou'll also have un!
xviii Introducton
VisuaI Basic Versions
So how did we geL here, anyway 8eLween 99 and 998, MicrosoL released six versions
o visual 8asic (versions .0 Lhrough 6.0), which revoluLionized soLware developmenL or
Windows by inLroducing evenL-driven programming Lo a wide audience based on Lhe
uick8asic programming language and an lDF.
developmenL and innovaLion, MicrosoL released visual 8asic .NF1 2002, an objecL-orienLed
programming language closely relaLed Lo visual 8asic buL implemenLed on Lhe MicrosoL
.NF1 Framework, a comprehensive library o coded soluLions inLended Lo be used by mosL
new applicaLions LhaL run on Lhe Windows plaLorm. As improved versions o visual 8asic
came ouL in 2008, 2005, and 2008, visual 8asic became a componenL wiLhin Lhe visual
and Leam developmenL projecLs, as well as conLinued improvemenLs Lo Lhe .NF1 Framework.
visual 8asic 200 is now so LighLly inLegraLed wiLh visual SLudio LhaL iL is available only
as a componenL in Lhe visual SLudio 200 programming suiLe, which includes visual C#,
visual C--, visual Web Developer, and oLher MicrosoL .NF1 developmenL Lools. Since
2005, boLh visual 8asic and visual SLudio have been markeLed wiLhouL Lhe ".NF1" moniker,
alLhough Lhey are sLill based on Lhe .NF1 Framework Lechnology.
Proessional, Premium, UlLimaLe, and Fxpress. l've wriLLen Lhis book Lo be compaLible
wiLh all ediLions o visual 8asic 200 and visual SLudio 200, buL especially wiLh Lhe Lools
and Lechniques available in visual SLudio 200 Proessional and visual 8asic 200 Fxpress.
AlLhough visual 8asic 200 is similar in many ways Lo visual 8asic 2008, Lhere are many
imporLanL dierences and improvemenLs, so l recommend LhaL you compleLe Lhe exercises
in Lhis book using Lhe visual 8asic 200 soLware.
Note 1he visual SLudio 200 soLware is noL included wiLh Lhis book. 1he CD disLribuLed wiLh
LhaL requires Lhe visual SLudio 200 soLware (sold separaLely) or use. l you don'L have visual
SLudio, you can download visual 8asic 200 Fxpress or ree, and iL conLains an amazing paleLLe
o eaLures, Lhough obviously noL all Lhe eaLures o visual SLudio Proessional, Premium, or
UlLimaLe. As you compleLe Lhe exercises in Lhis book, l will noLe rom Lime Lo Lime which eaLures
are unavailable Lo you i you are using visual 8asic 200 Fxpress. Also noLe LhaL i you are using
visual 8asic 200 Fxpress and you wanL Lo compleLe ChapLer 20, "CreaLing Web SiLes and Web
Pages by Using visual Web Developer and ASP.NF1," you will need Lo download visual Web
Developer 200 Fxpress Lo compleLe Lhe exercises. visual Web Developer is included in visual
SLudio Proessional, Premium, and UlLimaLe, buL noL visual 8asic Fxpress.
Introducton xxi
PrereIease Software
1his book was reviewed and LesLed againsL Lhe Release CandidaLe o visual
SLudio 200.
visual SLudio 200.
visual SLudio 200 and visual 8asic 200. l Lhere are any changes or correcLions or Lhis
book, Lhey will be collecLed and added Lo an easy-Lo-access MicrosoL Knowledge 8ase
arLicle on Lhe Web. See "SupporL or 1his 8ook," laLer in Lhis lnLroducLion.
DigitaI Content for DigitaI Book keaders. l you boughL a digiLal-only ediLion o Lhis book, you can
enjoy selecL conLenL rom Lhe prinL ediLion's companion CD.
visiL Lo geL your downloadable conLenL. 1his conLenL
is always up-Lo-daLe and available Lo all readers.
lnstaIIing and Using the Practice liIes
in Lhe book. For example, when you're learning how Lo display daLabase Lables on a orm
by using Lhe DctcCriJview
daLabase named FaculLy200.accdb-and Lhen use visual SLudio daLabase programming
Lools Lo access Lhe daLabase.
LhaL aren'L relevanL Lo Lhe exercise. lnsLead, you can concenLraLe on learning how Lo masLer
visual 8asic 200 programming Lechniques.
in Lhe chapLers, you'll also learn by doing, which is an easy and eecLive way Lo acquire and
remember new skills.
Important 8eore you break Lhe seal on Lhe CD, be sure LhaL Lhis book maLches your version
o Lhe soLware. 1his book is designed or use wiLh visual SLudio 200 and Lhe visual 8asic 200
programming language.
package, or you can sLarL Lhe soLware, open a projecL, and Lhen click AbouL MicrosoL visual
SLudio on Lhe Help menu aL Lhe Lop o Lhe screen.
InstaIIng the Practce fIes
disk space.
so LhaL you can use Lhem wiLh Lhe exercises in Lhis book.
l. Remove Lhe CD rom Lhe package inside Lhis book and inserL iL inLo your CD drive.
Note An Fnd-User License AgreemenL (FULA) should open auLomaLically. l Lhis
agreemenL does noL appear, you can double-click SLarLCD.exe on Lhe CD. l you have
Windows 7 or Windows visLa, click CompuLer on Lhe SLarL menu, double-click Lhe icon or
your CD drive, and Lhen double-click SLarLCD.exe.
xxii Introducton
2. Review Lhe FULA. l you accepL Lhe Lerms, selecL Lhe AccepL opLion, and Lhen click NexL.
A menu appears wiLh opLions relaLed Lo Lhe book.
3. Click lnsLall PracLice Files.
4. Follow Lhe on-screen insLrucLions.
Note
insLallaLion locaLion, which by deaulL is C.\vb0sbs. l you change Lhe insLallaLion locaLion,
. 1rusL me-iL is good
Lo use Lhe deaulL insLallaLion locaLion.
5.
package inside Lhe back cover o your book.
l you accepLed Lhe deaulL seLLings, a older named C.\vb0sbs has been creaLed on
.
one older in C.\vb0sbs or each chapLer in Lhe book.
compleLed projecLs, and oLhers will require LhaL you enLer some program code.)
l
.
Usng the Practce fIes
.
.
1he chapLers are builL around scenarios LhaL simulaLe real programming projecLs so LhaL you
can easily apply Lhe skills you learn Lo your own work.
Note . Accordingly, you
8asic or visual SLudio soLware. 1o see whaL version o visual 8asic or visual SLudio you're using,
click Lhe AbouL command on Lhe Help menu.
and soluLions in dierenL ways. 1he insLrucLions in Lhis book generally rely on Lhe deaulL
seLLing or visual SLudio. For more inormaLion abouL how seLLings wiLhin Lhe developmenL
"CusLomizing lDF SeLLings Lo MaLch SLep-by-SLep Fxercises" in ChapLer , "Fxploring Lhe
visual SLudio lnLegraLed DevelopmenL FnvironmenL."
Introducton xxvii
Conventons
1he names o all program elemenLs-conLrols, objecLs, meLhods, uncLions, properLies,
and so on-appear in itclic.
Hands-on exercises or you Lo ollow are given in numbered lisLs o sLeps (, 2,
1exL LhaL you need Lo Lype appears in boId.
As you work Lhrough sLeps, you'll occasionally see Lables wiLh lisLs o properLies LhaL
you'll seL in visual SLudio. 1exL properLies appear wiLhin quoLes, buL you don'L need Lo
Lype Lhe quoLes.
A plus sign (-) beLween Lwo key names means LhaL you musL press Lhose keys aL Lhe
same Lime. For example, "Press AlL-1ab" means LhaL you hold down Lhe AlL key while
you press 1ab.
Readeraids labeled NoLe, 1ip, and lmporLanL provide addiLional inormaLion or alLernaLive
meLhods or a sLep. ou should read Lhese beore conLinuing wiLh Lhe exercise.
Other features
ou can learn special programming Lechniques, background inormaLion, or eaLures
relaLed Lo Lhe inormaLion being discussed by reading Lhe sidebars LhaL appear
LhroughouL Lhe chapLers.
suggesL uLure areas or exploraLion.
ou can learn abouL opLions or Lechniques LhaL build on whaL you learned in a chapLer
by Lrying Lhe One SLep FurLher exercise aL Lhe end o LhaL chapLer.
ou can geL a quick reminder o how Lo perorm Lhe Lasks you learned by reading Lhe
uick Reerence Lable aL Lhe end o a chapLer. 1hese handy Lables are also designed
Lo be used as a Lopical reerence aLer you compleLe Lhe book and you need a quick
reminder abouL how Lo perorm a programming Lask.
HeIpfuI Support Links
ou are inviLed Lo check ouL Lhe ollowing links LhaL provide supporL or Lhe visual SLudio
200 soLware and Lhis book's conLenLs.
xxviii Introducton
VsuaI Studo 20l0 Software Support
For quesLions abouL Lhe visual SLudio 200 soLware, l recommend Lwo MicrosoL Web siLes.
htt.//msJn.micrcscjt.ccm/vbcsic/ (Lhe MicrosoL visual 8asic Developer CenLer
home page)
htt.//www.micrcscjt.ccm/ccmmunities/ (Lhe home o Lechnical communiLies relaLed Lo
MicrosoL soLware producLs and Lechnologies)
8oLh Web siLes give you access Lo proessional visual 8asic developers, MicrosoL employees,
visual 8asic blogs, newsgroups, webcasLs, Lechnical chaLs, and inLeresLing user groups.
For addiLional inormaLion abouL Lhese and oLher elecLronic and prinLed resources, see Lhe
Appendix, "Where Lo Co or More lnormaLion."
Support for This Book
Fvery eorL has been made Lo ensure Lhe accuracy o Lhis book and Lhe conLenLs o Lhe
companion CD. As correcLions or changes are collecLed, Lhey will be added Lo a MicrosoL
Knowledge 8ase arLicle. MicrosoL Press provides supporL or books and companion CDs
aL Lhe ollowing Web siLe.
htt.//www.micrcscjt.ccm/lecrnin/sucrt/bccls/
l you have commenLs, quesLions, or ideas regarding Lhe book or Lhe companion CD,
or quesLions LhaL are noL answered by visiLing Lhe siLes previously menLioned, please send
Lhem Lo MicrosoL Press via an e-mail message Lo msinut@micrcscjt.ccm.
Please noLe LhaL MicrosoL soLware producL supporL is noL oered Lhrough Lhese addresses,
nor does Lhe auLhor o Lhis book oer direcL producL supporL.
We Want to Hear from You
We welcome your eedback abouL Lhis book. Please share your commenLs and ideas Lhrough
Lhe ollowing shorL survey.
htt.//www.micrcscjt.ccm/lecrnin/bcclsurvey
our parLicipaLion helps MicrosoL Press creaLe books LhaL beLLer meeL your needs and your
sLandards.
Note We hope LhaL you will give us deLailed eedback in our survey. l you have quesLions abouL
our publishing program, upcoming LiLles, or MicrosoL Press in general, we encourage you Lo
inLeracL wiLh us using 1wiLLer aL htt.//twitter.ccm/MicrcscjtPress. For supporL issues, use only Lhe
e-mail address shown previously.
l
ParL l
Gettng Started wth Mcrosoft
VsuaI asc 20l0
In ths part:
Chapter l: fxpIorng the VsuaI Studo Integrated
DeveIopment fnvronment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Chapter 2: Wrtng Your frst Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
Chapter 3: Workng wth 1ooIbox ControIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
Chapter 4: Workng wth Menus, 1ooIbars, and DaIog oxes. . . . . . . . . . . . . . . . 97
ln ParL l, you'll receive an overview o essenLial MicrosoL visual 8asic 200 programming
Lechniques and an inLroducLion Lo Lhe Lools and eaLures LhaL you will work wiLh during mosL
visual 8asic programming sessions. ou'll learn Lo use Lhe visual SLudio 200 lnLegraLed
DevelopmenL FnvironmenL (lDF), wiLh iLs ulsome collecLion o programming Lools, windows,
and menu commands, and you'll receive sLep-by-sLep insLrucLion on how Lo build and run
several inLeresLing programs rom scraLch. 1his is Lhe place Lo sLarL i you're new Lo visual
8asic programming or upgrading rom an earlier version.
ChapLer 2 inLroduces how conLrols, orms, properLies, and program code can be used in
combinaLion Lo creaLe an enLerLaining Lucky Seven sloL machine game. ChapLer 8 provides
an overview o Lhe mosL useul 1oolbox conLrols, which help you presenL inormaLion
or program choices Lo Lhe user, gaLher inpuL, work wiLh daLes and Limes, and connecL
Lo Lhe Web. ChapLer 4 ocuses on adding menus, Loolbars, and dialog boxes Lo visual 8asic
.
3
ChapLer
fxpIorng the VsuaI Studo
Integrated DeveIopment
fnvronment
After compIetng ths chapter, you wII be abIe to:
Use Lhe visual SLudio lnLegraLed DevelopmenL FnvironmenL.
Open and run a visual 8asic program.
Change properLy seLLings.
Move, resize, dock, and auLomaLically hide Lool windows.
Use Lhe lDF NavigaLor.
Open a Web browser wiLhin visual SLudio.
CeL Help and manage Help seLLings.
CusLomize lDF seLLings Lo maLch Lhis book's sLep-by-sLep insLrucLions.
Are you ready Lo sLarL working wiLh MicrosoL visual SLudio 200 1his chapLer gives
you Lhe skills you need Lo geL up and running wiLh Lhe visual SLudio 200 lnLegraLed
DevelopmenL FnvironmenL (lDF)-Lhe place where you will wriLe MicrosoL visual 8asic
programs. ou should read Lhis chapLer wheLher you are new Lo visual 8asic programming
or you have used previous versions o visual 8asic or visual SLudio.
ln Lhis chapLer, you'll learn Lhe essenLial visual SLudio menu commands and programming
procedures. ou'll open and run a simple visual 8asic program named Music 1rivia,
you'll change a programming seLLing called a rcerty, and you'll pracLice moving, sizing,
docking, and hiding Lool windows.
wiLh Lhe lDF NavigaLor, open a Web browser wiLhin visual SLudio, geL more inormaLion
by using Lhe online Help documenLaLion, and cusLomize Lhe lDF Lo maLch Lhis book's
sLep-by-sLep insLrucLions. 1hese are common Lasks LhaL you'll use in mosL visual SLudio
programming sessions, and Lhey will soon become second naLure Lo you (i Lhey are
noL already).
6 Part I Gettng Started wth Mcrosoft VsuaI asc 20l0
1p ln Lhe Open ProjecL dialog box, you see a number o sLorage locaLions along Lhe leL side
o Lhe window. 1he ProjecLs older under MicrosoL visual SLudio 200 is parLicularly useul.
8y deaulL, visual SLudio saves your programming projecLs in Lhis ProjecLs older, giving each
projecL iLs own subolder. We'll use a dierenL projecLs older Lo organize your programming
coursework, however, as you'll learn below. AddiLional locaLions, such as FavoriLes and Libraries,
will also be available Lo you, depending on how your compuLer and operaLing sysLem has been
. (1he screen shoLs in Lhis book show Windows 7.)
2. 8rowse Lo Lhe C.\vb0sbs older on your hard disk.
enLiLled "lnsLalling and Using Lhe PracLice Files" in Lhe lnLroducLion. l you didn'L insLall
wiLh Lhis book.
3. .
.sln.)
visual SLudio loads Lhe Music1rivia orm, properLies, and program code or Lhe
Music1rivia soluLion. 1he SLarL Page may sLill be visible in Lhe cenLer o Lhe screen.
ln Lhe
in Lhe soluLion.
Chapter l fxpIorng the VsuaI Studo Integrated DeveIopment fnvronment 7
1roubIeshootng l you see an error message indicaLing LhaL Lhe projecL you wanL Lo
an older version o Lhe visual 8asic soLware. (Farlier versions o visual 8asic can'L open
Lhe visual 8asic 200 projecLs included on Lhe companion CD.) 1o check which version
o visual 8asic you're using, click Lhe AbouL command on Lhe Help menu.
visual SLudio provides a special check box named Always Show SoluLion Lo conLrol several
opLions relaLed Lo soluLions wiLhin Lhe lDF. 1he check box is locaLed on Lhe ProjecLs
and SoluLions/Ceneral Lab o Lhe OpLions dialog box, which you open by clicking Lhe OpLions
command on Lhe 1ools menu. l Lhe check box is selecLed, a subolder is creaLed or each new
. Also, i
you selecL Lhe Always Show SoluLion check box, a ew opLions relaLed Lo soluLions appear in
Lhe lDF, such as commands on Lhe File menu and a soluLion enLry in SoluLion Fxplorer. l you
like Lhe idea o creaLing separaLe olders or soluLions and seeing soluLion-relaLed commands
and seLLings, selecL Lhis check box. ou'll learn more abouL Lhese opLions aL Lhe end o Lhe
chapLer.
Projects and SoIutions
ln visual SLudio, programs under developmenL are Lypically called rcjects or scluticns
. visual 8asic 200
. .sln), and i you examine
. (visual
8asic 200 is reerred Lo as v8 0 inLernally.)
.
conLains inormaLion abouL one or more projecLs.
mulLiple relaLed projecLs. 1he samples included wiLh Lhis book Lypically have a single
.vbproj) has Lhe same eecL as
.sln). 8uL or a mulLi-projecL soluLion, you will wanL Lo open
.
buL Lhe basic Lerminology LhaL you mighL have learned while using visual 8asic 2005
or 2008 sLill applies.
The VisuaI Studio TooIs
AL Lhis poinL, you should Lake a ew momenLs Lo sLudy Lhe visual SLudio lDF and idenLiy
some o Lhe programming Lools and windows LhaL you'll be using as you compleLe Lhis
course. l you've wriLLen visual 8asic programs beore, you'll recognize many (buL perhaps
8 Part I Gettng Started wth Mcrosoft VsuaI asc 20l0
noL all) o Lhe programming Lools. CollecLively, Lhese eaLures are Lhe componenLs LhaL you
use Lo consLrucL, organize, and LesL your visual 8asic programs. A ew o Lhe programming
Lools also help you learn more abouL Lhe resources on your sysLem, including Lhe larger
world o daLabases and Web siLe connecLions available Lo you. 1here are also several
powerul Help Lools.
1he menu bcr provides access Lo mosL o Lhe commands LhaL conLrol Lhe developmenL
environmenL. Menus and commands work as Lhey do in all Windows-based programs, and
you can access Lhem by using Lhe keyboard or Lhe mouse. LocaLed below Lhe menu bar is
Lhe StcnJcrJ tcclbcr, a collecLion o buLLons LhaL serve as shorLcuLs or execuLing commands
and conLrolling Lhe visual SLudio lDF. My assumpLion is LhaL you've used Word, Fxcel, or some
oLher Windows-based applicaLion enough Lo know quiLe a biL abouL Loolbars, and how Lo
use amiliar Loolbar commands, such as Open, Save, CuL, and PasLe. 8uL you'll probably be
impressed wiLh Lhe number and range o Loolbars provided by visual SLudio or programming
Lasks. ln Lhis book, you'll learn Lo use several Loolbars, you can see Lhe ull lisL o Loolbars aL any
Lime by righL-clicking any Loolbar in Lhe lDF.
Along Lhe boLLom o Lhe screen, you may see Lhe Windows tcslbcr. ou can use Lhe Laskbar
Lo swiLch beLween various visual SLudio componenLs and Lo acLivaLe oLher Windows-based
programs. ou mighL also see Laskbar icons or Windows lnLerneL Fxplorer, anLivirus uLiliLies,
and oLher programs insLalled on your sysLem. ln mosL o my screen shoLs, l'll hide Lhe Laskbar,
Lo show more o Lhe lDF.
1he ollowing screen shoL shows some o Lhe Lools and windows in Lhe visual SLudio lDF.
Don'L worry LhaL Lhis screen looks dierenL rom your currenL developmenL environmenL
view. ou'll learn more abouL Lhese elemenLs (and how you adjusL your views) as you work
Lhrough Lhe chapLer.
1he main Lools visible in Lhis visual SLudio lDF are Lhe Designer, SoluLion Fxplorer, Lhe
ProperLies window, and Lhe 1oolbox, as shown here. ou mighL also see more specialized
Lools, such as Server Fxplorer and ObjecL 8rowser, or Lhey may appear as Labs wiLhin Lhe
lDF.
you'll see i your visual SLudio soLware has already been used. (WhaL l show is essenLially
Lhe "resh download" or "ouL-o-Lhe-box" view.)
l a Lool isn'L visible and you wanL Lo see iL, click Lhe view menu and selecL Lhe Lool. 8ecause
Lhe view menu has expanded sLeadily over Lhe years, MicrosoL has moved some o Lhe less
requenLly used view Lools Lo a submenu called OLher Windows. Check Lhere i you don'L see
whaL you need.
1he exacL size and shape o Lhe Lools and windows depend on how your developmenL
. WiLh visual SLudio, you can align and aLLach, or Jccl,
windows Lo make visible only Lhe elemenLs LhaL you wanL Lo see. ou can also parLially
conceal Lools as tcbbeJ Jccuments along Lhe edge o Lhe developmenL environmenL
Chapter l fxpIorng the VsuaI Studo Integrated DeveIopment fnvronment 9
and Lhen swiLch back and orLh beLween documenLs quickly. 1rying Lo sorL ouL which Lools
when you're learning Lhe busy visual SLudio inLerace. our developmenL environmenL will
probably look besL i you seL your moniLor and Windows deskLop seLLings so LhaL Lhey
maximize your screen space, buL even Lhen Lhings can geL a liLLle crowded.
1p AlLhough l use a screen resoluLion o 800 600 or mosL o Lhe screen shoLs in Lhis
book-so LhaL you can see Lhe lDF clearly-l usually use 280 x 024 or wriLing code. ou can
change Lhe screen resoluLion in Windows 7 by righL-clicking Lhe Windows deskLop and clicking
Screen ResoluLion. ln Windows visLa, you righL-click Lhe Windows deskLop and click Personalize.
1he purpose o all Lhis Lool complexiLy is Lo add many new and useul eaLures Lo Lhe lDF while
providing clever mechanisms or managing Lhe cluLLer. 1hese mechanisms include eaLures
describe laLer
in Lhis chapLer. l you're jusL sLarLing ouL wiLh visual SLudio, Lhe besL way Lo deal wiLh Lhis eaLure
Lension is Lo hide Lhe Lools LhaL you don'L plan Lo use oLen Lo make room or Lhe imporLanL
ones. 1he crucial Lools or beginning visual 8asic programming-Lhe ones you'll sLarL using righL
away in Lhis book-are Lhe Designer, Lhe ProperLies window, SoluLion Fxplorer, and Lhe 1oolbox.
ou won'L use Lhe Server Fxplorer, Class view, ObjecL 8rowser, or Debug windows unLil laLer in
Lhe book.
l2 Part I Gettng Started wth Mcrosoft VsuaI asc 20l0
visual SLudio loads and compiles Lhe projecL inLo an cssembly (a sLrucLured collecLion
o modules, daLa, and maniesL inormaLion or a program), prepares Lhe program or
LesLing or Jebuin, and Lhen (i Lhe compilaLion is successul) runs Lhe program in
Lhe developmenL environmenL. While Lhe program is running, an icon or Lhe program
appears on Lhe Windows Laskbar. ALer a momenL, you see Lhe Music1rivia orm again,
Lhis Lime wiLh Lhe phoLograph and answer label hidden rom view, as shown here.
Music 1rivia now asks iLs imporLanL quesLion. "WhaL rock and roll insLrumenL is oLen
played wiLh sharp, slapping Lhumb movemenLs"
2. Click Lhe Answer buLLon Lo reveal Lhe soluLion Lo Lhe quesLion.
1he program displays Lhe answer (1he 8ass CuiLar) below Lhe quesLion and Lhen
displays a phoLograph o an obscure SeaLLle bass player demonsLraLing Lhe Lechnique,
as shown here. 1he LesL program works.
Chapter l fxpIorng the VsuaI Studo Integrated DeveIopment fnvronment l3
3. Click uiL Lo close Lhe program.
1he orm closes, and Lhe visual SLudio lDF becomes acLive again.
Thinking About Properties
ln visual 8asic, each user inLerace (Ul) elemenL in a program (including Lhe orm iLsel)
. ou can seL properLies aL design Lime by using Lhe
ProperLies window. ProperLies can also be reerenced in code Lo do meaningul work
while Lhe program runs. (Ul elemenLs LhaL receive inpuL oLen use properLies Lo convey
inormaLion Lo Lhe program.
grasp. viewing Lhem in Lerms o someLhing rom everyday lie can help.
Consider Lhis bicycle analogy. a bicycle is an objecL you use Lo ride rom one place Lo
anoLher. 8ecause a bicycle is a physical objecL, iL has several inherenL characLerisLics. lL has
a brand name, a color, gears, brakes, and wheels, and iL's builL in a parLicular sLyle. (lL mighL
be a road bike, a mounLain bike, or a Landem bike.) ln visual 8asic Lerminology, Lhese
characLerisLics are rcerties o Lhe bicycle cbject. MosL o Lhe bicycle's properLies were
. 8uL oLhers (Lires, Lravel speed, and opLions such as
. 1he bike mighL
even have inLangible (LhaL is, invisible) properLies, such as manuacLure daLe, currenL owner,
value, or renLal sLaLus. And Lo add a liLLle more complexiLy, a company or shop mighL
own one bicycle or (Lhe more likely scenario) an
properLies. As you work wiLh visual 8asic, you'll seL Lhe properLies o a varieLy o objecLs,
and you'll organize Lhem in very useul ways.
The Properties window
ln Lhe lDF, you can use Lhe ProperLies window Lo change Lhe characLerisLics, or rcerty
settins, o Lhe Ul elemenLs on a orm. A properLy seLLing is a quclity o one o Lhe objecLs in
your program. ou can change properLy seLLings rom Lhe ProperLies window while you're
creaLing your user inLerace, or you can add program code via Lhe Code FdiLor Lo change one
or more properLy seLLings while your program is running. For example, Lhe Lrivia quesLion
onL size or wiLh a dierenL alignmenL. (WiLh visual SLudio, you can display LexL in any onL
insLalled on your sysLem, jusL as you can in Fxcel or Word.)
1he ProperLies window conLains an ObjecL lisL LhaL iLemizes all Lhe Ul elemenLs (objecLs) on
Lhe orm. 1he window also lisLs Lhe properLy seLLings LhaL can be changed or each objecL.
ou can click one o Lwo convenienL buLLons Lo view properLies alphabeLically or by caLegory.
.
Chapter l fxpIorng the VsuaI Studo Integrated DeveIopment fnvronment l5
1p 1he ProperLies window has Lwo handy buLLons aL Lhe Lop o Lhe window LhaL you can
use Lo urLher organize properLies. Clicking Lhe AlphabeLical buLLon lisLs all Lhe properLies
in alphabeLical order and puLs Lhem in jusL a ew caLegories. Clicking Lhe CaLegorized
buLLon organizes Lhe properLy lisL inLo many logical caLegories. l recommend CaLegorized
view i you are new Lo visual SLudio.
3. Scroll Lhe ProperLies window lisL box unLil Lhe lcnt properLy is visible.
1he ProperLies window scrolls like a regular lisL box. l you are in CaLegorized view, FonL
is in Lhe Appearance caLegory.
4. Click Lhe lcnt properLy name (in Lhe leL column).
1he currenL onL (MicrosoL Sans Seri) is parLially displayed in Lhe righL column, and
a buLLon wiLh Lhree doLs on iL appears by Lhe onL name. 1his buLLon is called an ellisis
buttcn and indicaLes LhaL a dialog box is available Lo cusLomize Lhe properLy seLLing.
5. Click Lhe FonL ellipsis buLLon in Lhe ProperLies window.
visual SLudio displays Lhe FonL dialog box, shown here, which you can use Lo speciy
new ormaLLing characLerisLics or Lhe LexL in Lhe selecLed label on your orm. 1he FonL
dialog box conLains more Lhan one ormaLLing opLion, or each opLion you selecL,
a .
6. Change Lhe onL sLyle rom Regular Lo Oblique (LhaL is, lLalic), and Lhen click OK Lo
.
visual SLudio records your changes and adjusLs Lhe properLy seLLings accordingly.
ou can examine Lhe changes by viewing your orm in Lhe Designer or by expanding
Lhe FonL properLy in Lhe ProperLies window.
l6 Part I Gettng Started wth Mcrosoft VsuaI asc 20l0
Now change a properLy seLLing or Lhe lcbel2 objecL (Lhe label LhaL conLains Lhe LexL
"1he 8ass CuiLar").
7. ln Lhe Designer, click Lhe second label objecL (lcbel2).
When you selecL Lhe objecL, resize handles surround iL.
8. Click Lhe lcnt properLy in Lhe ProperLies window.
1he lcbel2 objecL has iLs own unique seL o properLy seLLings. AlLhough Lhe properLy
names are Lhe same as Lhose o Lhe lcbel1 objecL, Lhe values in Lhe properLy seLLings
are disLincL and allow Lhe lcbel2 objecL Lo acL independenLly on Lhe orm.
9. Click Lhe FonL ellipsis buLLon, seL Lhe onL sLyle Lo 8old and Lhe onL size Lo 2 poinLs,
and Lhen click OK.
l0. Scroll Lo Lhe lcreCclcr properLy in Lhe ProperLies window, and Lhen click iL in Lhe leL
column.
ll. Click Lhe ForeColor arrow in Lhe righL column, click Lhe CusLom Lab, and Lhen click
a dark purple color.
1he LexL in Lhe lcbel2 objecL is now bold and purple on Lhe orm, as shown here.
CongraLulaLions! ou've jusL learned how Lo seL properLies in a visual 8asic program by using
Lhe visual SLudio ProperLies window-one o Lhe imporLanL skills in becoming a visual 8asic
programmer.
Chapter l fxpIorng the VsuaI Studo Integrated DeveIopment fnvronment l7
Moving and kesizing the Programming TooIs
WiLh numerous programming Lools Lo conLend wiLh on Lhe screen, Lhe visual SLudio lDF
can become a preLLy busy place. 1o give you compleLe conLrol over Lhe shape and size o
Lhe elemenLs in Lhe developmenL environmenL, visual SLudio leLs you move, resize, dock,
and auLo hide mosL o Lhe inLerace elemenLs LhaL you use Lo build programs.
1o move one o Lhe Lool windows in visual SLudio, simply click Lhe LiLle bar and drag Lhe
objecL Lo a new locaLion. l you align one window along Lhe edge o anoLher window, iL
aLLaches Lo LhaL window, or Jccls iLsel. Dockable windows are advanLageous because Lhey
always remain visible. (1hey don'L become hidden behind oLher windows.) l you wanL Lo
see more o a docked window, simply drag one o iLs borders Lo view more conLenL.
l you wanL Lo compleLely close a window, click Lhe Close buLLon in Lhe upper-righL corner
o Lhe window. ou can always open Lhe window again laLer by clicking Lhe appropriaLe
command on Lhe view menu.
l you wanL an opLion somewhere beLween docking and closing a window, you mighL Lry
auLo hiding a Lool window aL Lhe side o Lhe visual SLudio lDF by clicking Lhe Liny AuLo Hide
pushpin buLLon on Lhe righL side o Lhe Lool's LiLle bar. 1his acLion removes Lhe window
rom Lhe docked posiLion and places Lhe LiLle o Lhe Lool aL Lhe edge o Lhe developmenL
environmenL in an unobLrusive Lab. When you auLo hide a window, you'll noLice LhaL Lhe Lool
window remains visible as long as you keep Lhe mouse poinLer in Lhe area o Lhe window.
When you move Lhe mouse Lo anoLher parL o Lhe lDF, Lhe window slides ouL o view.
1o resLore a window LhaL you have auLo hidden, click Lhe Lool Lab aL Lhe edge o Lhe
developmenL environmenL or hold your mouse over Lhe Lab. (ou can recognize a window
LhaL is auLo hidden because Lhe pushpin in iLs LiLle bar is poinLing sideways.) 8y holding Lhe
mouse poinLer over Lhe LiLle, you can use Lhe Lools in whaL l call "peek-a-boo" mode-in oLher
words, Lo quickly display an auLo hidden window, click iLs Lab, check or seL Lhe inormaLion
you need, and Lhen move Lhe mouse Lo make Lhe window disappear. l you ever need Lhe
Lool displayed permanenLly, click Lhe AuLo Hide pushpin buLLon again so LhaL Lhe poinL o
Lhe pushpin aces down, and Lhe window Lhen remains visible.
AnoLher useul eaLure o visual SLudio is Lhe abiliLy Lo display windows as Labbed documenLs
(windows wiLh Lab handles LhaL parLially hide behind oLher windows) and Lo dock windows by
using Lhe docking guides LhaL appear as Liny squares on Lhe perimeLer o Lhe lDF, as well as
a cenLrally locaLed "guide diamond," as shown on Lhe nexL page.
l8 Part I Gettng Started wth Mcrosoft VsuaI asc 20l0
1he docking guides are changeable icons LhaL appear on Lhe surace o Lhe lDF when you
move a window or Lool rom a docked posiLion Lo a new locaLion. 8ecause Lhe docking
guides are associaLed wiLh shaded, recLangular areas o Lhe lDF, you can preview Lhe resulLs
o your docking maneuver beore you acLually make iL. ln visual SLudio 200, Lhis eaLure has
docking guides, none o which remain permanenL unLil you release Lhe mouse buLLon.
8ecause docking and auLo hiding Lechniques Lake some pracLice Lo masLer, l recommend LhaL
you use Lhe ollowing exercises Lo experimenL wiLh Lhe window-managemenL eaLures o Lhe
lDF.
a way LhaL seems comorLable or you.
Movng and Reszng 1ooI Wndows
1o move and resize one o Lhe programming Lool windows in visual SLudio, ollow Lhese
sLeps. 1his exercise demonsLraLes how Lo manipulaLe Lhe ProperLies window, buL you can
work wiLh a dierenL Lool window i you wanL Lo.
24 Part I Gettng Started wth Mcrosoft VsuaI asc 20l0
2. FxperimenL wiLh Lhe browser and how iL uncLions wiLhin Lhe lDF.
AlLhough Lhe browser is more basic Lhan lnLerneL Fxplorer or anoLher ull-eaLured
. ou can
also open and run lnLerneL Fxplorer (or anoLher browser) direcLly rom Lhe Windows
Laskbar.
3.
or LiLle bar Lo close Lhe window.
Getting HeIp
visual SLudio includes Help documenLaLion LhaL you can use Lo learn more abouL Lhe visual
SLudio lDF, Lhe visual 8asic programming language, and Lhe MicrosoL .NF1 Framework.
1ake a momenL Lo explore Lhese Help resources now beore moving on Lo ChapLer 2, where
.
l you have used visual SLudio 2008, you will noLice some dierences in Lhe visual SLudio
200 Help documenLaLion. .
1able - highlighLs Lhe major dierences LhaL you should be aware o.
30 Part I Gettng Started wth Mcrosoft VsuaI asc 20l0
3.
name and older locaLion in which visual SLudio plans Lo save Lhe seLLings.
l you wanL Lo go back Lo Lhese seLLings, you'll use Lhis same wizard and Lhe lmporL
SelecLed FnvironmenLal SeLLings radio buLLon Lo resLore Lhem.
4. Click NexL Lo view Lhe deaulL lisL o seLLings LhaL you can use or visual SLudio.
Depending on whaL visual SLudio componenLs are insLalled, you will see a lisL o
seLLings similar Lo Lhose shown in Lhe ollowing screen shoL.
5. Click visual 8asic DevelopmenL SeLLings (i iL is noL already selecLed), and click Finish.
1p l you are using visual 8asic 200 Fxpress, click FxperL SeLLings, and click Finish.
1he wizard swiLches your lDF seLLings, including menu commands, Loolbars,
and seLLings wiLhin a ew dialog boxes, Lool windows, and Lhe Code FdiLor.
Feel ree Lo repeaL Lhis cusLomizaLion process any Lime LhaL you need Lo reseL your
seLLings (or example, i you make a cusLomizaLion misLake LhaL you regreL), or i you
wanL Lo cusLomize visual SLudio or anoLher programming Lool.
6. Click Close Lo close Lhe wizard.
32 Part I Gettng Started wth Mcrosoft VsuaI asc 20l0
conLain only one projecL (Lhe siLuaLion or mosL programs in Lhis book). 1he second
opLion causes visual SLudio Lo posLpone saving your projecL unLil you click Lhe Save
. 1his "delayed
save" eaLure allows you Lo creaLe a LesL program, compile and debug Lhe program,
and even run iL wiLhouL acLually saving Lhe projecL on disk-a useul eaLure when you
wanL Lo creaLe a quick LesL program LhaL you mighL wanL Lo discard insLead o saving.
(An equivalenL siLuaLion in word-processing Lerms is when you open a new Word
documenL, enLer an address or a mailing label, prinL Lhe address, and Lhen exiL Word
.) WiLh Lhis deaulL seLLing, Lhe exercises in Lhis book prompL you
Lo save your projecLs aLer you creaLe Lhem, alLhough you can also save your projecLs
in advance by selecLing Lhe Save New ProjecLs When CreaLed check box.
ou'll also noLice LhaL l have Lyped "C.\vb0sbs" in Lhe ProjecLs LocaLion LexL box Lo
. MosL o Lhe projecLs LhaL
Lhem rom Lhe compleLed projecL l provide or you Lo examine. (8e sure Lo change Lhis
seLLing on your compuLer as well.)
ALer you have adjusLed Lhese seLLings, you're ready Lo check our visual 8asic compiler
seLLings.
4. Click Lhe v8 DeaulLs iLem in Lhe OpLions dialog box.
visual SLudio displays a lisL o our compiler seLLings. OpLion FxpliciL, OpLion SLricL,
OpLion Compare, and OpLion lner. our screen looks like Lhis.
AlLhough a deLailed descripLion o Lhese seLLings is beyond Lhe scope o Lhis chapLer,
you'll wanL Lo veriy LhaL OpLion FxpliciL is seL Lo On and OpLion SLricL is seL Lo O-Lhe
deaulL seLLings or visual 8asic programming wiLhin visual SLudio. OpLion FxpliciL On
Chapter l fxpIorng the VsuaI Studo Integrated DeveIopment fnvronment 33
is a seLLing LhaL requires you Lo declare a variable beore using iL in a program-a very
good programming pracLice LhaL l wanL Lo encourage. OpLion SLricL O allows variables
and objecLs o dierenL Lypes Lo be converLed in cerLain circumsLances wiLhouL
generaLing a compiler error. (For example, a number can be assigned Lo a LexL box
objecL wiLhouL error.) AlLhough Lhis is a poLenLially worrisome programming pracLice,
OpLion SLricL O is a useul seLLing or cerLain Lypes o demonsLraLion programs. l you
don'L keep Lhis seLLing, a ew projecLs will display error messages when you run Lhem.
OpLion Compare deLermines Lhe comparison meLhod when dierenL sLrings are
compared and sorLed. For more inormaLion abouL comparing sLrings and sorLing LexL,
see ChapLer 8, "Fxploring 1exL Files and SLring Processing."
OpLion lner was a new seLLing in visual 8asic 2008. When you seL OpLion SLricL Lo O
and OpLion lner Lo On, you can declare variables wiLhouL expliciLly sLaLing a daLa Lype,
or raLher, i you make such a declaraLion, Lhe visual 8asic compiler will iner (or Lake
an educaLed guess) abouL Lhe daLa Lype based on Lhe iniLial assignmenL you made or
Lhe variable. 1he designers o visual 8asic creaLed Lhis seLLing Lo make wriLing code
. ou'll learn more abouL
Lhe eaLure in ChapLer 5, "visual 8asic variables and Formulas, and Lhe .NF1
Framework."
As a general rule, l recommend LhaL you seL OpLion lner Lo O Lo avoid unexpecLed
resulLs in how variables are used in your programs. l have seL OpLion lner Lo O in
mosL o Lhe sample projecLs included on Lhe companion CD.
5. Feel ree Lo examine addiLional seLLings in Lhe OpLions dialog box relaLed Lo your
programming environmenL and visual SLudio.
Lhe OpLions dialog box.
ou're ready Lo exiL visual SLudio and sLarL programming.
One Step lurther. xiting VisuaI Studio
Fach chapLer in Lhis book concludes wiLh a secLion LiLled "One SLep FurLher" LhaL enables
you Lo pracLice an addiLional skill relaLed Lo Lhe Lopic aL hand. ALer Lhe "One SLep FurLher"
LuLorial, l've compiled a uick Reerence Lable in each chapLer LhaL reprises Lhe imporLanL
concepLs discussed in Lhe chapLer, so LhaL i you need Lo reer Lo a concepL quickly, you can
have ready access Lo iL.
and close Lhe developmenL environmenL. Cive iL a Lry.
37
ChapLer 2
Wrtng Your frst Program
After compIetng ths chapter, you wII be abIe to:
CreaLe Lhe user inLerace or a new program.
SeL Lhe properLies or each objecL in your user inLerace.
WriLe program code.
Save and run Lhe program.
.
As you learned in ChapLer , "Fxploring Lhe visual SLudio lnLegraLed DevelopmenL
FnvironmenL," Lhe MicrosoL visual SLudio 200 lnLegraLed DevelopmenL FnvironmenL (lDF)
conLains several powerul Lools Lo help you run and manage your programs. visual SLudio
also conLains everyLhing you need Lo build your own applicaLions or Windows and Lhe Web
rom Lhe ground up.
ln Lhis chapLer, you'll learn how Lo creaLe a simple buL aLLracLive user inLerace wiLh Lhe
conLrols in Lhe visual SLudio 1oolbox. NexL you'll learn how Lo cusLomize Lhe operaLion
o Lhese conLrols wiLh properLy seLLings. 1hen you'll see how Lo idenLiy jusL whaL your
program should do by wriLing program code. Finally, you'll learn how Lo save and run your
new .
Lucky Seven. Your lirst VisuaI Basic Program
1he Windows-based applicaLion you're going Lo consLrucL is Lucky Seven, a game program
LhaL simulaLes a lucky number sloL machine. Lucky Seven has a simple user inLerace and can
be creaLed and compiled in jusL a ew minuLes using MicrosoL visual 8asic. Here's whaL your
Chapter 2 Wrtng Your frst Program 39
applicaLion projecL in Lhis exercise, Lhis dialog box is also Lhe gaLeway Lo oLher Lypes
o developmenL projecLs, such as a Web applicaLion, console applicaLion, MicrosoL
deploymenL projecL.
Near Lhe Lop o Lhe New ProjecL dialog box, you will noLice a drop-down lisL box.
1his eaLure allows you Lo speciy Lhe version o Lhe MicrosoL .NF1 Framework LhaL
your applicaLion will LargeL. 1his eaLure is someLimes called multi-tcretin, meaning
LhaL Lhrough iL, you can selecL Lhe LargeL environmenL LhaL your program will run on.
For example, i you reLain Lhe deaulL selecLion o .NF1 Framework 4, any compuLer LhaL
your applicaLion will run on musL have .NF1 Framework 4 insLalled. (NoL Lo worry-Lhe
.NF1 Framework is usually insLalled as parL o Lhe operaLing sysLem insLallaLion, or when
you insLall a new visual 8asic program LhaL you have wriLLen.) Unless you have a
need, you can jusL leave Lhis drop-down lisL aL iLs deaulL seLLing o .NF1 Framework 4.
visual 8asic 200 Fxpress does noL include Lhis drop-down lisL. ou'll learn more abouL
Lhe .NF1 Framework in ChapLer 5, "visual 8asic variables and Formulas, and Lhe .NF1
Framework."
3. Click Lhe Windows Forms ApplicaLion icon in Lhe cenLral 1emplaLes area o Lhe dialog
box, i iL is noL already selecLed.
visual SLudio prepares Lhe developmenL environmenL or visual 8asic Windows
applicaLion programming.
Chapter 2 Wrtng Your frst Program 4l
2. Click Lhe 1oolbox Lab Lo display Lhe 1oolbox window in Lhe lDF.
1he 1oolbox conLains all Lhe conLrols LhaL you'll use Lo build visual 8asic programs in
Lhis book. 1he conLrols suiLable or creaLing a Windows applicaLion are visible now
because you selecLed Lhe Windows ApplicaLion projecL Lype earlier. ConLrols are
organized by Lype, and by deaulL Lhe Common ConLrols caLegory is visible. (l Lhe
1oolbox is noL visible now, click 1oolbox on Lhe view menu Lo display iL.)
3. Double-click Lhe 3uttcn conLrol in Lhe 1oolbox, and Lhen move Lhe mouse poinLer away
rom Lhe 1oolbox.
visual SLudio creaLes a deaulL-sized buLLon objecL on Lhe orm and hides Lhe 1oolbox,
as shown here.
46 Part I Gettng Started wth Mcrosoft VsuaI asc 20l0
. 1hese include seLLings
or Lhe background color, LexL, onL heighL, and widLh o Lhe buLLon. 8ecause Lhere are
so many properLies, visual SLudio organizes Lhem inLo caLegories and displays Lhem
in ouLline view. l you wanL Lo see Lhe properLies in a caLegory, click Lhe arrow sign (>)
nexL Lo Lhe caLegory LiLle.
5. l iL is noL already visible, scroll in Lhe ProperLies window unLil you see Lhe 1ext properLy
locaLed in Lhe Appearance caLegory.
6. Double-click Lhe 1ext .
1he currenL 1ext seLLing ("8uLLon") is highlighLed in Lhe ProperLies window.
7. 1ype Spin, and Lhen press FN1FR.
1he 1ext properLy changes Lo "Spin" in Lhe ProperLies window and on Lhe buLLon
on Lhe orm. Now you'll change Lhe 1ext properLy o Lhe second buLLon Lo "Fnd."
(ou'll selecL Lhe second buLLon in a new way Lhis Lime.)
8. Open Lhe ObjecL lisL aL Lhe Lop o Lhe ProperLies window.
A lisL o Lhe inLerace objecLs in your program appears as ollows.
9. Click 8uLLon2 SysLem.Windows.Forms.8uLLon (Lhe second buLLon) in Lhe lisL box.
1he properLy seLLings or Lhe second buLLon appear in Lhe ProperLies window, and
visual SLudio highlighLs 8uLLon2 on Lhe orm.
l0. Double-click Lhe currenL 1ext properLy ("8uLLon2"), Lype nd, and Lhen press FN1FR.
1he LexL o Lhe second buLLon changes Lo "Fnd."
50 Part I Gettng Started wth Mcrosoft VsuaI asc 20l0
7. Click OK.
1he PayCoins phoLo is loaded inLo Lhe picLure box. 8ecause Lhe phoLo is relaLively small
(24 K8), iL opens quickly on Lhe orm.
8.
image.
l sized my picLure box objecL Lo be 44 pixels wide by 46 pixels high. ou can maLch
Lhis size by using Lhe widLh and heighL dimensions locaLed on Lhe lower-righL side
o Lhe visual SLudio lDF. (1he dimensions o Lhe selecLed objecL are given on Lhe
lower-righL side, and Lhe locaLion on Lhe orm o Lhe objecL's upper-leL corner is given
Lo Lhe leL o Lhe dimensions.)
1his parLicular image displays besL when Lhe picLure box objecL reLains a square shape.
Note As you look aL Lhe picLure box objecL, you mighL noLice a Liny shorLcuL arrow called
a smcrt tc near iLs upper-righL corner. 1his smarL Lag is a buLLon LhaL you can click Lo
quickly change a ew common picLure box seLLings and open Lhe SelecL Resource dialog
box. (ou'll see Lhe smarL Lag again in ChapLer 4, "Working wiLh Menus, 1oolbars, and
Dialog 8oxes," when you use Lhe 1cclStri conLrol.)
Now you'll change Lhe visible properLy Lo False so LhaL Lhe image will be invisible when
Lhe program sLarLs.
9. Click Lhe visible properLy in Lhe 8ehavior caLegory o Lhe ProperLies window, and Lhen
click Lhe arrow in Lhe second column.
1he valid seLLings or Lhe visible properLy appear in a lisL box.
l0. Click False Lo make Lhe picLure invisible when Lhe program sLarLs.
Chapter 2 Wrtng Your frst Program 53
lnside Lhe Code FdiLor are program sLaLemenLs associaLed wiLh Lhe currenL orm.
Program sLaLemenLs LhaL are used LogeLher Lo perorm some acLion are Lypically
grouped in a programming consLrucL called a rcceJure. A common Lype o procedure
is a Sub procedure, someLimes called a subrcutine. Sub procedures include a Sub
lnJ Sub. (l'll Lalk abouL Lhe Public and PrivaLe
keywords laLer.) Procedures are Lypically execuLed when cerLain evenLs occur, such as
when a buLLon is clicked. When a procedure is associaLed wiLh a parLicular objecL and
an evenL, iL is called an event hcnJler or an event rcceJure.
When you double-clicked Lhe Fnd buLLon (3uttcn2), visual SLudio auLomaLically added
3uttcn2_Clicl evenL procedure, as Lhe ollowing code
shows. .) ou may noLice
oLher biLs o code in Lhe Code FdiLor (words like Public and Clcss), which visual SLudio
Lhem here.
Pr i vat e Sub But t on2_Cl i ck( ByVal sender As Syst em. Obj ect , _
ByVal e As Syst em. Event Ar gs) Handl es But t on2. Cl i ck
End Sub
acLivaLes Lhe inLerace elemenL associaLed wiLh Lhe procedure. ln Lhis case, Lhe evenL
is a mouse click, buL as you'll see laLer in Lhe book, iL could also be a dierenL Lype
o evenL.
2. 1ype nd, and Lhen press Lhe FN1FR key.
When you Lype Lhe sLaLemenL, visual SLudio recognizes lnJ as a unique reserved word
or leywcrJ and displays iL in a lisL box wiLh Common and All Labs. MicrosoL calls Lhis
auLo-exLend eaLure lnLelliSense because iL Lries Lo inLelligenLly help you wriLe code,
and you can browse Lhrough various visual 8asic keywords and objecLs alphabeLically.
(ln Lhis way, Lhe language is parLially discoverable Lhrough Lhe lDF iLsel.)
ALer you press Lhe FN1FR key, Lhe leLLers in lnJ Lurn blue and are indenLed, indicaLing
LhaL visual 8asic recognizes lnJ as one o several hundred unique keywords wiLhin
Lhe visual 8asic language. ou use Lhe lnJ keyword Lo sLop your program and
remove iL rom Lhe screen. ln Lhis case, lnJ is also a compleLe rcrcm stctement,
a sel-conLained insLrucLion execuLed by Lhe visucl 3csic ccmiler, Lhe parL o visual
SLudio LhaL processes or crses each line o visual 8asic scurce ccJe, combining Lhe
resulL wiLh . Program sLaLemenLs are a liLLle
like compleLe senLences in a human language-sLaLemenLs can be o varying lengLhs
buL musL ollow Lhe grammaLical "rules" o Lhe compiler. ln visual SLudio, program
sLaLemenLs can be composed o keywords, properLies, objecL names, variables,
numbers, special symbols, and oLher values. ou'll learn more abouL how program
sLaLemenLs are consLrucLed in ChapLer 5.
As you enLer program sLaLemenLs and make oLher ediLs, Lhe Code FdiLor handles many
o Lhe ormaLLing deLails or you, including adjusLing indenLaLion and spacing and
Chapter 2 Wrtng Your frst Program 55
1p As you enLer Lhe program code, visual 8asic ormaLs Lhe LexL and displays dierenL
parLs o Lhe program in color Lo help you idenLiy Lhe various elemenLs. When you begin
Lo Lype a properLy, visual 8asic also displays Lhe available properLies or Lhe objecL you're
using in a lisL box, so you can double-click Lhe properLy or keep Lyping Lo enLer iL yoursel.
l visual 8asic displays an error message, you mighL have misspelled a program sLaLemenL.
Check Lhe line againsL Lhe LexL in Lhis book, make Lhe necessary correcLion, and conLinue
Lyping. (ou can also deleLe a line and Lype iL rom scraLch.) ln addiLion, visual 8asic mighL
add necessary code auLomaLically. For example, when you Lype Lhe ollowing code, visual
8asic auLomaLically adds Lhe lnJ lj line. Readers o previous ediLions o Lhis book have
. Halvorson,
l know l Lyped iL jusL as you wroLe iL!"-so please give Lhis program code your closesL
aLLenLion. l promise you, iL works!
Pi ct ur eBox1. Vi si bl e = Fal se ' hi de pi ct ur e
Label 1. Text = CSt r ( I nt ( Rnd( ) * 10) ) ' pi ck number s
Label 2. Text = CSt r ( I nt ( Rnd( ) * 10) )
Label 3. Text = CSt r ( I nt ( Rnd( ) * 10) )
' i f any number i s 7 di spl ay pi ct ur e and beep
I f ( Label 1. Text = "7") Or ( Label 2. Text = " 7" ) _
Or ( Label 3. Text = "7") Then
Pi ct ur eBox1. Vi si bl e = Tr ue
Beep( )
End I f
56 Part I Gettng Started wth Mcrosoft VsuaI asc 20l0
4. Click Lhe Save All command on Lhe File menu Lo save your addiLions Lo Lhe program.
. Since
opens, prompLing you or Lhe name and locaLion o Lhe projecL. (l your copy o
projecL, you won'L see Lhe Save ProjecL dialog box now-visual SLudio jusL saves
your changes.)
5. .
l recommend LhaL you use Lhe C.\vb0sbs\Chap02 older (Lhe locaLion o Lhe book's
.
l builL or you on disk.
6. Clear Lhe CreaLe DirecLory For SoluLion check box.
When Lhis check box is selecLed, iL creaLes a second older or your program's soluLion
mosL programs in Lhis book).
7. .
Note l you wanL Lo save jusL Lhe iLem you are currenLly working on (Lhe orm, Lhe code
module, or someLhing else), you can use Lhe Save command on Lhe File menu. l you wanL
Lo save Lhe currenL iLem wiLh a dierenL name, you can use Lhe Save As command.
A Look at the 8uttonI_Click Procedure
1he 3uttcn1_Clicl procedure is execuLed when Lhe user clicks Lhe Spin buLLon on Lhe orm.
1he procedure uses some preLLy complicaLed sLaLemenLs, and because l haven'L ormally
inLroduced Lhem yeL, iL mighL look a liLLle conusing. However, i you Lake a closer look,
you'll probably see a ew Lhings LhaL look amiliar. 1aking a peek aL Lhe conLenLs o Lhese
procedures will give you a eel or Lhe Lype o program code you'll be creaLing laLer in
Lhis book. (l you'd raLher noL sLop or Lhis preview, eel ree Lo skip Lo Lhe nexL secLion,
"Running visual 8asic ApplicaLions.")
1he 3uttcn1_Clicl procedure perorms Lhree Lasks.
lL hides Lhe digiLal phoLo.
lL creaLes Lhree random numbers or Lhe number labels.
lL displays Lhe phoLo when Lhe number 7 appears.
Chapter 2 Wrtng Your frst Program 57
LeL's look aL each o Lhese sLeps individually.
Hiding Lhe phoLo is accomplished wiLh Lhe ollowing line.
Pi ct ur eBox1. Vi si bl e = Fal se ' hi de pi ct ur e
1his line is made up o Lwo parLs. a program sLaLemenL and a commenL.
1he Picture3cx1.visible = lclse program sLaLemenL seLs Lhe visible properLy o Lhe picLure
box objecL (Picture3cx1) Lo False (one o Lwo possible seLLings). ou mighL remember LhaL
you seL Lhis properLy Lo False once beore by using Lhe ProperLies window. ou're doing
away a phoLo LhaL mighL have been displayed in a previous game. 8ecause Lhe properLy
will be changed aL run Lime and noL aL design Lime, you musL seL Lhe properLy by using
program code. 1his is a handy eaLure o visual 8asic, and l'll Lalk abouL iL more in ChapLer 8,
"Working wiLh 1oolbox ConLrols."
a ccmment. CommenLs are explanaLory noLes included in program code ollowing a single
quoLaLion mark ('). Programmers use commenLs Lo describe how imporLanL sLaLemenLs work
in a program. 1hese noLes aren'L processed by visual 8asic when Lhe program runs, Lhey exisL
only Lo documenL whaL Lhe program does. ou'll wanL Lo use commenLs oLen when you
wriLe visual 8asic programs Lo leave an easy-Lo-undersLand record o whaL you're doing.
1he nexL Lhree lines handle Lhe random number compuLaLions. Does Lhis concepL sound
sLrange ou can acLually make visual 8asic generaLe unpredicLable numbers wiLhin
guidelines-in oLher words, you can creaLe random numbers or loLLery conLesLs, dice
games, or oLher sLaLisLical paLLerns. 1he RnJ uncLion in each line creaLes a random number
beLween 0 and (a number wiLh a decimal poinL and several decimal places), and Lhe lnt
uncLion reLurns Lhe inLeger porLion o Lhe resulL o mulLiplying Lhe random number by 0.
1his compuLaLion creaLes random numbers beLween 0 and 9 in Lhe program-jusL whaL you
need or Lhis parLicular sloL machine applicaLion.
Label 1. Text = CSt r ( I nt ( Rnd( ) * 10) ) ' pi ck number s
ou Lhen need Lo jump Lhrough a liLLle hoop in your code. ou need Lo copy Lhese random
converLed Lo
LexL wiLh Lhe CStr (converL Lo sLring) uncLion. NoLice how CStr, lnt, and RnJ are all connecLed in
Lhe program sLaLemenL-Lhey work collecLively Lo produce a resulL like a maLhemaLical ormula.
ALer Lhe compuLaLion and conversion, Lhe values are assigned Lo Lhe 1ext properLies o Lhe
numbers Lo be displayed in bold,
24-poinL, 1imes New Roman onL in Lhe Lhree number labels.
1he lasL group o sLaLemenLs in Lhe program checks wheLher any o Lhe random numbers is 7.
l one or more o Lhem is, Lhe program displays Lhe graphical depicLion o a payouL, and a
beep announces Lhe winnings.
Chapter 2 Wrtng Your frst Program 59
appears, and Lhe compuLer beeps. ou win! (1he sound you hear depends on your
DeaulL 8eep seLLing in Lhe Sound ConLrol Panel. 1o make Lhis game sound really cool,
change Lhe DeaulL 8eep sound Lo someLhing more dynamic.)
3. Click Lhe Spin buLLon 5 or 6 more Limes, waLching Lhe resulLs o Lhe spins in Lhe
number boxes.
AbouL hal Lhe Lime you spin, you hiL Lhe jackpoL-preLLy easy odds. (1he acLual odds
are abouL 2. .) LaLer on, you mighL wanL Lo
make Lhe game Lougher by displaying Lhe phoLo only when Lwo or Lhree 7s appear,
or by creaLing a running LoLal o winnings.
4. .
1he program sLops, and Lhe developmenL environmenL reappears on your screen.
1p l you run Lhis program again, you mighL noLice LhaL Lucky Seven displays exacLly Lhe
same sequence o random numbers. 1here is noLhing wrong here-Lhe visual 8asic RnJ
uncLion was designed Lo display a reectin
properly LesL your code using ouLpuL LhaL can be reproduced again and again. 1o creaLe
Lruly "random" numbers, use Lhe RcnJcmize uncLion in your code, as shown in Lhe
exercise aL Lhe end o Lhis chapLer. 1he .NF1 Framework, which you'll learn Lo use laLer, also
supplies random number uncLions.
SampIe Projects on Disk
l you didn'L build Lhe MyLucky7 projecL rom scraLch (or i you did build Lhe projecL and wanL Lo
compare whaL you creaLed Lo whaL l builL or you as l wroLe Lhe chapLer), Lake a momenL Lo open
and run Lhe compleLed Lucky7 projecL, which is locaLed in Lhe C.\vb0sbs\Chap02\Lucky7 older
. l you need a reresher
course on opening projecLs, see Lhe deLailed insLrucLions in ChapLer . l you are asked i you wanL
Lo save changes Lo Lhe MyLucky7 projecL, be sure Lo click Save.
own and experimenLing wiLh Lhem. 8uL aLer you have compleLed Lhe projecLs, iL is oLen a
i you run inLo Lrouble.
beore you run Lhe compleLed program in mosL o Lhe sLep-by-sLep exercises.
. l you didn'L creaLe MyLucky7, use
.
60 Part I Gettng Started wth Mcrosoft VsuaI asc 20l0
BuiIding an xecutabIe liIe
our lasL Lask in Lhis chapLer is Lo compleLe Lhe developmenL process and creaLe an
applicaLion or Windows, or an . (Had you creaLed a dierenL projecL Lype,
o course, such as a Web applicaLion, Lhe resulL o your developmenL eorLs would have
.) Windows applicaLions creaLed wiLh
.exe and can be run on any sysLem LhaL conLains
.
Lhe . .) l you plan Lo disLribuLe your applicaLions, see Lhe
secLion enLiLled "Deploying our ApplicaLion" laLer in Lhe chapLer.
or your Windows applicaLion projecL. a debug build and a release build.
Debug builds are creaLed auLomaLically by visual SLudio when you creaLe and LesL
your program. 1hey are sLored in a older called 8in\Debug wiLhin your projecL older.
1he debug
slighLly slower.
projecL. 1o cusLomize Lhe seLLings or your release build, you click Lhe [PrcjectNcme]
ProperLies command on Lhe ProjecL menu, and Lhen click Lhe Compile Lab, where you see
a lisL o compilaLion opLions LhaL looks like Lhis.
62 Part I Gettng Started wth Mcrosoft VsuaI asc 20l0
DepIoying Your AppIication
visual SLudio helps you disLribuLe your visual 8asic applicaLions by providing several opLions
or Jelcyment-LhaL is, or insLalling Lhe applicaLion on one or more compuLer sysLems.
Since Lhe release o visual SLudio in 2002, visual 8asic applicaLions have been compiled as
Lo run. Assemblies conLain our elemenLs. MicrosoL inLermediaLe language (MSlL) code,
. visual SLudio 200 conLinues Lo
oer Lhis same basic deploymenL archiLecLure, wiLh some noLeworLhy improvemenLs or
dierenL plaLorms and applicaLion Lypes.
How do assemblies acLually work FirsL, assemblies are so comprehensive and sel-describing
LhaL visual SLudio applicaLions don'L acLually need Lo be ormally regisLered wiLh Lhe
operaLing sysLem Lo run. 1his means LhaL LheoreLically a visual 8asic 200 applicaLion can be
insLalled by simply copying Lhe assembly or Lhe program Lo a second compuLer LhaL has Lhe
correcL version o Lhe .NF1 Framework insLalled-a process called XCOPY instcllcticn, aLer
Lhe MS-DOS XCOP command LhaL copies a compleLe direcLory (older) sLrucLure rom one
locaLion Lo anoLher. ln pracLice, however, iL isn'L pracLical Lo deploy visual 8asic applicaLions
by using a copy procedure such as XCOP (via Lhe command prompL) or Windows Fxplorer.
For commercial applicaLions, an insLallaLion program wiLh a graphical user inLerace is usually
preerred, and iL's oLen desirable Lo regisLer Lhe program wiLh Lhe operaLing sysLem so
LhaL iL can be uninsLalled laLer by using ConLrol Panel. ln addiLion, iL is oLen useul Lo Lake
advanLage o Lhe Web or an applicaLion's iniLial deploymenL and Lo have an applicaLion
check Lhe Web periodically or updaLes.
AlLhough Lhe advanced opLions relaLed Lo deploymenL and securiLy go beyond Lhe scope o
Lhis book, you should be amiliar wiLh your deploymenL opLions. 1o manage Lhe deploymenL
process, visual SLudio 200 supporLs Lwo deploymenL Lechnologies, CliclOnce and WinJcws
lnstcller.
FssenLially, ClickOnce is a robusL Web-based publishing Lechnology LhaL allows you Lo conLrol
how applicaLions are made available Lo users via Lhe lnLerneL, alLhough ClickOnce insLallaLions
can also be disLribuLed via CD-ROM. WiLh ClickOnce, you can creaLe an insLallaLion service
Lheir own wiLh minimal inLeracLion. WiLh ClickOnce, you can speciy prerequisiLes, such as
a parLicular version o Lhe .NF1 Framework, and you can easily publish updaLes on a Web page
. ou can geL sLarLed wiLh
ClickOnce aL any Lime by using Lhe Publish command on Lhe 8uild menu. And you can conLrol
how ClickOnce works by seLLing properLies using Lhe ProperLies command on Lhe ProjecL
menu. .)
67
ChapLer 8
Workng wth 1ooIbox ControIs
After compIetng ths chapter, you wII be abIe to:
Use 1ext3cx and 3uttcn conLrols Lo creaLe a Hello World program.
Use Lhe Dcte1imePicler conLrol Lo display your birLh daLe.
Use Checl3cx, RcJic3uttcn, and list3cx conLrols Lo process user inpuL.
Use Lhe linllcbel conLrol and Lhe Prccess.Stcrt meLhod Lo display a Web page by
using your sysLem's deaulL browser.
As you learned in earlier chapLers, MicrosoL visual SLudio 200 conLrols are Lhe graphical
Lools you use Lo build Lhe user inLerace o a MicrosoL visual 8asic program. ConLrols are
locaLed in Lhe developmenL environmenL's 1oolbox, and you use Lhem Lo creaLe objecLs
on a orm wiLh a simple series o mouse clicks and dragging moLions.
Lhe conLrols are also accessible on Labs such as Common ConLrols, ConLainers, and PrinLing.
(ou used a ew o Lhese conLrols in Lhe previous chapLer.) Among Lhe Common ConLrols,
Lhere are ew changes beLween visual 8asic 2008 and visual 8asic 200, so i you're really
experienced wiLh Lhe lasL version o visual 8asic, you may simply wanL Lo move on Lo Lhe
daLabase and Web applicaLion chapLers o Lhis book (ParL lv), or Lhe deLailed maLerial abouL
programming Lechniques in ParLs ll and lll. However, or mosL casual visual 8asic users, Lhere is
a loL sLill Lo learn abouL Lhe language's exLensive collecLion o Windows Forms 1oolbox conLrols,
and we'll work wiLh several o Lhem here.
ln Lhis chapLer, you'll learn how Lo display inormaLion in a LexL box, work wiLh daLe and Lime
inormaLion on your sysLem, process user inpuL wiLh Checl3cx, RcJic3uttcn, and list3cx
conLrols, and display a Web page wiLhin a visual 8asic program. 1he exercises in Lhis chapLer
will help you design your own visual 8asic applicaLions and will Leach you more abouL
objecLs, properLies, and program code. l you are new Lo visual SLudio and visual 8asic, Lhis
chapLer will be especially useul.
The Basic Use of ControIs. The HeIIo worId Program
A greaL LradiLion in inLroducLory programming books is Lhe Hello World program, which
demonsLraLes how Lhe simplesL uLiliLy can be builL and run in a given programming
language. ln Lhe days o characLer-based programming, Hello World was usually a Lwo-line
or Lhree-line program Lyped in a program ediLor and assembled wiLh a sLand-alone compiler.
Chapter 3 Workng wth 1ooIbox ControIs 69
70 Part I Gettng Started wth Mcrosoft VsuaI asc 20l0
6. Click Lhe 1ext3cx conLrol on Lhe Common ConLrols Lab o Lhe 1oolbox.
7. Draw a LexL box similar Lo Lhis.
1ext bcxes are used Lo display LexL on a orm or Lo geL user inpuL while a program
is running. How a LexL box works depends on how you seL iLs properLies and how you
reerence Lhe LexL box in Lhe program code. ln Lhis program, a LexL box objecL will be used
Lo display Lhe message "Hello, world!" when you click a buLLon objecL on Lhe orm.
ou'll add a buLLon Lo Lhe orm now.
8. Click Lhe 3uttcn conLrol in Lhe 1oolbox.
9. Draw a buLLon below Lhe LexL box on Lhe orm.
our orm looks someLhing like Lhis.
74 Part I Gettng Started wth Mcrosoft VsuaI asc 20l0
4. Click Lhe Dcte1imePicler conLrol in Lhe 1oolbox.
5. Draw a daLe/Lime picker objecL near Lhe Lop o Lhe orm, as shown in Lhe ollowing
screen shoL.
1he daLe/Lime picker objecL by deaulL displays Lhe currenL daLe, buL you can adjusL Lhe
displayed daLe by changing Lhe objecL's vclue properLy. Displaying Lhe daLe is a handy
design guide-iL leLs you size Lhe daLe/Lime picker objecL appropriaLely when you're
creaLing iL.
6. Click Lhe 3uttcn conLrol in Lhe 1oolbox, and Lhen add a buLLon objecL below Lhe
daLe/Lime picker.
ou'll use Lhis buLLon Lo display your birLh daLe and Lo veriy LhaL Lhe daLe/Lime picker
works correcLly.
7. ln Lhe ProperLies window, change Lhe 1ext properLy o Lhe buLLon objecL Lo Show My
Birthday.
Now you'll add a ew lines o program code Lo a procedure associaLed wiLh Lhe buLLon
objecL. 1his is an evenL procedure because iL runs when an evenL, such as a mouse click,
occurs, or in Lhe objecL.
8. Double-click Lhe buLLon objecL on Lhe orm Lo display iLs deaulL evenL procedure,
and Lhen Lype Lhe ollowing program sLaLemenLs beLween Lhe Privcte Sub and lnJ Sub
sLaLemenLs in Lhe 3uttcn1_Clicl evenL procedure.
MsgBox( " Your bi r t h dat e was " & Dat eTi mePi cker 1. Text )
MsgBox( " Day of t he year : " & _
Dat eTi mePi cker 1. Val ue. DayOf Year . ToSt r i ng( ) )
Chapter 3 Workng wth 1ooIbox ControIs 75
1hese program sLaLemenLs display Lwo message boxes (small dialog boxes) wiLh
inormaLion rom Lhe daLe/Lime picker objecL. 1ext properLy o
Lhe daLe/Lime picker Lo display Lhe birLh daLe inormaLion LhaL you selecL when using
Lhe objecL aL run Lime. 1he Ms3cx uncLion displays Lhe sLring value "our birLh daLe
was" in addiLion Lo Lhe LexLual value held in Lhe daLe/Lime picker's 1ext properLy. 1hese
Lwo pieces o inormaLion are joined LogeLher by Lhe sLring concaLenaLion operaLor (&).
ou'll learn more abouL Lhe Ms3cx uncLion and Lhe sLring concaLenaLion operaLor in
ChapLer 5, "visual 8asic variables and Formulas, and Lhe .NF1 Framework."
1he second and Lhird lines collecLively orm one program sLaLemenL and have been
broken by Lhe line conLinuaLion characLer (_) because Lhe sLaLemenL was a biL Loo long
Lo prinL in Lhis book.
Program lines can be more Lhan 65,000 characLers long in Lhe visual SLudio Code
FdiLor, buL iL's usually easiesL Lo work wiLh lines o 80 or ewer characLers. ou can
divide long program sLaLemenLs among mulLiple lines by using a space and a line
conLinuaLion characLer (_) aL Lhe end o each line in Lhe sLaLemenL excepL or Lhe lasL
line. (ou cannoL use a line conLinuaLion characLer Lo break a sLring LhaL's in quoLaLion
marks, however.) l use Lhe line conLinuaLion characLer in Lhis exercise Lo break Lhe
second line o code inLo Lwo parLs.
Note SLarLing in visual 8asic 200, Lhe line conLinuaLion characLer (_) is opLional. 1here
are a ew insLances where Lhe line conLinuaLion characLer is needed, buL Lhey are rare. ln
Lhis book, l sLill use line conLinuaLion characLers Lo make iL clear where Lhere are long lines,
buL you don'L have Lo include Lhem.
1he sLaLemenL DaLe1imePicker.value.DayOear.1oSLring() uses Lhe daLe/Lime
picker objecL Lo calculaLe Lhe day o Lhe year in which you were born, counLing rom
January . 1his is accomplished by Lhe DcyOjYecr properLy and Lhe 1cStrin meLhod,
which converLs Lhe numeric resulL o Lhe daLe calculaLion Lo a LexLual value LhaL's more
easily displayed by Lhe Ms3cx uncLion.
MethcJs are special sLaLemenLs LhaL perorm an acLion or a service or a parLicular
objecL, such as converLing a number Lo a sLring or adding iLems Lo a lisL box. MeLhods
dier rom properLies, which conLain a value, and evenL procedures, which execuLe
when a user manipulaLes an objecL. MeLhods can also be shared among objecLs, so
when you learn how Lo use a parLicular meLhod, you'll oLen be able Lo apply iL Lo
several circumsLances. We'll discuss several imporLanL meLhods as you work Lhrough
Lhis book.
Chapter 3 Workng wth 1ooIbox ControIs 77
NoLice LhaL Lhe LexL box porLion o Lhe objecL also changes as you scroll Lhe daLe.
1he "Loday" value aL Lhe boLLom o Lhe calendar doesn'L change, however.
AlLhough you can scroll all Lhe way back Lo your exacL birLhday, you mighL noL have
Lhe paLience Lo scroll monLh by monLh. 1o move Lo your birLh year asLer, selecL Lhe
year value in Lhe daLe/Lime picker LexL box and enLer a new year.
4. SelecL Lhe our-digiL year in Lhe daLe/Lime picker LexL box.
When you selecL Lhe daLe, Lhe daLe/Lime picker closes.
5. 1ype your birLh year in place o Lhe year LhaL's currenLly selecLed, and Lhen click Lhe
arrow again.
1he calendar reappears in Lhe year o your birLh.
6. Click Lhe scroll arrow again Lo locaLe Lhe monLh in which you were born, and Lhen click
Lhe exacL day on which you were born.
displayed in Lhe LexL box. ou can click Lhe buLLon objecL Lo see how Lhis inormaLion
is made available Lo oLher objecLs on your orm.
7. Click Lhe Show My 8irLhday buLLon.
visual 8asic execuLes your program code and displays a message box conLaining Lhe
day and daLe o your birLh. NoLice how Lhe Lwo daLes shown in Lhe Lwo boxes maLch.
8. Click OK in Lhe message box.
A second message box appears, indicaLing Lhe day o Lhe year on which you were
Chapter 3 Workng wth 1ooIbox ControIs 8l
l. Click Lhe SLarL Debugging buLLon on Lhe SLandard Loolbar.
visual 8asic runs Lhe program in Lhe lDF. 1he calculaLor image appears in a picLure box
.
2. SelecL Lhe Copy Machine check box.
visual 8asic displays Lhe copy machine image, as shown here.
3. FxperimenL wiLh dierenL combinaLions o check boxes, selecLing or clearing Lhe boxes
several Limes Lo LesL Lhe program. 1he program logic you added wiLh a ew shorL
lines o visual 8asic code manages Lhe boxes perecLly. (ou'll learn much more abouL
program code in upcoming chapLers.)
4. Click Lhe Close buLLon on Lhe orm Lo end Lhe program.
Usng Group oxes and Rado uttons
1he RcJic3uttcn conLrol is anoLher Lool LhaL you can use Lo receive inpuL in a program,
and iL is also locaLed on Lhe Common ConLrols Lab o Lhe 1oolbox. Radio buLLons geL Lheir
name rom Lhe old push-buLLon car radios o Lhe 950s and 960s, when people pushed
or "selecLed" one buLLon on Lhe car radio and Lhe resL o Lhe buLLons clunked back Lo Lhe
unselecLed posiLion. Only one buLLon could be selecLed aL a Lime, because (iL was LhoughL)
Lhe driver should lisLen Lo only one Lhing aL a Lime. ln visual SLudio, you can also oer
muLually exclusive opLions or a user on a orm, allowing Lhem Lo pick one (and only one)
opLion rom a group. 1he procedure is Lo use Lhe Crcu3cx conLrol Lo creaLe a rame on Lhe
orm, and Lhen Lo use Lhe RcJic3uttcn conLrol Lo place Lhe desired number o radio buLLons
in Lhe rame. (8ecause Lhe Crcu3cx conLrol is noL used LhaL oLen, iL is locaLed on Lhe
ConLainers Lab o Lhe 1oolbox.) NoLe also LhaL your orm can have more Lhan one group o
86 Part I Gettng Started wth Mcrosoft VsuaI asc 20l0
our orm now will look similar Lo Lhis.
selecLions, and Lo pick rom Lhe selecLions while Lhe program is running.
6. Double-click Lhe list3cx1 objecL on Lhe orm Lo open Lhe Code FdiLor.
1he SelecteJlnJexChcneJ evenL procedure or Lhe list3cx1 objecL appears in Lhe
Code FdiLor. 1his procedure runs each Lime Lhe user clicks an iLem in Lhe lisL box objecL.
We need Lo updaLe Lhe image in Lhe picLure box objecL when Lhis happens, so you'll
add a line o program code Lo make iL happen.
7. 1ype Lhe ollowing program code.
' The l i st box i t emsel ect ed ( 0- 2) i s hel d i n t he Sel ect edI ndex pr oper t y
Sel ect Case Li st Box1. Sel ect edI ndex
Case 0
Pi ct ur eBox1. I mage = Syst em. Dr awi ng. I mage. Fr omFi l e _
( " c: \ vb10sbs\ chap03\ har ddi sk. bmp")
Case 1
Pi ct ur eBox1. I mage = Syst em. Dr awi ng. I mage. Fr omFi l e _
( " c: \ vb10sbs\ chap03\ pr i nt er . bmp" )
Case 2
Pi ct ur eBox1. I mage = Syst em. Dr awi ng. I mage. Fr omFi l e _
( " c: \ vb10sbs\ chap03\ sat edi sh. bmp")
End Sel ect
commenL.
CommenLs, which are displayed in green Lype, are simply noLes wriLLen by
a programmer Lo describe whaL's imporLanL or inLeresLing abouL a parLicular piece
o program code. l wroLe Lhis commenL Lo explain LhaL Lhe SelecteJlnJex properLy
reLurns a number Lo Lhe program corresponding Lo Lhe placemenL o Lhe iLem LhaL
Lhe user selecLed in Lhe lisL box. 1here will be Lhree iLems in Lhe lisL box in Lhis program,
Chapter 3 Workng wth 1ooIbox ControIs 87
and Lhey will be numbered 0, , and 2 (rom Lop Lo boLLom). One inLeresLing poinL here
is LhaL visual SLudio sLarLs Lhe counL aL 0, noL , which is airly Lypical among compuLer
programs and someLhing you'll see elsewhere in Lhe book.
1he enLire block o code LhaL you Lyped is acLually called a Select Ccse decision
sLrucLure, which explains Lo Lhe compiler how Lo process Lhe user's selecLion in Lhe lisL
box. 1he imporLanL keyword LhaL begins Lhis decision sLrucLure is list3cx1
.SelecteJlnJex, which is read as "Lhe SelecteJlnJex properLy o Lhe lisL box objecL
named list3cx1." l iLem 0 is selecLed, Lhe Ccse 9 secLion o Lhe sLrucLure, which uses
Lhe lrcmlile meLhod Lo load a picLure o an exLernal hard disk inLo Lhe picLure box
objecL, will be execuLed. l iLem is selecLed, Lhe Ccse 1 secLion will be execuLed, and
a prinLer will appear in Lhe picLure box objecL. l iLem 2 is selecLed, Lhe Ccse 2 secLion
will be execuLed, and a saLelliLe dish will appear. Don'L worry Loo much i Lhis is a liLLle
sLrange-you'll geL a more ulsome inLroducLion Lo decision sLrucLures in ChapLer 6.
Now you need Lo enLer some program code Lo add LexL Lo Lhe lisL box objecL. 1o do
Lhis, we'll do someLhing new-we'll puL some program sLaLemenLs in Lhe lcrm1_lccJ
.
8. SwiLch back Lo Lhe Designer and double-click Lhe orm (lcrm1) Lo display Lhe
lcrm1_lccJ evenL procedure in Lhe Code FdiLor.
1he lcrm1_lccJ evenL procedure appears. 1his program code is execuLed each Lime
Lhe LisL 8ox program is loaded inLo memory. Programmers puL program sLaLemenLs
in Lhis special procedure when Lhey wanL Lhem execuLed every Lime a orm loads.
(our program can display more Lhan one orm, or none aL all, buL Lhe deaulL behavior
is LhaL visual 8asic loads and runs Lhe lcrm1_lccJ evenL procedure each Lime Lhe user
runs Lhe program.
o Lhe user inLerace LhaL couldn'L be creaLed easily by using Lhe conLrols in Lhe 1oolbox
or Lhe ProperLies window.
9. 1ype Lhe ollowing program code.
' Add i t ems t o a l i st box l i ke t hi s:
Li st Box1. I t ems. Add( " Ext r a har d di sk")
Li st Box1. I t ems. Add( " Pr i nt er ")
Li st Box1. I t ems. Add( " Sat el l i t e di sh" )
accomplishes. 1he nexL Lhree lines add iLems Lo Lhe lisL box (list3cx1) in Lhe program.
1he words in quoLes will appear in Lhe lisL box when iL appears on Lhe orm.
1he imporLanL keyword in Lhese sLaLemenLs is AJJ, a handy meLhod LhaL adds iLems
Lo lisL boxes or oLher iLems. Remember LhaL in Lhe list3cx1_SelecteJlnJexChcneJ evenL
.
l0. Click Lhe Save All buLLon on Lhe Loolbar Lo save your changes, speciying Lhe
C.\vb0sbs\Chap08 older as Lhe locaLion.
Chapter 3 Workng wth 1ooIbox ControIs 89
1p Speaking o building robusL programs, you should know LhaL mosL o Lhe images in Lhis
simple example were loaded by using an cbsclute cth ncme in Lhe program code. AbsoluLe paLh
work well enough so long as Lhe iLem you are reerencing acLually exisLs aL Lhe .
However, in a commercial applicaLion, you can'L always be sure LhaL your user won'L move around
Lhey need are no longer locaLed in Lhe expecLed place. 1o make your applicaLions more seaworLhy,
or rcbust, iL is usually beLLer Lo use relaLive paLhs when accessing images and oLher resources.
ou can also embed images and oLher resources wiLhin your applicaLion. For inormaLion abouL
Lhis handy Lechnique, see Lhe "How Lo. CreaLe Fmbedded Resources" and "Accessing ApplicaLion
Resources" Lopics in Lhe visual SLudio 200 Help documenLaLion.
A Word About 1ermnoIogy
OK-now LhaL Lhis chapLer is compleLe, leL's do a quick Lerminology review. So ar in Lhis
book, l've used several dierenL Lerms Lo describe iLems in a visual 8asic program. Do
you know whaL mosL Lhese iLems are yeL lL's worLh lisLing several o Lhem now Lo clear
up any conusion. l Lhey are sLill unclear Lo you, bookmark Lhis secLion and review Lhe
chapLers LhaL you have jusL compleLed or more inormaLion. (A ew new Lerms are also
menLioned here or Lhe sake o compleLeness, and l'll describe Lhem more ully laLer
in Lhe book.)
Program statement A line o code in a visual 8asic program, a sel-conLained
insLrucLion execuLed by Lhe visual 8asic compiler LhaL perorms useul work wiLhin Lhe
applicaLion. Program sLaLemenLs can vary in lengLh (some conLain only one visual 8asic
enorced
by Lhe visual 8asic compiler. ln visual SLudio 200, program sLaLemenLs can be
composed o keywords, properLies, objecL names, variables, numbers, special symbols,
and oLher values. (See ChapLers 2 and 5.)
Keyword A reserved word wiLhin Lhe visual 8asic language LhaL is recognized by
Lhe visual 8asic compiler and perorms useul work. (For example, Lhe lnJ keyword
sLops program execuLion.) Keywords are one o Lhe basic building blocks o program
sLaLemenLs, Lhey work wiLh objecLs, properLies, variables, and oLher values Lo orm
compleLe lines o code and (Lhereore) insLrucLions or Lhe compiler and operaLing
sysLem. MosL keywords are shown in blue Lype in Lhe Code FdiLor. (See ChapLer 2.)
VarabIe A special conLainer used Lo hold daLa Lemporarily in a program.
1he programmer creaLes variables by using Lhe Dim sLaLemenL and Lhen uses Lhese
.
Numbers, names, and properLy values can be sLored in variables. (See ChapLer 5.)
90 Part I Gettng Started wth Mcrosoft VsuaI asc 20l0
ControI A Lool LhaL you use Lo creaLe objecLs in a visual 8asic program (mosL
commonly, on a orm). ou selecL conLrols rom Lhe 1oolbox and use Lhem Lo draw
objecLs wiLh Lhe mouse on a orm. ou use mosL conLrols Lo creaLe Ul elemenLs such
as buLLons, picLure boxes, and lisL boxes. (See especially ChapLers 2 Lhrough 4.)
Object An elemenL LhaL you creaLe in a visual 8asic program wiLh a conLrol in Lhe
1oolbox. (ln addiLion, objecLs are someLimes supplied by oLher sysLem componenLs,
and many o Lhese objecLs conLain daLa.) ln visual 8asic, Lhe orm iLsel is also an objecL.
1echnically speaking, objecLs are insLances o a class LhaL supporLs properLies, meLhods,
and evenLs. ln addiLion, objecLs have whaL is known as inherent juncticnclity-Lhey
know how Lo operaLe and can respond Lo cerLain siLuaLions on Lheir own. A lisL box
"knows" how Lo scroll, or example. (See ChapLers Lhrough 4.)
CIass
does. .
ln visual 8asic, you can use exisLing .NF1 Framework classes (like System.Mcth and
System.WinJcws.lcrms.lcrm), and you can build your own classes and inheriL properLies,
meLhods, and evenLs rom Lhem. (lnheritcnce allows one class Lo acquire Lhe pre-exisLing
inLerace and behavior characLerisLics o anoLher class.) AlLhough classes mighL sound
esoLeric aL Lhis poinL, Lhey are a key eaLure o visual SLudio 200. ln Lhis book, you will
use Lhem Lo build user inLeraces rapidly and Lo exLend Lhe work LhaL you do Lo oLher
programming projecLs. (See ChapLers 5 and 6.)
Namespace A hierarchical library o classes organized under a unique name, such
as System.WinJcws or System.Dicncstics. 1o access Lhe classes and underlying objecLs
wiLhin a namespace, you place an lmcrts sLaLemenL aL Lhe Lop o your program code.
Fvery projecL in visual SLudio also has a rooL namespace, which is seL using Lhe projecL's
ProperLies page. Namespaces are oLen reerred Lo as clcss librcries in visual SLudio
books and documenLaLion. (See ChapLer 5.)
Property A value or characLerisLic held by an objecL. For example, a buLLon objecL
has a 1ext properLy, Lo speciy Lhe LexL LhaL appears on Lhe buLLon, and an lmce
.
ln visual 8asic, properLies can be seL aL design Lime by using Lhe ProperLies window,
or aL run Lime by using sLaLemenLs in Lhe program code. ln code, Lhe ormaL or
seLLing a properLy is
Obj ect . Pr oper t y = Val ue
where Object is Lhe name o Lhe objecL you're cusLomizing, Prcerty is Lhe characLerisLic
you wanL Lo change, and vclue is Lhe new properLy seLLing. For example,
But t on1. Text = "Hel l o"
could be used in Lhe program code Lo seL Lhe 1ext properLy o Lhe 3uttcn1 objecL Lo
"Hello". (See ChapLers Lhrough 8.)
92 Part I Gettng Started wth Mcrosoft VsuaI asc 20l0
3. CreaLe a new visual 8asic Windows Forms ApplicaLion projecL named MywebLink.
1he new projecL is creaLed, and a blank orm appears in Lhe Designer.
4. Click Lhe linllcbel conLrol in Lhe 1oolbox, and draw a recLangular link label objecL on
your orm.
Link label objecLs look like label objecLs excepL LhaL all label LexL is displayed in blue
underlined Lype on Lhe orm.
5. SeL Lhe 1ext properLy o Lhe link label objecL Lo Lhe Uniorm Resource LocaLor (URL) or
Lhe MicrosoL Press home page. htt.//www.micrcscjt.ccm/lecrnin/bccls/.
our orm looks like Lhis.
6. Click Lhe orm in Lhe lDF Lo selecL iL. (Click Lhe orm iLsel, noL Lhe link label objecL.)
1his is Lhe Lechnique LhaL you use Lo view Lhe properLies o Lhe deaulL orm, Form,
in Lhe ProperLies window. Like oLher objecLs in your projecL, Lhe orm also has
properLies LhaL you can seL.
7. SeL Lhe 1ext properLy o Lhe orm objecL Lo web Link Test.
1he 1ext
Lime and when Lhe program runs. AlLhough Lhis cusLomizaLion isn'L relaLed exclusively
Lo Lhe Web, l LhoughL you'd enjoy picking up LhaL skill now, beore we move on Lo
oLher projecLs. (We'll cusLomize Lhe LiLle bar in mosL o Lhe programs we build.)
8. Double-click Lhe link label objecL, and Lhen Lype Lhe ollowing program code in Lhe
linllcbel1_linlClicleJ evenL procedure.
' Change t he col or of t he l i nk by set t i ng Li nkVi si t ed t o Tr ue.
Li nkLabel 1. Li nkVi si t ed = Tr ue
' Use t he Pr ocess. St ar t met hod t o open t he def aul t br owser
' usi ng t he Mi cr osof t Pr ess URL:
Chapter 3 Workng wth 1ooIbox ControIs 93
Syst em. Di agnost i cs. Pr ocess. St ar t _
( "ht t p: / / www. mi cr osof t . com/ l ear ni ng/ books/ ")
l've included more commenLs in Lhe program code Lo give you some pracLice enLering
Lhem. As soon as you enLer Lhe single quoLe characLer ('), visual SLudio changes Lhe
color o Lhe line Lo green.
1he Lwo program sLaLemenLs LhaL aren'L commenLs conLrol how Lhe link works. SeLLing
Lhe linlvisiteJ properLy Lo 1rue gives Lhe link LhaL dimmer color o purple, which
indicaLes in many browsers LhaL Lhe HyperLexL Markup Language (H1ML) documenL
associaLed wiLh Lhe link has already been viewed. AlLhough seLLing Lhis properLy isn'L
necessary Lo display a Web page, iL's a good programming pracLice Lo provide Lhe
user wiLh inormaLion in a way LhaL's consisLenL wiLh oLher applicaLions.
1he second program sLaLemenL (which l have broken inLo Lwo lines) runs Lhe deaulL
Web browser (such as lnLerneL Fxplorer) i Lhe browser isn'L already running. (l Lhe
browser is running, Lhe URL jusL loads immediaLely.) 1he Stcrt meLhod in Lhe Prccess
class perorms Lhe imporLanL work, by sLarLing a process or execuLable program session
in memory or Lhe browser. 1he Prccess class, which manages many oLher aspecLs o
program execuLion, is a member o Lhe System.Dicncstics namespace. 8y including
an lnLerneL address or a URL wiLh Lhe Stcrt meLhod, l'm leLLing visual 8asic know LhaL
l wanL Lo view a Web siLe, and visual 8asic is clever enough Lo know LhaL Lhe deaulL
sysLem browser is Lhe Lool LhaL would besL display LhaL URL, even Lhough l didn'L
idenLiy Lhe browser by name.
An exciLing eaLure o Lhe Prccess.Stcrt meLhod is LhaL iL can be used Lo run oLher
Windows applicaLions, Loo. l l did wanL Lo idenLiy a parLicular browser by name Lo
. (Here l'll requesL
Lhe lnLerneL Fxplorer browser.)
Syst em. Di agnost i cs. Pr ocess. St ar t ( " I Expl or e. exe" , _
" ht t p: / / www. mi cr osof t . com/ l ear ni ng/ books/ " )
Here, Lwo argumenLs are used wiLh Lhe Stcrt meLhod, separaLed by a comma. 1he exacL
locaLion or Lhe program named lFxplore.
8asic will search Lhe currenL sysLem paLh or iL when Lhe program runs.
l l wanLed Lo run a dierenL applicaLion wiLh Lhe Stcrt meLhod-or example, i l wanLed
.doc-
l could use Lhe ollowing synLax.
Syst em. Di agnost i cs. Pr ocess. St ar t ( " Wi nwor d. exe" , _
" c: \ myl et t er . doc")
As you can see, Lhe Stcrt meLhod in Lhe Prccess class is very useul.
Now LhaL you've enLered your code, you should save your projecL. (l you experimenLed
wiLh Lhe Stcrt synLax as l showed you, resLore Lhe original code shown aL Lhe beginning
.)
97
ChapLer 4
Workng wth Menus, 1ooIbars,
and DaIog oxes
After compIetng ths chapter, you wII be abIe to:
Add menus Lo your programs by using Lhe MenuStri conLrol.
Process menu and Loolbar selecLions by using evenL procedures and Lhe Code FdiLor.
Add Loolbars and buLLons by using Lhe 1cclStri conLrol.
Use Lhe OenlileDiclc and CclcrDiclc conLrols Lo creaLe sLandard dialog boxes.
Add access keys and shorLcuL keys Lo menus.
ln ChapLer 8, "Working wiLh 1oolbox ConLrols," you used several MicrosoL visual SLudio
200 conLrols Lo gaLher inpuL rom Lhe user while he or she used a program. ln Lhis chapLer,
you'll learn how Lo presenL more choices Lo Lhe user by creaLing proessional-looking menus,
Loolbars, and dialog boxes.
A menu is locaLed on Lhe menu bar and conLains a lisL o relaLed commands, a Loolbar
conLains buLLons and oLher Lools LhaL perorm useul work in a program. MosL menu
and Loolbar commands are execuLed immediaLely aLer Lhey're clicked, or example, when
Lhe user clicks Lhe Copy command on Lhe FdiL menu, inormaLion is copied Lo Lhe Clipboard
immediaLely. l a menu command is ollowed by an ellipsis ( . . . ), however, clicking Lhe
command displays a dialog box requesLing more inormaLion beore Lhe command is carried
ouL, and many Loolbar buLLons also display dialog boxes.
ln Lhis chapLer, you'll learn how Lo use Lhe MenuStri and 1cclStri conLrols Lo add
a proessional look Lo your applicaLion's user inLerace. ou'll also learn how Lo process menu,
Loolbar, and dialog box commands.
Adding Menus by Using the MenuStri ControI
1he MenuStri conLrol is a Lool LhaL adds menus Lo your programs, which you can cusLomize
wiLh properLy seLLings in Lhe ProperLies window. WiLh MenuStri, you can add new menus,
modiy and reorder exisLing menus, and deleLe old menus. ou can also creaLe a sLandard
such as access keys, check marks, and keyboard shorLcuLs. 1he menus look perecL-jusL
like a proessional Windows applicaLion-buL MenuStri creaLes only Lhe visible parL o your
menus and commands. ou sLill need Lo wriLe evenL procedures LhaL process Lhe menu
Chapter 4 Workng wth Menus, 1ooIbars, and DaIog oxes 99
Designer laLer and ediL whaL you've done or add addiLional menu iLems-Lhe menu
sLrip objecL is ully cusLomizable and wiLh iL you can creaLe an exciLing menu-driven user
inLerace like Lhe ones you've seen in Lhe besL Windows applicaLions.
5. Click Lhe 1ype Here Lag, Lype CIock, and Lhen press FN1FR.
1he word Clccl
Here Lags appear, wiLh which you can creaLe submenu iLems below Lhe new Clock
menu or addiLional menu LiLles. 1he submenu iLem is currenLly selecLed.
6. 1ype Date Lo creaLe a DaLe command or Lhe Clock menu, and Lhen press FN1FR.
visual SLudio adds Lhe DaLe command Lo Lhe menu and selecLs Lhe nexL submenu iLem.
7. 1ype Time Lo creaLe a 1ime command or Lhe menu, and Lhen press FN1FR.
ou now have a Clock menu wiLh Lwo menu commands, DaLe and 1ime. ou could
or Lhis example program. our orm looks like Lhe one shown here.
8. Click Lhe orm Lo close Lhe Menu Designer.
1he Menu Designer closes, and your orm opens in Lhe lDF wiLh a new Clock menu.
ou're ready Lo sLarL cusLomizing Lhe menu now.
Adding Access Keys to Menu Commands
WiLh mosL applicaLions, you can access and execuLe menu commands by using Lhe
keyboard. ln visual SLudio, or example, you can open Lhe File menu by pressing Lhe AL1
key and Lhen pressing Lhe F key. Once Lhe File menu is open, you can open a projecL by
pressing Lhe P key. 1he key LhaL you press in addiLion Lo Lhe AL1 key and Lhe key LhaL you
l00 Part I Gettng Started wth Mcrosoft VsuaI asc 20l0
press Lo execuLe a command in an open menu are called cccess leys. ou can idenLiy
Lhe access key o a menu iLem because iL's eiLher underlined, or, in some Windows 7
applicaLions, iL appears in a small, handy box on Lhe menu.
visual SLudio makes iL easy Lo provide access key supporL. 1o add an access key Lo a menu
iLem, acLivaLe Lhe Menu Designer, and Lhen Lype an ampersand (&) beore Lhe appropriaLe
leLLer in Lhe menu name. When you open Lhe menu aL run Lime (when Lhe program is
running), your program auLomaLically supporLs Lhe access key.
Menu Conventions
8y convenLion, each menu LiLle and menu command in a Windows applicaLion has
an iniLial capiLal leLLer.
and Help is usually Lhe lasL. OLher common menu names are view, FormaL, and Window.
No maLLer whaL menus and commands you use in your applicaLions, Lake care Lo be
clear and consisLenL wiLh Lhem. Menus and commands should be easy Lo use and should
have as much in common as possible wiLh Lhose in oLher Windows-based applicaLions.
As you creaLe menu iLems, use Lhe ollowing guidelines.
.
Assign each menu iLem an access key.
possible, or Lhe access key LhaL is commonly assigned (such as x or FxiL).
Menu iLems aL Lhe same level musL have a unique access key.
l a command is used as an on/o Loggle, place a check mark Lo Lhe leL o
Lhe iLem when iL's acLive. ou can add a check mark by seLLing Lhe ChecleJ
properLy o Lhe menu command Lo 1rue in Lhe ProperLies window.
Place an ellipsis ( . . . ) aLer a menu command LhaL requires Lhe user Lo enLer
more inormaLion beore Lhe command can be execuLed. 1he ellipsis indicaLes
LhaL you'll open a dialog box i Lhe user selecLs Lhis iLem.
Note 8y deaulL, mosL versions o Windows don'L display Lhe underline or small box or access
. ln Windows XP, you can Lurn o
Lhis opLion by using Lhe FecLs buLLon on Lhe Appearance Lab o Lhe Display ProperLies conLrol
panel. ln Windows visLa and Windows 7, you can Lurn o Lhis opLion by clicking Lhe Appearance
And PersonalizaLion opLion in ConLrol Panel, clicking Fase O Access CenLer, clicking Make 1he
Keyboard Fasier 1o Use, and Lhen selecLing Underline Keyboard ShorLcuLs And Access Keys.
NoLe, however, LhaL in some applicaLions running under Windows 7 (such as visual SLudio 200
acLivaLe Lhem.
l04 Part I Gettng Started wth Mcrosoft VsuaI asc 20l0
MenuStri conLrol is relaLed Lo Lhe 1cclStri conLrol. (We'll see urLher examples o LhaL
laLer in Lhis chapLer.) 1he _Clicl synLax means LhaL Lhis is Lhe evenL procedure LhaL runs
when a user clicks Lhe menu iLem.
We'll keep Lhis menu name or now, buL i you wanLed Lo creaLe your own inLernal
names or menu objecLs, you could selecL Lhe objecL, open Lhe ProperLies window,
and change Lhe Ncme properLy. AlLhough l won'L boLher wiLh LhaL exLra sLep in Lhis
chapLer, laLer in Lhe book you'll pracLice renaming objecLs in your program Lo conorm
more readily Lo proessional programming pracLices.
3. 1ype Lhe ollowing program sLaLemenL.
Label 1. Text = Ti meSt r i ng
1his program sLaLemenL displays Lhe currenL Lime (rom Lhe sysLem clock) in Lhe 1ext
properLy o Lhe lcbel1 objecL, replacing Lhe previous lcbel1 LexL (i any). 1imeStrin
is a properLy LhaL conLains Lhe currenL Lime ormaLLed or display or prinLing. ou can
use 1imeStrin aL any Lime in your programs Lo display Lhe Lime accuraLely down Lo
Lhe second. (1imeStrin is essenLially a replacemenL or Lhe older MicrosoL visual 8asic
1lMl$ sLaLemenL.)
Note 1he visual 8asic 1imeStrin properLy reLurns Lhe currenL sysLem Lime. ou can seL
Lhe sysLem Lime by using Lhe Clock, Language, and Region caLegory in Lhe ConLrol Panel
in Windows visLa or Windows 7.
4. Press FN1FR.
visual 8asic inLerpreLs Lhe line and adjusLs capiLalizaLion and spacing, i necessary.
(visual 8asic checks each line or synLax errors as you enLer iL.)
1p ou can enLer a line by pressing FN1FR or FSC. ou can also press Lhe UP ARROW or
DOWN ARROW key Lo enLer a line i you don'L wanL Lhe exLra blank space (carriage reLurn)
in Lhe Code FdiLor.
5. Click Lhe view Designer buLLon in SoluLion Fxplorer, and Lhen double-click Lhe DaLe
command on Lhe Clock menu.
1he Dcte1cclStriMenultem_Clicl evenL procedure appears in Lhe Code FdiLor.
1his evenL procedure is execuLed when Lhe user clicks Lhe DaLe command on Lhe
Clock menu.
6. 1ype Lhe ollowing program sLaLemenL.
Label 1. Text = Dat eSt r i ng
l06 Part I Gettng Started wth Mcrosoft VsuaI asc 20l0
3. Click Lhe 1ime command.
1he currenL sysLem Lime appears in Lhe label box, as shown here.
Now you'll Lry displaying Lhe currenL daLe by using Lhe access keys on Lhe menu.
4. Press and release Lhe AL1 key, and Lhen press Lhe C key.
.
5. Press Lhe D key Lo display Lhe currenL daLe.
1he currenL daLe appears in Lhe label box. However, i Lhe box is noL big enough,
Lhe daLe mighL be LruncaLed. l Lhis happens, sLop Lhe program, resize Lhe label objecL,
and Lry iL again.
6.
Lo sLop Lhe program.
CongraLulaLions! ou've creaLed a working program LhaL uses menus and access keys. ln Lhe
nexL exercise, you'll learn how Lo use Loolbars.
System CIock Properties and Methods
ou can use various properLies and meLhods Lo reLrieve chronological values rom Lhe
sysLem clock. ou can use Lhese values Lo creaLe cusLom calendars, clocks, and alarms
in your programs. 1able 4- lisLs Lhe mosL useul sysLem clock properLies and meLhods.
For more inormaLion, check Lhe Lopics "DaLes and 1imes Summary" and "DaLeAnd1ime
Class" in Lhe visual SLudio Help documenLaLion.
l08 Part I Gettng Started wth Mcrosoft VsuaI asc 20l0
2. Click Lhe Liny smarL Lag in Lhe upper-righL corner o Lhe new Loolbar.
1he smarL Lag poinLs Lo Lhe righL and looks similar Lo Lhe smarL Lag we saw in Lhe
Picture3cx conLrol in ChapLer 2, "WriLing our FirsL Program." When you click Lhe
Lag, a 1oolSLrip 1asks window opens LhaL includes a ew o Lhe mosL common Loolbar
Lasks and properLies, as shown here.
commands.
3. Click lnserL SLandard lLems.
visual SLudio adds a collecLion o sLandard Loolbar buLLons Lo Lhe Loolbar, including
New, Open, Save, PrinL, CuL, Copy, PasLe, and Help. our orm looks similar Lo Lhe
ollowing screen shoL.
lL is noL necessary or you Lo sLarL wiLh a ull Loolbar o buLLons as l have done here-
l'm merely demonsLraLing one o Lhe useul "auLomaLic" eaLures o visual SLudio 200.
ou could also creaLe Lhe buLLons on your Loolbar one by one using Lhe 1cclStri
ediLing commands, as l'll demonsLraLe shorLly. 8uL or many applicaLions, clicking
lnserL SLandard lLems is a Lime-saving eaLure. Remember, however, LhaL alLhough
Lhese Loolbar buLLons look proessional, Lhey are noL uncLional yeL. 1hey need evenL
procedures Lo make Lhem work.
Chapter 4 Workng wth Menus, 1ooIbars, and DaIog oxes l09
4. Click Lhe Add 1oolSLrip8uLLon arrow on Lhe righL side o Lhe new Loolbar, and Lhen click
Lhe 8uLLon iLem.
Add 1oolSLrip8uLLon adds more iLems Lo your Loolbar, such as buLLons, labels, spliL
buLLons, LexL boxes, combo boxes, and oLher useul Ul elemenLs. ou've now creaLed
a cusLom Loolbar buLLon, by deaulL, iL conLains a picLure o a mounLain and a sun.
5. Widen Lhe orm window Lo ensure LhaL you can see all Lhe Lool sLrip iLems.
6. RighL-click Lhe new buLLon, poinL Lo DisplaySLyle, and click lmageAnd1exL.
our new buLLon displays boLh LexL and a graphical image on Lhe Loolbar. visual SLudio
names your new buLLon 1cclStri3uttcn1 in Lhe program, and Lhis name appears by
deaulL on Lhe Loolbar. l necessary, widen Lhe orm window Lo see Lhe new buLLon,
because iL conLains Lhe deaulL LexL value 1oolSLrip8uLLon.
7. SelecL Lhe 1cclStri3uttcn1 objecL.
8. ln Lhe ProperLies window, change Lhe 1cclStri3uttcn1 objecL's 1ext properLy Lo Color,
which is Lhe name o your buLLon on Lhe orm, and Lhen press FN1FR.
1he Color buLLon appears on Lhe Loolbar. ou'll use Lhis buLLon laLer in Lhe program
Lo change Lhe color o LexL on Lhe orm. Now inserL a cusLom biLmap or your buLLon.
9. RighL-click Lhe Color buLLon, and Lhen click Lhe SeL lmage command.
1he SelecL Resource dialog box appears.
l0. Click Local Resource (i iL is noL already selecLed), and Lhen click Lhe lmporL buLLon.
ll. 8rowse Lo Lhe C.\vb0sbs\Chap04 older, click Lhe Color8uLLon.
l creaLed or you, click Open, and Lhen click OK.
visual SLudio loads Lhe pink, blue, and yellow painL icon inLo Lhe Color buLLon, as
shown in Lhe ollowing screen shoL.
Chapter 4 Workng wth Menus, 1ooIbars, and DaIog oxes ll5
l. Click Lhe SLarL Debugging buLLon on Lhe SLandard Loolbar.
1he program runs, and Lhe Clock menu and Lhe Loolbar appear aL Lhe Lop o Lhe screen.
2. On Lhe orm's Loolbar, click Open.
1he Open dialog box opens. lL looks greaL, doesn'L iL (ln oLher words, iL looks jusL like
a regular Windows applicaLion.) NoLice Lhe 8iLmaps (*.bmp) enLry in Lhe dialog box. ou
OpenFi l eDi al og1. Fi l t er = "Bi t maps ( *. bmp) | *. bmp"
in Lhe Oen1cclStri3uttcn_Clicl evenL procedure.
8iLmaps (*. . 1he second
parL-*.
dialog box.
3. Open a older on your sysLem LhaL conLains biLmap images. l'm using Lhe color Loolbar
buLLon l've used in Lhis chapLer (locaLed in C.\vb0sbs\Chap04), buL you can display any
. .
4. .
A picLure o Lhe biLmap appears in Lhe picLure box. My orm looks like Lhis.
Now you'll pracLice using Lhe Clock menu.
5. On Lhe Clock menu, click Lhe 1ime command.
1he currenL Lime appears in Lhe label box.
ll6 Part I Gettng Started wth Mcrosoft VsuaI asc 20l0
6. Click Lhe Color buLLon on Lhe Loolbar.
1he Color dialog box opens, as shown here.
1he Color dialog box conLains elemenLs LhaL you can use Lo change Lhe color o Lhe
clock LexL in your program. 1he currenL color seLLing, black, is selecLed.
7. Click one o Lhe blue color boxes, and Lhen click OK.
1he Color dialog box closes, and Lhe color o Lhe LexL in Lhe clock label changes Lo
blue. (1haL's noL visible in Lhis book, alas, buL you'll see iL on Lhe screen.)
8. On Lhe Clock menu, click Lhe DaLe command.
1he currenL daLe is displayed in blue Lype. Now LhaL Lhe LexL color has been seL in Lhe
label, iL remains blue unLil Lhe color is changed again or Lhe program closes.
ll8 Part I Gettng Started wth Mcrosoft VsuaI asc 20l0
3. Open Lhe ProperLies window, click Lhe Shcrtcutkeys properLy in Lhe Misc caLegory,
and Lhen click Lhe arrow in Lhe second column.
A pop-up menu appears LhaL helps you assign Lhe shorLcuL key.
4. SelecL Lhe CLrl check box, click Lhe Key lisL box, and selecL Lhe leLLer 1 in Lhe
alphabeLical lisL.
1he ProperLies window looks like Lhis.
1p visual 8asic normally displays Lhe shorLcuL key combinaLion in Lhe menu when you
run Lhe program, Lo give users a hinL abouL which keys Lo press. 1o hide shorLcuL key
combinaLions rom Lhe user (i you're running ouL o space), seL Lhe ShcwShcrtcutkeys
properLy Lo False. 1he shorLcuL key sLill works, buL users won'L see a visual reminder or iL.
ou can also seL whaL will be displayed wiLhin Lhe program as a shorLcuL key by seLLing Lhe
ShcrtcutkeyDislcyStrin properLy.
5. Click Lhe DaLe command, and Lhen change iLs Shcrtcutkeys properLy seLLing Lo CLrl-D.
Now you'll run Lhe program and Lry Lhe shorLcuL keys.
6. Click Lhe orm Lo close Lhe Clock menu.
7. Click Lhe SLarL Debugging buLLon on Lhe SLandard Loolbar.
8. Press C1RL-D Lo run Lhe DaLe command.
1he currenL daLe appears in Lhe program.
9. Press C1RL-1 Lo run Lhe 1ime command.
1he currenL Lime appears in Lhe program.
l2l
ParL ll
Programmng fundamentaIs
In ths part:
Chapter 5: VsuaI asc VarabIes and formuIas, and the .Nf1 framework . . . . l23
Chapter 6: Usng Decson Structures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . l59
Chapter 7: Usng Loops and 1mers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . l8l
Chapter 8: Debuggng VsuaI asc Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
Chapter 9: 1rappng frrors by Usng Structured frror HandIng. . . . . . . . . . . . . 227
Chapter l0: Creatng ModuIes and Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . 247
Chapter ll: Usng Arrays to Manage Numerc and Strng Data . . . . . . . . . . . . . 273
Chapter l2: Workng wth CoIIectons. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
Chapter l3: fxpIorng 1ext fIes and Strng Processng . . . . . . . . . . . . . . . . . . . . 3l3
ln ParL l, "CeLLing SLarLed wiLh visual 8asic 200," you learned how Lo creaLe Lhe user
inLerace o a MicrosoL visual 8asic 200 program and how Lo build and run a program
in Lhe MicrosoL visual SLudio 200 developmenL environmenL. ln Lhe nine chapLers in ParL ll,
"Programming FundamenLals," you'll learn more abouL visual 8asic program code-Lhe
sLaLemenLs and keywords LhaL orm Lhe core o a visual 8asic program. ou'll learn how Lo
manage inormaLion wiLhin programs and conLrol how your code is execuLed, and you'll
learn . ou'll
also learn how Lo debug your programs and handle run-Lime errors i Lhey occur. ALer you
compleLe ParL ll, you'll be ready or more advanced Lopics, such as cusLomizing Lhe user
inLerace, daLabase programming, and Web programming.
l23
ChapLer 5
VsuaI asc VarabIes and formuIas,
and the .Nf1 framework
After compIetng ths chapter, you wII be abIe to:
Use variables Lo sLore daLa in your programs.
CeL inpuL by using Lhe lnut3cx uncLion.
Display messages by using Lhe Ms3cx uncLion.
Work wiLh dierenL daLa Lypes.
Use variables and operaLors Lo manipulaLe daLa.
Use meLhods in Lhe .NF1 Framework.
Use ariLhmeLic operaLors and uncLions in ormulas.
ln Lhis chapLer, you'll learn how Lo use variables and consLanLs Lo sLore daLa Lemporarily in
your program, and how Lo use Lhe lnut3cx and Ms3cx uncLions Lo gaLher and presenL
inormaLion by using dialog boxes. ou'll also learn how Lo use uncLions and ormulas
Lo perorm calculaLions, and how Lo use ariLhmeLic operaLors Lo perorm Lasks such as
mulLiplicaLion and sLring concaLenaLion. Finally, you'll learn how Lo Lap inLo Lhe powerul
classes and meLhods o MicrosoL .NF1 Framework 4 Lo perorm maLhemaLical calculaLions
and oLher useul work.
The Anatomy of a VisuaI Basic Program Statement
As you learned in ChapLer 2, "WriLing our FirsL Program," a line o code in a MicrosoL
visual 8asic program is called a rcrcm stctement. A program sLaLemenL is any
combinaLion o visual 8asic keywords, properLies, objecL names, variables, numbers, special
symbols, and oLher values LhaL collecLively creaLe a valid insLrucLion recognized by Lhe
visual 8asic compiler. A compleLe program sLaLemenL can be a simple keyword, such as
End
which halLs Lhe execuLion o a visual 8asic program, or iL can be a combinaLion o elemenLs,
such as Lhe ollowing sLaLemenL, which uses Lhe 1imeStrin properLy Lo assign Lhe currenL
sysLem Lime Lo Lhe 1ext properLy o Lhe lcbel1 objecL.
Label 1. Text = Ti meSt r i ng
l24 Part II Programmng fundamentaIs
1he rules o consLrucLion LhaL musL be used when you build a programming sLaLemenL
are called stctement syntcx. visual 8asic shares many o iLs synLax rules wiLh Lhe oLher
developmenL producLs in visual SLudio, as well as earlier versions o Lhe 8ASlC programming
language. 1he Lrick Lo wriLing good program sLaLemenLs is learning Lhe synLax o Lhe mosL
useul elemenLs in a programming language and Lhen using Lhose elemenLs correcLly Lo
process Lhe daLa in your program. ForLunaLely, visual 8asic does a loL o Lhe LoughesL work
or you, so Lhe Lime you spend wriLing program code is relaLively shorL, and you can reuse
Lhe resulLs in uLure programs. 1he visual SLudio lDF also poinLs ouL poLenLial synLax errors
.
ln Lhis chapLer and Lhe ollowing chapLers, you'll learn Lhe mosL imporLanL visual 8asic
keywords and program sLaLemenLs, as well as many o Lhe objecLs, properLies, and meLhods
provided by visual SLudio conLrols and Lhe .NF1 Framework.
and objecLs complemenL nicely Lhe programming skills you've already learned and will help
you wriLe powerul programs in Lhe uLure.
criLical eaLures o nearly every program.
Using VariabIes to Store lnformation
A vcricble is a Lemporary sLorage locaLion or daLa in your program. ou can use one
or many variables in your code, and Lhey can conLain words, numbers, daLes, properLies, or
oLher values. 8y using variables, you can assign a shorL and easy-Lo-remember name Lo each
piece o daLa you plan Lo work wiLh. variables can hold inormaLion enLered by Lhe user aL
orm. ln shorL, variables are handy conLainers LhaL you can use Lo sLore and Lrack almosL any
Lype o inormaLion.
Using variables in a visual 8asic program requires some planning. 8eore you can use
a variable, you musL seL aside memory in Lhe compuLer or Lhe variable's use. 1his process is
a liLLle like reserving a seaL aL a LheaLer or a baseball game. l'll cover Lhe process o making
reservaLions or, or Jeclcrin, a variable in Lhe nexL secLion.
Setting Aside Space for VariabIes. The Dim Statement
Since Lhe release o visual 8asic in 2002, iL has been necessary or visual 8asic programmers
Lo expliciLly declare variables beore using Lhem. 1his was a change rom visual 8asic 6
and earlier versions o visual 8asic, where (under cerLain circumsLances) you could declare
variables impliciLly-in oLher words, simply by using Lhem and wiLhouL having Lo include a
Dim sLaLemenL.
variable conusion and misspelled variable names, which inLroduced poLenLial bugs inLo Lhe
code LhaL mighL or mighL noL be discovered laLer.
Chapter 5 VsuaI asc VarabIes and formuIas, and the .Nf1 framework l25
ln visual 8asic 2008, a biL o Lhe pasL reLurned in Lhe area o variable declaraLion. lL became
possible once again Lo declare a variable impliciLly. l don'L recommend Lhis or mosL uses,
however, so l won'L discuss Lhis eaLure unLil you learn Lhe recommended programming
pracLice, which experienced programmers ar and wide will praise you or adopLing.
1o declare a variable in visual 8asic 200, Lype Lhe variable name aLer Lhe Dim sLaLemenL.
(Dim sLands or Jimensicn.) 1his declaraLion reserves room in memory or Lhe variable when
Lhe program runs and leLs visual 8asic know whaL Lype o daLa iL should expecL Lo see laLer.
AlLhough Lhis declaraLion can be done aL any place in Lhe program code (as long as Lhe
declaraLion happens beore Lhe variable is used), mosL programmers declare variables in
one place aL Lhe Lop o Lheir evenL procedures or code modules.
For example, Lhe ollowing sLaLemenL creaLes space or a variable named lcstNcme LhaL will
hold a LexLual, or strin, value.
Di mLast Name As St r i ng
NoLe LhaL in addiLion Lo idenLiying Lhe variable by name, l've used Lhe As keyword Lo give
Lhe Strin. (ou'll learn
abouL oLher daLa Lypes laLer in Lhis chapLer.) A sLring variable conLains LexLual inormaLion. words,
leLLers, symbols-even numbers.
.
Why do you need Lo declare variables visual 8asic wanLs you Lo idenLiy Lhe name and Lhe
Lype o your variables in advance so LhaL Lhe compiler can seL aside Lhe memory Lhe program
will need Lo sLore and process Lhe inormaLion held in Lhe variables. Memory managemenL
mighL noL seem like a big deal Lo you (aLer all, modern personal compuLers have loLs
o RAM and gigabyLes o ree hard disk space), buL in some programs, memory can be
consumed quickly, and iL's a good pracLice Lo Lake memory allocaLion seriously even as you
. As you'll soon see, dierenL Lypes o variables have
dierenL space requiremenLs and size limiLaLions.
Note Strin or lnteer)
aren'L required-inormaLion is simply held by using a generic (and memory hungry) daLa Lype
called vcricnt, which can hold daLa o any size or ormaL. varianLs are noL supporLed in visual
8asic 200, however. AlLhough Lhey are handy or beginning programmers, Lheir design makes
easily-someLimes causing unexpecLed resulLs. As you'll learn laLer, however, you can sLill sLore
inormaLion in generic conLainers called Object, which are likewise general-purpose in uncLion
.
ALer you declare a variable, you're ree Lo assign inormaLion Lo iL in your code by using
Lhe assignmenL operaLor (=). For example, Lhe ollowing program sLaLemenL assigns Lhe lasL
name "Jeerson" Lo Lhe lcstNcme variable.
Last Name = " J ef f er son"
l26 Part II Programmng fundamentaIs
NoLe LhaL l was careul Lo assign a LexLual value Lo Lhe lcstNcme variable because iLs
daLa Lype is Strin. l can also assign values wiLh spaces, symbols, or numbers Lo Lhe variable,
such as
Last Name = " 1313 Mocki ngbi r d Lane"
buL Lhe variable is sLill considered a sLring value. 1he number porLion could be used in
a
by using one o a handul o conversion uncLions LhaL l'll discuss in ChapLer 8, "Fxploring
1exL Files and SLring Processsing."
ALer Lhe lcstNcme variable is assigned a value, iL can be used in place o Lhe name
"Jeerson" in your code. For example, Lhe assignmenL sLaLemenL
Label 1. Text = Last Name
displays "Jeerson" in Lhe label named lcbel1 on a orm.
ImpIct VarabIe DecIaraton
l you really wanL Lo declare variables "Lhe old way" in visual 8asic 200-LhaL is, wiLhouL
expliciLly declaring Lhem by using Lhe Dim sLaLemenL-you can place Lhe Oticn lxlicit
Ojj sLaLemenL aL Lhe very Lop o your orm's or module's program code (beore any evenL
procedures), and iL will Lurn o Lhe visual 8asic deaulL requiremenL LhaL variables be declared
beore Lhey're used. As l menLioned earlier, l don'L recommend Lhis sLaLemenL as a permanenL
programs Lo visual 8asic 200.
AnoLher possibiliLy is Lo use Lhe Oticn lnjer sLaLemenL, which was added Lo visual
8asic 2008. l Oticn lnjer is seL Lo On, visual 8asic will deduce or injer Lhe Lype o a variable
by examining Lhe iniLial assignmenL you make. 1his allows you Lo declare variables wiLhouL
.
For example, Lhe expression
Di mat t endance = 100
will declare Lhe variable named cttenJcnce as an lnteer, because 00 is an inLeger
expression. ln oLher words, wiLh Oticn lnjer seL Lo On, iL is Lhe same as Lyping
Di mat t endance As I nt eger = 100
Likewise, Lhe expression
Di maddr ess = " 1012 Dai sy Lane"
will declare Lhe variable address as Lype Strin, because iLs iniLial assignmenL was o Lype
Strin. l you seL Oticn lnjer Lo O, however, visual 8asic will declare Lhe variable as Lype
Object .
l28 Part II Programmng fundamentaIs
1he orm conLains Lwo labels and Lwo buLLons. ou'll use variables Lo display
inormaLion in each o Lhe labels.
Note 1he label objecLs look like boxes because l seL Lheir 3crJerStyle properLies Lo Fixed8D.
5. Double-click Lhe Show buLLon.
1he 3uttcn1_Clicl evenL procedure appears in Lhe Code FdiLor.
6. 1ype Lhe ollowing program sLaLemenLs Lo declare and use Lhe lcstNcme variable.
Di mLast Name As St r i ng
Last Name = " Lut her "
Label 1. Text = Last Name
Last Name = " Bodenst ei n von Kar l st adt "
Label 2. Text = Last Name
1he program sLaLemenLs are arranged in Lhree groups.
Lhe lcstNcme variable by using Lhe Dim sLaLemenL and Lhe Strin Lype. ALer you
Lype Lhis line, visual SLudio places a green jagged line under Lhe lcstNcme variable,
because iL has been declared buL noL used in Lhe program. 1here is noLhing wrong
here-visual SLudio is jusL reminding you LhaL a new variable has been creaLed and is
waiLing Lo be used.
1p program, iL
could be a sign LhaL you misspelled a variable name somewhere wiLhin your code.
1he second and Lhird lines assign Lhe name "LuLher" Lo Lhe lcstNcme variable and
. 1his example demonsLraLes
one o Lhe mosL common uses o variables in a program-Lranserring inormaLion
Lo a properLy. As you have seen beore, all sLring values assigned Lo variables are
displayed in red Lype.
1he ourLh line assigns Lhe name "8odensLein von KarlsLadL" Lo Lhe lcstNcme variable
(in oLher words, iL changes Lhe conLenLs o Lhe variable). NoLice LhaL Lhe second sLring
. When you assign LexL sLrings
Lo variables, or use Lhem in oLher places, you need Lo enclose Lhe LexL wiLhin quoLaLion
marks. (ou don'L need Lo do Lhis wiLh numbers.)
Finally, keep in mind anoLher imporLanL characLerisLic o Lhe variables being declared
in Lhis evenL procedure-Lhey mainLain Lheir scce, or hold Lheir value, only wiLhin Lhe
evenL procedure you're using Lhem in. LaLer in Lhis chapLer, you'll learn how Lo declare
variables so LhaL Lhey can be used in any o your orm's evenL procedures.
Chapter 5 VsuaI asc VarabIes and formuIas, and the .Nf1 framework l29
7. Click Lhe Form.vb [Design] Lab Lo display Lhe orm again.
8. Double-click Lhe uiL buLLon.
1he 3uttcn2_Clicl evenL procedure appears in Lhe Code FdiLor.
9. 1ype Lhe ollowing program sLaLemenL Lo sLop Lhe program.
End
our screen looks like Lhis.
l0. Click Lhe Save All buLLon on Lhe SLandard Loolbar Lo save your changes.
ll. Click Lhe SLarL Debugging buLLon on Lhe SLandard Loolbar Lo run Lhe program.
1he program runs in Lhe lDF.
l2. Click Lhe Show buLLon.
1he program declares Lhe variable, assigns Lwo values Lo iL, and copies each value Lo
Lhe appropriaLe label on Lhe orm. 1he program produces Lhe ouLpuL shown in Lhe
ollowing screen shoL.
l30 Part II Programmng fundamentaIs
l3. Click Lhe uiL buLLon Lo sLop Lhe program.
1he program sLops, and Lhe developmenL environmenL reLurns.
VariabIe Naming Conventions
Naming variables can be a liLLle Lricky because you need Lo use names LhaL are shorL
buL inLuiLive and easy Lo remember. 1o avoid conusion, use Lhe ollowing convenLions
when naming variables.
8egin each variable name wiLh a leLLer or underscore. 1his is a visual 8asic
requiremenL. variable names can conLain only leLLers, underscores, and
numbers.
AlLhough variable names can be virLually any lengLh, Lry Lo keep Lhem under
88 characLers Lo make Lhem easier Lo read. (variable names were limiLed Lo
255 characLers in visual 8asic 6, buL LhaL's no longer a consLrainL.)
Make your variable names descripLive by combining one or more words when
iL makes sense Lo do so. For example, Lhe variable name Scles1cxRcte is much
clearer Lhan 1cx or Rcte.
Use a combinaLion o uppercase and lowercase characLers and numbers.
An
a variable, or example, DcteOj3irth. However, some programmers preer Lo use
disLinguish variable names rom uncLions and module names, which usually
begin wiLh uppercase leLLers. Fxamples o camel casing include JcteOj3irth,
emlcyeeNcme, and counLer.
Don'L use visual 8asic keywords, objecLs, or properLies as variable names. l
you do, you'll geL an error when you Lry Lo run your program.
OpLionally, you can begin each variable name wiLh a Lwo-characLer or
Lhree-characLer abbreviaLion corresponding Lo Lhe Lype o daLa LhaL's sLored
in Lhe variable. For example, use sLrName Lo show LhaL Lhe Name variable
conLains sLring daLa. AlLhough you don'L need Lo worry Loo much abouL Lhis
deLail now, you should make a noLe o Lhis convenLion or laLer-you'll see iL
in parLs o Lhe visual SLudio Help documenLaLion and in some o Lhe advanced
books abouL visual 8asic programming. (1his convenLion and abbreviaLion
scheme was originally creaLed by MicrosoL DisLinguished Fngineer Charles
Simonyi and is someLimes called Lhe Hungarian Naming ConvenLion.)
Using a VariabIe to Store lnput
One pracLical use or a variable is Lo Lemporarily hold inormaLion LhaL was enLered by Lhe
user. AlLhough you can oLen use an objecL such as a lisL box or a LexL box Lo gaLher Lhis
inormaLion, aL Limes you mighL wanL Lo deal direcLly wiLh Lhe user and save Lhe inpuL in
l32 Part II Programmng fundamentaIs
ALer lnut3cx has reLurned a LexL sLring Lo Lhe program, Lhe ourLh sLaLemenL in Lhe
procedure places Lhe user's name in Lhe 1ext properLy o Lhe lcbel1 objecL, which
displays iL on Lhe orm.
6. Save your changes.
7. Click Lhe SLarL Debugging buLLon on Lhe SLandard Loolbar Lo run Lhe program.
1he program runs in Lhe lDF.
8. Click Lhe lnpuL 8ox buLLon.
visual 8asic execuLes Lhe 3uttcn1_Clicl evenL procedure, and Lhe lnpuL 8ox dialog box
opens on your screen, as shown here.
9. 1ype your ull name, and Lhen click OK.
1he lnut3cx uncLion reLurns your name Lo Lhe program and places iL in Lhe lullNcme
variable. 1he program Lhen uses Lhe variable Lo display your name on Lhe orm, as
shown here.
Use Lhe lnut3cx uncLion in your programs anyLime you wanL Lo prompL Lhe user or
inormaLion. ou can use Lhis uncLion in combinaLion wiLh Lhe oLher inpuL conLrols Lo
. ln Lhe nexL exercise, you'll learn
how Lo use a similar uncLion Lo display LexL in a dialog box.
l0. Click Lhe uiL buLLon on Lhe orm Lo sLop Lhe program.
1he program sLops, and Lhe developmenL environmenL reappears.
Chapter 5 VsuaI asc VarabIes and formuIas, and the .Nf1 framework l33
what ls a lunction?
lnut3cx is a special visual 8asic keyword known as a juncticn. A uncLion is a
sLaLemenL LhaL perorms meaningul work (such as prompLing Lhe user or inormaLion
or calculaLing an equaLion) and Lhen reLurns a resulL Lo Lhe program. 1he value
reLurned by a uncLion can be assigned Lo a variable, as iL was in Lhe lnpuL 8ox
program, or iL can be assigned Lo a properLy or anoLher sLaLemenL or uncLion. visual
. For example,
Lhe lnut3cx uncLion you jusL execuLed used Lhe Prcmt variable Lo display dialog
box insLrucLions or Lhe user. When a uncLion uses more Lhan one argumenL, commas
separaLe Lhe argumenLs, and Lhe whole group o argumenLs is enclosed in parenLheses.
1he ollowing sLaLemenL shows a uncLion call LhaL has Lwo argumenLs.
Ful l Name = I nput Box( Pr ompt , Ti t l e)
NoLice LhaL l'm using iLalic in Lhis synLax descripLion Lo indicaLe LhaL cerLain iLems are
placeholders or inormaLion you speciy.
and in Lhe visual SLudio Help documenLaLion.
Using a VariabIe for Output
ou can display Lhe conLenLs o a variable by assigning Lhe variable Lo a properLy (such as
Lhe 1ext properLy o a label objecL) or by passing Lhe variable as an argumenL Lo a dialog box
uncLion. One useul dialog box uncLion or displaying ouLpuL is Lhe Ms3cx uncLion. When
you call Lhe Ms3cx uncLion, iL displays a dialog box, someLimes called a messce bcx, wiLh
various opLions LhaL you can speciy. Like lnut3cx, iL Lakes one or more argumenLs as inpuL,
and Lhe resulLs o Lhe uncLion call can be assigned Lo a variable. 1he synLax or Lhe Ms3cx
uncLion is
But t onCl i cked = MsgBox( Pr ompt , But t ons, Ti t l e)
where Prcmt is Lhe LexL Lo be displayed in Lhe message box, 3uttcns is a number LhaL
1itle is Lhe
LexL displayed in Lhe message box LiLle bar. 1he variable 3uttcnClicleJ is assigned Lhe resulL
reLurned by Lhe uncLion, which indicaLes which buLLon Lhe user clicked in Lhe dialog box.
l you're jusL displaying a message using Lhe Ms3cx uncLion, Lhe 3uttcnClicleJ variable,
Lhe assignmenL operaLor (=), Lhe 3uttcns argumenL, and Lhe 1itle argumenL are opLional.
ou'll be using Lhe 1itle argumenL, buL you won'L be using Lhe oLhers in Lhe ollowing
exercise, or more inormaLion abouL Lhem (including Lhe dierenL buLLons you can include in
Ms3cx and a ew more opLions), search or Lhe Lopic "Msg8ox MeLhod" in Lhe visual SLudio
Help documenLaLion. As Lhe arLicle noLes, Lhe Ms3cx uncLion is someLimes also reerred Lo
as a methcJ, Micrcscjt.visucl3csic namespace.
Chapter 5 VsuaI asc VarabIes and formuIas, and the .Nf1 framework l35
5. Click Lhe SLarL Debugging buLLon on Lhe SLandard Loolbar.
6. Click Lhe lnpuL 8ox buLLon, Lype your name in Lhe inpuL box, and
Lhen click OK.
visual 8asic sLores Lhe inpuL in Lhe program in Lhe lullNcme variable and Lhen displays
iL in a message box. ALer Lyping Lhe name Wclter Hcr in Lhe inpuL box, l received Lhis
message box.
7. Click OK Lo close Lhe message box. 1hen click uiL Lo close Lhe program.
1he program closes, and Lhe developmenL environmenL reLurns.
1he Strin daLa Lype is useul or managing LexL in your programs, buL whaL abouL
numbers,
managemenL o all Lypes o daLa, visual 8asic provides several addiLional daLa Lypes
LhaL you can use or your variables. Many o Lhese are amiliar daLa Lypes rom
earlier versions o 8ASlC or visual 8asic, and some o Lhe daLa Lypes were inLroduced
in
64-biL compuLers.
1able 5- lisLs Lhe undamenLal (or elemenLary) daLa Lypes in visual 8asic. 1ypes preceded
by an S are designed or sineJ numbers, meaning LhaL Lhey can hold boLh posiLive and
negaLive values. 1ypes preceded by a U are unsineJ Jctc tyes, meaning LhaL Lhey cannoL
hold negaLive values. l your program needs Lo perorm a loL o calculaLions, you mighL
gain a perormance advanLage in your programs i you choose Lhe righL daLa Lype or your
variables-a size LhaL's neiLher Loo big nor Loo small. ln Lhe nexL exercise, you'll see how
several o Lhese daLa Lypes work.
Note variable sLorage size is measured in biLs. 1he amounL o space required Lo sLore
one sLandard (ASCll) keyboard characLer in memory is 8 biLs, which equals byLe.
l38 Part II Programmng fundamentaIs
6. Click Lhe Dcte Lype in Lhe lisL box.
1he daLe 8//968 appears in Lhe Sample DaLa box.
7. Click each daLa Lype in Lhe lisL box Lo see how visual 8asic displays iL in Lhe Sample
DaLa box.
8. Click Lhe uiL buLLon Lo sLop Lhe program.
Now you'll examine how Lhe undamenLal daLa Lypes are declared aL Lhe Lop o Lhe
orm and how Lhey're used in Lhe list3cx1_SelecteJlnJexChcneJ evenL procedure.
9. Double-click Lhe orm iLsel (noL any objecLs on Lhe orm), and enlarge Lhe Code FdiLor
Lo see more o Lhe program code.
1he Code FdiLor looks like Lhis.
Chapter 5 VsuaI asc VarabIes and formuIas, and the .Nf1 framework l39
Scroll Lo Lhe Lop o Lhe Code FdiLor Lo see Lhe dozen or so program sLaLemenLs l added
Lo declare variables in your program-one or each o Lhe undamenLal daLa Lypes
in visual 8asic. (l didn'L creaLe an example or Lhe S3yte, UShcrt, Ulnteer, and Ulcn
Lypes, because Lhey closely resemble Lheir signed or unsigned counLerparLs.) 8y placing
each Dim sLaLemenL here, aL Lhe Lop o Lhe orm's code iniLializaLion area, l'm ensuring
LhaL Lhe variables will be valid, or will have scce, or all o Lhe orm's evenL procedures.
1haL way, l can seL Lhe value o a variable in one evenL procedure and read iL in anoLher.
Normally, variables are valid only in Lhe evenL procedure in which Lhey're declared.
1o make Lhem valid across Lhe orm, you need Lo declare variables aL Lhe Lop o your
orm's code.
Note l've given each variable Lhe same name as l did in Lhe daLa Lypes Lable
earlier in Lhe chapLer so LhaL you can see Lhe examples l showed you in acLual
program code.
l0. Scroll down in Lhe Code FdiLor, and examine Lhe lcrm1_lccJ evenL procedure.
ou'll see Lhe ollowing sLaLemenLs, which add iLems Lo Lhe lisL box objecL in Lhe
program. (ou mighL remember Lhis synLax rom ChapLer 8, "Working wiLh 1oolbox
ConLrols"-l used some similar sLaLemenLs Lhere.)
ll. Scroll up and examine Lhe list3cx1_SelecteJlnJexChcneJ
evenL procedure.
l40 Part II Programmng fundamentaIs
1he list3cx1_SelecteJlnJexChcneJ evenL procedure processes Lhe selecLions you make
in Lhe lisL box and looks like Lhis.
1he hearL o Lhe evenL procedure is a Select Ccse decision sLrucLure. ln Lhe nexL chapLer,
we'll discuss how Lhis group o program sLaLemenLs selecLs one choice rom many.
For now, noLice how each secLion o Lhe Select Ccse block assigns a sample value Lo
one o Lhe undamenLal daLa Lype variables and Lhen assigns Lhe variable Lo Lhe 1ext
properLy o Lhe lcbel4 objecL on Lhe orm. l used code like Lhis in ChapLer 8 Lo process
lisL box choices, and you can use Lhese Lechniques Lo work wiLh lisL boxes and daLa
Lypes in your own programs.
Note l you have more Lhan one orm in your projecL, you need Lo declare variables in
a slighLly dierenL way (and place) Lo give Lhem scope LhroughouL your program (LhaL is, in
each orm LhaL your projecL conLains). 1he Lype o variable LhaL you'll declare is a public, or
procedures noL associaLed wiLh a parLicular orm. For inormaLion abouL creaLing public
variables in modules, see ChapLer 0, "CreaLing Modules and Procedures."
l2. Scroll Lhrough Lhe list3cx1_SelecteJlnJexChcneJ evenL procedure, and examine each
o Lhe variable assignmenLs closely.
1ry changing Lhe daLa in a ew o Lhe variable assignmenL sLaLemenLs and running Lhe
program again Lo see whaL Lhe daLa looks like. ln parLicular, you mighL Lry assigning
Chapter 5 VsuaI asc VarabIes and formuIas, and the .Nf1 framework l4l
values Lo variables LhaL are ouLside Lheir accepLed range, as shown in Lhe daLa Lypes
Lable presenLed earlier. l you make such an error, visual 8asic adds a jagged line below
Lhe incorrecL value in Lhe Code FdiLor, and Lhe program won'L run unLil you change
iL. 1o learn more abouL your misLake, you can poinL Lo Lhe jagged underlined value
and read a shorL LoolLip error message abouL Lhe problem.
1p 8y deaulL, a green jagged line indicaLes a warning, a red jagged line indicaLes
a synLax error, a blue jagged line indicaLes a compiler error, and a purple jagged line
indicaLes some oLher error.
l3. l you made any changes you wanL Lo save Lo disk, click Lhe Save All buLLon on Lhe
SLandard Loolbar.
visual 8asic also leLs you creaLe your own daLa Lypes. 1his eaLure is mosL useul
dierenL daLa caLegories. ou creaLe a (UD1) by using Lhe Structure
sLaLemenL, and you declare variables associaLed wiLh Lhe new Lype by using Lhe Dim
sLaLemenL. 8e aware LhaL Lhe Structure sLaLemenL cannoL be locaLed in an evenL
procedure-iL musL be locaLed aL Lhe Lop o Lhe orm along wiLh oLher variable
declaraLions, or in a code module.
lmlcyee LhaL can sLore Lhe name, daLe o birLh, and hire daLe associaLed wiLh a worker.
St r uct ur e Empl oyee
Di mName As St r i ng
Di mDat eOf Bi r t h As Dat e
Di mHi r eDat e As Dat e
End St r uct ur e
ALer you creaLe a daLa Lype, you can use iL in Lhe program code or Lhe orm's or
module's evenL procedures. 1he ollowing sLaLemenLs use Lhe new lmlcyee Lype.
1he PrcJuctMcncer, o Lhe lmlcyee Lype,
and Lhe second sLaLemenL assigns Lhe name "Frin M. Hagens" Lo Lhe Ncme componenL
o Lhe variable.
Di mPr oduct Manager As Empl oyee
Pr oduct Manager . Name = " Er i n M. Hagens"
1his looks a liLLle similar Lo seLLing a properLy, doesn'L iL visual 8asic uses Lhe same
noLaLion or Lhe relaLionship beLween objecLs and properLies as iL uses or Lhe
.
l46 Part II Programmng fundamentaIs
our screen looks similar Lo Lhis.
objecLs inLo Lhe lirstNum and SeccnJNum variables.
' Assi gn t ext box val ues t o var i abl es
Fi r st Num= Text Box1. Text
SecondNum= Text Box2. Text
1he 1ext3cx conLrol handles Lhe Lranser wiLh Lhe 1ext properLy-a properLy LhaL accepLs
LexL enLered by Lhe user and makes iL available or use in Lhe program. l'll make requenL
use o Lhe 1ext3cx conLrol in Lhis book. When iL's seL Lo mulLiline and resized, iL can
ALer Lhe LexL box values are assigned Lo Lhe variables, Lhe evenL procedure deLermines
which radio buLLon has been selecLed, calculaLes Lhe maLhemaLical ormula, and
displays Lhe resulL in a Lhird LexL box.
' Det er mi ne checked but t on and cal cul at e
I f Radi oBut t on1. Checked = Tr ue Then
Text Box3. Text = Fi r st Num+ SecondNum
End I f
Remember rom ChapLer 8 LhaL only one radio buLLon objecL in a group box objecL can
be selecLed aL any given Lime. ou can Lell wheLher a radio buLLon has been selecLed by
evaluaLing Lhe ChecleJ properLy. l iL's 1rue, Lhe buLLon has been selecLed. l Lhe ChecleJ
l48 Part II Programmng fundamentaIs
1he Advanced MaLh orm opens in Lhe Designer. 1he Advanced MaLh program is
idenLical Lo Lhe 8asic MaLh program, wiLh Lhe excepLion o Lhe operaLors shown in Lhe
radio buLLons and in Lhe program.
4. Click Lhe SLarL Debugging buLLon on Lhe SLandard Loolbar.
1he program displays Lwo LexL boxes in which you enLer numeric values, a group o
operaLor radio buLLons, a LexL box LhaL displays resulLs, and Lwo buLLons.
5. 1ype 9 in Lhe variable LexL box, and Lhen press 1A8.
6. 1ype 2 in Lhe variable 2 LexL box.
ou can now apply any o Lhe advanced operaLors Lo Lhe values in Lhe LexL boxes.
7. Click Lhe lnLeger Division radio buLLon, and Lhen click Lhe CalculaLe buLLon.
1he operaLor is applied Lo Lhe Lwo values, and Lhe number 4 appears in Lhe ResulL box,
as shown here.
lnLeger division produces only Lhe whole number resulL o Lhe division operaLion.
AlLhough 9 divided by 2 equals 4.5, Lhe inLeger division operaLion reLurns only Lhe
.
working wiLh quanLiLies LhaL can'L easily be divided inLo racLional componenLs, such
as .
8. Click Lhe Remainder radio buLLon, and Lhen click Lhe CalculaLe buLLon.
1he number appears in Lhe ResulL box. Remainder division (modulus ariLhmeLic)
reLurns Lhe remainder (Lhe parL leL over) aLer Lwo numbers are divided. 8ecause
9 divided by 2 equals 4 wiLh a remainder o (2 * 4 - = 9), Lhe resulL produced by
Lhe McJ operaLor is . ln addiLion Lo adding an early-970s vibe Lo your code, Lhe
McJ operaLor can help you Lrack "leLovers" in your calculaLions, such as Lhe amounL
.
Chapter 5 VsuaI asc VarabIes and formuIas, and the .Nf1 framework l49
9. Click Lhe FxponenLiaLion radio buLLon, and Lhen click Lhe CalculaLe buLLon.
1he number 8 appears in Lhe ResulL box. 1he exponenLiaLion operaLor () raises
a . For example, 9 2 equals 9
2
, or 8. ln a visual 8asic
ormula, 9
2
is wriLLen 9 2.
l0. Click Lhe ConcaLenaLion radio buLLon, and Lhen click Lhe CalculaLe buLLon.
1he number 92 appears in Lhe ResulL box. 1he sLring concaLenaLion operaLor (&)
combines Lwo sLrings in a ormula, buL noL Lhrough addiLion. 1he resulL is
a combinaLion o Lhe "9" characLer and Lhe "2" characLer. SLring concaLenaLion can be
perormed on numeric variables-or example, i you're displaying Lhe inning-by-inning
score o a baseball game as Lhey do in old-Lime score boxes-buL concaLenaLion is
more commonly perormed on sLring values or variables.
8ecause l declared Lhe lirstNum and SeccnJNum variables as Lype Dcuble, you can'L
combine words or leLLers by using Lhe program code as wriLLen. As an example, Lry Lhe
ollowing LesL, which causes an error and ends Lhe program.
ll. 1ype birth in Lhe variable LexL box, Lype day in Lhe variable 2 LexL box, veriy LhaL
ConcaLenaLion is selecLed, and Lhen click CalculaLe.
visual 8asic is unable Lo process Lhe LexL values you enLered, so Lhe program sLops
running, and an error message appears on Lhe screen.
l50 Part II Programmng fundamentaIs
1his Lype o error is called a run-time errcr-an error LhaL suraces noL during Lhe design
and compilaLion o Lhe program buL laLer, when Lhe program is running and encounLers
a condiLion LhaL iL doesn'L know how Lo process. l Lhis seems odd, you mighL imagine
LhaL visual 8asic is simply oering you a modern rendiLion o Lhe roboL plea "Does noL
. 1he compuLer-speak message
"Conversion rom sLring 'birLh' Lo Lype 'Double' is noL valid" means LhaL Lhe words you
enLered in Lhe LexL boxes ("birLh" and "day") could noL be converLed, or ccst, by visual
8asic Lo variables o Lhe Lype Dcuble. Dcuble Lypes can conLain only numbers-period.
As we shall explore in more deLail laLer, visual SLudio doesn'L leave you hanging wiLh
such a problem, buL provides a dialog box wiLh dierenL Lypes o inormaLion Lo help
you resolve Lhe run-Lime error. For now, you have learned anoLher imporLanL lesson
abouL daLa Lypes and when noL Lo mix Lhem.
l2. Click Lhe SLop Debugging buLLon on Lhe SLandard Loolbar Lo end Lhe program.
our program ends and reLurns you Lo Lhe developmenL environmenL.
Note ln ChapLer 8, "Debugging visual 8asic Programs," you'll learn abouL debugging
mode, which allows you Lo Lrack down Lhe deecLs, or bus, in your program code.
Now Lake a look aL Lhe program code Lo see how variables were declared and how Lhe
advanced operaLors were used.
l3. Scroll Lo Lhe code aL Lhe Lop o Lhe Code FdiLor, i iL is noL currenLly visible.
ou see Lhe ollowing commenL and program sLaLemenL.
' Decl ar e Fi r st Numand SecondNumvar i abl es
Di mFi r st Num, SecondNumAs Doubl e
As you mighL recall rom Lhe previous exercise, lirstNum and SeccnJNum are Lhe
variables LhaL hold numbers coming in rom Lhe 1ext3cx1 and 1ext3cx2 objecLs.
l4. Change Lhe daLa Lype rom Dcuble Lo Strin so LhaL you can properly LesL how Lhe
sLring concaLenaLion (&) operaLor works.
l5. Scroll down in Lhe Code FdiLor Lo see how Lhe advanced operaLors are used in Lhe
program code.
ou see Lhe ollowing code.
' Assi gn t ext box val ues t o var i abl es
Fi r st Num= Text Box1. Text
SecondNum= Text Box2. Text
' Det er mi ne checked but t on and cal cul at e
I f Radi oBut t on1. Checked = Tr ue Then
Text Box3. Text = Fi r st Num\ SecondNum
End I f
Chapter 5 VsuaI asc VarabIes and formuIas, and the .Nf1 framework l5l
I f Radi oBut t on2. Checked = Tr ue Then
Text Box3. Text = Fi r st NumMod SecondNum
End I f
I f Radi oBut t on3. Checked = Tr ue Then
Text Box3. Text = Fi r st Num^ SecondNum
End I f
I f Radi oBut t on4. Checked = Tr ue Then
Text Box3. Text = Fi r st Num& SecondNum
End I f
Like Lhe 8asic MaLh program, Lhis program loads daLa rom Lhe LexL boxes and places
iL in Lhe lirstNum and SeccnJNum variables. 1he program Lhen checks Lo see which
radio buLLon Lhe user checked and compuLes Lhe requesLed ormula. ln Lhis evenL
procedure, Lhe inLeger division (\), remainder (McJ), exponenLiaLion (), and sLring
concaLenaLion (&) operaLors are used. Now LhaL you've changed Lhe daLa Lype o Lhe
variables Lo Strin, run Lhe program again Lo see how Lhe & operaLor works on LexL.
l6. Click Lhe SLarL Debugging buLLon.
l7. 1ype birth in Lhe variable LexL box, Lype day in Lhe variable 2 LexL box, click
ConcaLenaLion, and Lhen click CalculaLe.
1he program now concaLenaLes Lhe sLring values and doesn'L produce a run-Lime error,
as shown here.
l8. Click Lhe uiL buLLon Lo close Lhe program.
As you can see, Lhe Strin . However, iL is
noL a LoLal soluLion because variables o Lype Strin will noL uncLion correcLly i you
Lry Lhe lnLeger Division, Remainder, or FxponenLiaLion operaLions wiLh Lhem. So, i you
really wanLed Lo have your program process numbers cnJ LexL sLrings inLerchangeably,
you'd need Lo add some addiLional program logic Lo your code. For now, however,
.
l54 Part II Programmng fundamentaIs
1he System.Mcth class is a collecLion o meLhods provided by Lhe .NF1 Framework or
ariLhmeLic operaLions. 1he .NF1 Framework is organized in a hierarchical ashion and can
be very deep. 1he lmcrts sLaLemenL makes iL easier Lo reerence classes, properLies,
and meLhods in your projecL. For example, i you didn'L include Lhe previous lmcrts
sLaLemenL, Lo call Lhe Sqrt meLhod you would have Lo Lype System.Mcth.Sqrt insLead o
jusL Sqrt. 1he lmcrts
come even beore Lhe variables LhaL you declare or Lhe orm and Lhe Public Clcss lcrm1
sLaLemenL LhaL visual 8asic auLomaLically provides.
8. Move down in Lhe Code FdiLor, and Lhen add Lhe ollowing code Lo Lhe 3uttcn1_Clicl
evenL procedure beLween Lhe Privcte Sub and lnJ Sub sLaLemenLs.
Di mResul t As Doubl e
Resul t = Sqr t ( 625)
Text Box1. Text = Resul t
1hese Lhree sLaLemenLs declare a variable o Lhe double Lype named Result, use Lhe
Sqrt meLhod Lo compuLe Lhe square rooL o 625, and assign Lhe Result variable Lo Lhe
1ext properLy o Lhe LexL box objecL so LhaL Lhe answer is displayed.
9. Click Lhe Save All buLLon on Lhe SLandard Loolbar Lo save your changes. Speciy Lhe
C.\vb0sbs\Chap05 older as Lhe locaLion.
l0. Click Lhe SLarL Debugging buLLon on Lhe SLandard Loolbar.
1he Framework MaLh program runs in Lhe lDF.
ll. Click Lhe Square RooL buLLon.
visual 8asic calculaLes Lhe square rooL o 625 and displays Lhe resulL (25) in Lhe LexL box.
As you can see here, Lhe Sqrt meLhod works!
l2. Click Lhe Close buLLon on Lhe orm Lo end Lhe program.
l59
ChapLer 6
Usng Decson Structures
After compIetng ths chapter, you wII be abIe to:
WriLe condiLional expressions.
Use an lj . . . 1hen sLaLemenL Lo branch Lo a seL o program sLaLemenLs based on
a varying condiLion.
Use Lhe McsleJ1ext3cx .
ShorL-circuiL an lj . . . 1hen sLaLemenL.
Use a Select Ccse sLaLemenL Lo selecL one choice rom many opLions in program code.
Use Lhe Ncme properLy Lo rename objecLs wiLhin a program.
Manage mouse evenLs and wriLe a McuseHcver evenL handler.
ln Lhe pasL ew chapLers, you used several eaLures o MicrosoL visual 8asic 200 Lo process
user inpuL. ou used menus, Loolbars, dialog boxes, and oLher 1oolbox conLrols Lo display
choices or Lhe user, and you processed inpuL by using properLy seLLings, variables, operaLors,
ormulas, and Lhe MicrosoL .NF1 Framework.
based on inpuL you receive rom Lhe user. ou'll also learn how Lo evaluaLe one or more
properLies or variables by using condiLional expressions, and Lhen execuLe one or more
program sLaLemenLs based on Lhe resulLs. ln shorL, you'll increase your programming
vocabulary by creaLing code blocks called Jecisicn structures LhaL conLrol how your program
execuLes, or , inLernally.
vent-Driven Programming
1he programs you've wriLLen so ar in Lhis book have displayed 1oolbox conLrols, menus,
Loolbars, and dialog boxes on Lhe screen, and wiLh Lhese programs, users could manipulaLe
. 1he programs puL Lhe user in charge,
waiLed paLienLly or a response, and Lhen processed Lhe inpuL predicLably. ln programming
circles, Lhis meLhodology is known as event-Jriven rcrcmmin. ou build a program by
creaLing a group o "inLelligenL" objecLs LhaL know how Lo respond Lo inpuL, and Lhen Lhe
program processes Lhe inpuL by using evenL procedures associaLed wiLh Lhe objecLs.
Where does Lhis inpuL come rom FundamenLally, o course, mosL inpuL comes rom Lhe user
o your program, who is opening menus, clicking Lhe mouse, Lyping in LexL boxes, and so on.
However, program inpuL can also come rom Lhe compuLer sysLem iLsel. For example, your
l60 Part II Programmng fundamentaIs
has elapsed on Lhe sysLem clock. ln Lhese siLuaLions, Lhe compuLer, noL Lhe user, Lriggers Lhe
imporLanL evenLs. 8uL regardless o how an evenL is Lriggered, visual 8asic reacLs by calling
Lhe evenL procedure associaLed wiLh Lhe objecL LhaL recognized Lhe evenL and execuLes
Lhe program code in Lhe evenL procedure. So ar, you've dealL primarily wiLh Lhe Clicl,
ChecleJChcneJ, and SelecteJlnJexChcneJ evenLs. However, visual 8asic objecLs also can
respond Lo many oLher Lypes o evenLs.
1he evenL-driven naLure o visual 8asic means LhaL mosL o Lhe compuLing done in your
programs is accomplished by evenL procedures.
inpuL, calculaLe new values, display ouLpuL, and handle oLher Lasks.
ln Lhis chapLer, you'll learn how Lo use decision sLrucLures Lo compare variables, properLies,
and values, and how Lo execuLe one or more sLaLemenLs based on Lhe resulLs. ln ChapLer 7,
"Using Loops and 1imers," you'll use loops Lo execuLe a group o sLaLemenLs over and
. 1ogeLher, Lhese powerul
Lo almosL any siLuaLion.
vents Supported by VisuaI Basic Objects
. 1hese
evenLs are lisLed when you selecL an objecL name in Lhe Class Name lisL box aL Lhe Lop
o Lhe Code FdiLor and Lhen click Lhe MeLhod Name arrow. (FvenLs are visually
in MicrosoL visual SLudio by a lighLning bolL icon.) ou can wriLe an evenL procedure or
any o Lhese evenLs, and i LhaL evenL occurs in Lhe program, visual 8asic will execuLe Lhe
evenL procedure LhaL's associaLed wiLh iL. For example, a lisL box objecL supporLs more Lhan
60 evenLs, including Clicl, DcubleClicl, DrcDrc, DrcOver, Cctlccus, keyDcwn, keyPress,
keyU, lcstlccus, McuseDcwn, McuseMcve, McuseU, McuseHcver, SelecteJlnJexChcneJ,
1extChcneJ, and vcliJcteJ. ou probably won'L need Lo wriLe code or more Lhan Lhree or
our o Lhese evenLs in your applicaLions, buL iL's nice Lo know LhaL you have so many choices
when you creaLe elemenLs in your inLerace. 1he ollowing screen shoL shows a parLial lisLing
o Lhe evenLs or a lisL box objecL in Lhe Code FdiLor.
l62 Part II Programmng fundamentaIs
in Lhe program and Lake a course o acLion based on Lhe resulL. ln iLs simplesL orm,
an lj . . . 1hen decision sLrucLure is wriLLen on a single line.
I f condi t i on Then st at ement
where ccnJiticn is a condiLional expression, and stctement is a valid visual 8asic program
sLaLemenL. For example.
I f Scor e >= 20 Then Label 1. Text = " You wi n! "
is an lj . . . 1hen decision sLrucLure LhaL uses Lhe condiLional expression.
Scor e >= 20
Lo deLermine wheLher Lhe program should seL Lhe 1ext properLy o Lhe lcbel1 objecL Lo "ou
win!" l Lhe Sccre variable conLains a value LhaL's greaLer Lhan or equal Lo 20, visual 8asic
seLs Lhe 1ext properLy, oLherwise, iL skips Lhe assignmenL sLaLemenL and execuLes Lhe nexL
line in Lhe evenL procedure. 1his sorL o comparison always resulLs in a 1rue or False value.
A condiLional expression never resulLs in a value o maybe.
1estng SeveraI Condtons n an lf . . . Then
Decson Structure
visual 8asic also supporLs an lj . . . 1hen decision sLrucLure LhaL you can use Lo include several
condiLional expressions. 1his block o sLaLemenLs can be several lines long and conLains Lhe
imporLanL keywords llselj, llse, and lnJ lj.
I f condi t i on1 Then
st at ement s execut ed i f condi t i on1 i s Tr ue
El seI f condi t i on2 Then
st at ement s execut ed i f condi t i on2 i s Tr ue
[ Addi t i onal El seI f condi t i ons and st at ement s can be pl aced her e]
El se
st at ement s execut ed i f none of t he condi t i ons i s Tr ue
End I f
ln Lhis sLrucLure, ccnJiticn1 . l Lhis condiLional expression is 1rue, Lhe block
o sLaLemenLs below iL is execuLed, one sLaLemenL aL a Lime. (ou can include one or more
program sLaLemenLs.
(ccnJiticn2) is evaluaLed. l Lhe second condiLion is 1rue, Lhe second block o sLaLemenLs
is execuLed. (ou can add addiLional llselj condiLions and sLaLemenLs i you have more
condiLions Lo evaluaLe.) l none o Lhe condiLional expressions is 1rue, Lhe sLaLemenLs below
Lhe llse keyword are execuLed. Finally, Lhe whole sLrucLure is closed by Lhe lnJ lj keywords.
1he ollowing code shows how a mulLiple-line lj . . . 1hen sLrucLure could be used Lo
deLermine Lhe amounL o Lax due in a hypoLheLical progressive Lax reLurn. (1he income
and percenLage numbers are rom Lhe projecLed U.S. lnLernal Revenue Service 200 1ax RaLe
.)
Chapter 6 Usng Decson Structures l63
Di mAdj ust edI ncome, TaxDue As Doubl e
Adj ust edI ncome = 50000
I f Adj ust edI ncome <= 8375 Then ' 10%t ax br acket
TaxDue = Adj ust edI ncome * 0. 1
El seI f Adj ust edI ncome <= 34000 Then ' 15%t ax br acket
TaxDue = 837. 5 + ( ( Adj ust edI ncome - 8375) * 0. 15)
El seI f Adj ust edI ncome <= 82400 Then ' 25%t ax br acket
TaxDue = 4681. 25 + ( ( Adj ust edI ncome - 34000) * 0. 25)
El seI f Adj ust edI ncome <= 171850 Then ' 28%t ax br acket
TaxDue = 16781. 25 + ( ( Adj ust edI ncome - 82400) * 0. 28)
El seI f Adj ust edI ncome <= 373650 Then ' 33%t ax br acket
TaxDue = 41827. 25 + ( ( Adj ust edI ncome - 171850) * 0. 33)
El se ' 35%t ax br acket
TaxDue = 108421. 25 + ( ( Adj ust edI ncome - 373650) * 0. 35)
End I f
Important 1he order o Lhe condiLional expressions in your lj . . . 1hen and llselj sLaLemenLs
is criLical. WhaL happens i you reverse Lhe order o Lhe condiLional expressions in Lhe Lax
compuLaLion example and lisL Lhe raLes in Lhe sLrucLure rom highesL Lo lowesL 1axpayers in Lhe
0 percenL, 5 percenL, 25 percenL, 28 percenL, and 88 percenL Lax brackeLs are all placed in Lhe
85 percenL Lax brackeL because Lhey all have an income LhaL's less Lhan or equal Lo S878,650.
oLhers are also 1rue.) All Lhe condiLional expressions in Lhis example LesL Lhe same variable, so
Lhey need Lo be lisLed in ascending order Lo geL Lhe Laxpayers Lo be placed in Lhe righL groups.
Moral. When you use more Lhan one condiLional expression, consider Lhe order careully.
1his useul decision sLrucLure LesLs Lhe double-precision variable AJjusteJlnccme
income level and subsequenL income levels unLil one o Lhe condiLional expressions evaluaLes
Lo 1rue, and Lhen deLermines Lhe Laxpayer's income Lax accordingly. WiLh some simple
sysLem, such as Lhe one in Lhe UniLed SLaLes. Provided LhaL Lhe Lax raLes are compleLe and up
Lo daLe and LhaL Lhe value in Lhe AJjusteJlnccme variable is correcL, Lhe program as wriLLen
will give Lhe correcL Lax owed or single U.S. Laxpayers or 200. l Lhe Lax raLes change, iL's
a simple maLLer Lo updaLe Lhe condiLional expressions. WiLh an addiLional decision sLrucLure
U.S. Laxpayers.
1p Fxpressions LhaL can be evaluaLed as 1rue or False are also known as 3cclecn exressicns,
and Lhe 1rue or False resulL can be assigned Lo a 8oolean variable or properLy. ou can assign
8oolean values Lo cerLain objecL properLies or 8oolean variables LhaL have been creaLed by using
Lhe Dim sLaLemenL and Lhe As 3cclecn keywords.
ln Lhe nexL exercise, you'll use an lj . . . 1hen decision sLrucLure LhaL recognizes users as Lhey
enLer a program-a simple way Lo geL sLarLed wiLh wriLing your own decision sLrucLures.
ou'll also learn how Lo use Lhe McsleJ1ext3cx conLrol Lo receive inpuL rom Lhe user in
a .
Chapter 6 Usng Decson Structures l65
AlLhough you won'L use iL now, Lake a momenL Lo noLe Lhe <CusLom> opLion, which
you can use laLer Lo creaLe your own inpuL masks using numbers and placeholder
characLers such as a hyphen (-).
8. Click OK Lo accepL Social SecuriLy Number as your inpuL mask.
visual SLudio displays your inpuL mask in Lhe McsleJ1ext3cx1 objecL, as shown in Lhe
ollowing screen shoL.
9. Double-click Lhe Sign ln buLLon.
1he 3uttcn1_Clicl evenL procedure appears in Lhe Code FdiLor.
l0. 1ype Lhe ollowing program sLaLemenLs in Lhe evenL procedure.
I f MaskedText Box1. Text = "555- 55- 1212" Then
MsgBox( " Wel come t o t he syst em! " )
El se
MsgBox( " I don' t r ecogni ze t hi s number " )
End I f
1his simple lj . . . 1hen decision sLrucLure checks Lhe value o Lhe McsleJ1ext3cx1
objecL's 1ext properLy, and i iL equals "555-55-22," Lhe sLrucLure displays Lhe
message "Welcome Lo Lhe sysLem!" l Lhe number enLered by Lhe user is some oLher
value, Lhe sLrucLure displays Lhe message "l don'L recognize Lhis number." 1he beauLy
in Lhis program, however, is how Lhe McsleJ1ext3cx1
Lo ensure LhaL iL is in Lhe correcL ormaL.
ll. Click Lhe Save All buLLon on Lhe SLandard Loolbar Lo save your changes. Speciy Lhe
C.\vb0sbs\Chap06 older as Lhe locaLion or your projecL.
l2. Click Lhe SLarL Debugging buLLon on Lhe SLandard Loolbar.
1he program runs in Lhe lDF. 1he orm prompLs Lhe user Lo enLer a Social SecuriLy
number (SSN) in Lhe appropriaLe ormaL, and displays underlines and hyphens Lo oer
Lhe user a hinL o Lhe ormaL required.
l66 Part II Programmng fundamentaIs
l3. 1ype abcd Lo LesL Lhe inpuL mask.
requesLed ormaL. A nine-digiL SSN is required.
l4. 1ype l234567890 Lo LesL Lhe inpuL mask.
visual 8asic displays Lhe number 28-45-6789 in Lhe masked LexL box, ignoring Lhe
0Lh digiL LhaL you Lyped. Again, visual 8asic has orced Lhe user's inpuL inLo Lhe
proper ormaL. our orm looks like Lhis.
l5. Click Lhe Sign ln buLLon.
visual 8asic displays Lhe message "l don'L recognize Lhis number" because Lhe SSN does
noL maLch Lhe number Lhe lj . . . 1hen decision sLrucLure is looking or.
l6. Click OK, deleLe Lhe SSN rom Lhe masked LexL box, enLer 555-55-l2l2 as Lhe number,
and Lhen click Sign ln again.
1his Lime Lhe decision sLrucLure recognizes Lhe number and displays a welcome message.
ou see Lhe ollowing message box.
Chapter 6 Usng Decson Structures l69
l2. Click OK Lo close Lhe message box.
l3. FxperimenL wiLh oLher values or Lhe SSN and PlN.
1esL Lhe program careully Lo be sure LhaL Lhe welcome message is noL displayed when
oLher PlNs or SSNs are enLered.
l4. .
1he program ends, and Lhe developmenL environmenL reLurns.
1p ou can urLher cusLomize Lhis program by using Lhe PcsswcrJChcr properLy in
masked LexL box objecLs. 1he PcsswcrJChcr properLy can be used Lo display a placeholder
characLer, such as an asLerisk (*), when Lhe user Lypes. (ou speciy Lhe characLer by using
Lhe ProperLies window.) Using a password characLer gives users addiLional secrecy as Lhey
enLer Lheir proLecLed password-a sLandard eaLure o such operaLions.
Short-Crcutng by Usng AndAlso and OrLlse
visual 8asic oers Lwo logical operaLors LhaL you can use in your condiLional sLaLemenLs,
AnJAlsc and Orllse. 1hese operaLors work Lhe same as AnJ and Or respecLively, buL
oer an imporLanL subLleLy in Lhe way Lhey're evaluaLed LhaL is worLh a ew momenLs o
LhoughLul consideraLion. However, Lhey are also somewhaL advanced, so i you would like
Lo skip Lhis secLion (oered here or compleLeness sake) eel ree Lo do so.
Consider an lj sLaLemenL LhaL has Lwo condiLions LhaL are connecLed by an AnJAlsc operaLor.
For Lhe sLaLemenLs o Lhe lj sLrucLure Lo be execuLed, boLh condiLions musL evaluaLe Lo 1rue.
llse sLaLemenL
immediaLely, wiLhouL LesLing Lhe second condiLion. 1his parLial, or shcrt-circuitin, evaluaLion
l70 Part II Programmng fundamentaIs
o an lj sLaLemenL makes logical sense-why should visual 8asic conLinue Lo evaluaLe Lhe lj
sLaLemenL i boLh condiLions cannoL be 1rue
1he Orllse operaLor works in a similar ashion. Consider an lj sLaLemenL LhaL has Lwo
condiLions LhaL are connecLed by an Orllse operaLor. For Lhe sLaLemenLs o Lhe lj sLrucLure
Lo be execuLed, aL leasL one condiLion musL evaluaLe Lo 1rue.
Lo 1rue, visual 8asic begins Lo execuLe Lhe sLaLemenLs in Lhe lj sLrucLure immediaLely, wiLhouL
LesLing Lhe second condiLion.
Here's an example o Lhe shorL-circuiL siLuaLion in visual 8asic, a simple rouLine LhaL uses
an lj sLaLemenL and an AnJAlsc operaLor Lo LesL Lwo condiLions and display Lhe message
"lnside l" i boLh condiLions are 1rue.
Di mNumber As I nt eger = 0
I f Number = 1 AndAl so MsgBox( " Second condi t i on t est " ) Then
MsgBox( " I nsi de I f " )
El se
MsgBox( " I nsi de El se")
End I f
1he Ms3cx uncLion iLsel is used as Lhe second condiLional LesL, which is somewhaL unusual,
buL Lhe sLrange synLax is compleLely valid and gives us a perecL opporLuniLy Lo see how
shorL-circuiLing works up close. 1he LexL "Second condiLion LesL" appears in a message
box only i Lhe Number variable is seL Lo , oLherwise, Lhe AnJAlsc operaLor shorL-circuiLs
Lhe lj sLaLemenL, and Lhe second condiLion isn'L evaluaLed. l you acLually Lry Lhis code,
remember LhaL iL's or demonsLraLion purposes only-you wouldn'L wanL Lo use Ms3cx
wiLh Lhis synLax as a LesL because iL doesn'L really LesL anyLhing. 8uL by changing Lhe Number
variable rom 0 Lo and back, you can geL a good idea o how Lhe AnJAlsc sLaLemenL and
shorL-circuiLing work.
Here's a second example o how shorL-circuiLing uncLions in visual 8asic when Lwo
condiLions are evaluaLed using Lhe AnJAlsc operaLor. 1his Lime, a more complex condiLional
LesL (7 / HumanAge <= ) is used aLer Lhe AnJAlsc operaLor Lo deLermine whaL some
people call Lhe "dog age" o a person.
Di mHumanAge As I nt eger
HumanAge = 7
' One year f or a dog i s seven year s f or a human
I f HumanAge <> 0 AndAl so 7 / HumanAge <= 1 Then
MsgBox( " You ar e at l east one dog year ol d" )
El se
MsgBox( " You ar e l ess t han one dog year ol d" )
End I f
As parL o a larger program LhaL deLermines Lhe so-called dog age o a person by dividing
his or her currenL age by 7, Lhis bare-bones rouLine Lries Lo deLermine wheLher Lhe value
in Lhe HumcnAe inLeger variable is aL leasL 7. (l you haven'L heard Lhe concepL o "dog
age" beore, bear wiLh me-ollowing Lhis logic, a 28-year-old person would be our dog
Chapter 6 Usng Decson Structures l7l
years old. 1his has been suggesLed as an inLeresLing way o relaLing Lo dogs, since dogs
have a liespan o roughly one-sevenLh LhaL o humans.) 1he code uses Lwo lj sLaLemenL
condiLions and can be used in a varieLy o dierenL conLexLs-l used iL in Lhe Clicl evenL
procedure or a buLLon objecL.
has been placed in Lhe HumcnAe variable-l've assumed momenLarily LhaL Lhe user has
enough sense Lo place a posiLive age inLo HumcnAe because a negaLive number would
produce incorrecL resulLs. 1he second condiLion LesLs wheLher Lhe person is aL leasL seven
years old. l boLh condiLions evaluaLe Lo 1rue, Lhe message "ou are aL leasL one dog year
old" is displayed in a message box. l Lhe person is less Lhan seven, Lhe message "ou are
less Lhan one dog year old" is displayed.
Now imagine LhaL l've changed Lhe value o Lhe HumcnAe variable rom 7 Lo 0. WhaL
lj sLaLemenL condiLion is evaluaLed as False by Lhe visual 8asic compiler,
and LhaL evaluaLion prevenLs Lhe second condiLion rom being evaluaLed, Lhus halLing, or
shorL-circuiLing, Lhe lj sLaLemenL and saving us rom a nasLy "divide by zero" error LhaL could
resulL i we divided 7 by 0 (Lhe new value o Lhe HumcnAe variable). And recall LhaL i you
divide by zero in a visual 8asic program and don'L caLch Lhe problem somehow, Lhe resulL
will be an error because division by zero isn'L permiLLed.
ln summary, Lhe AnJAlsc and Orllse operaLors in visual 8asic open up a ew new possibiliLies
or visual 8asic programmers, including Lhe poLenLial Lo prevenL run-Lime errors and oLher
unexpecLed resulLs. lL's also possible Lo improve perormance by placing condiLions LhaL
are Lime-consuming Lo calculaLe aL Lhe end o Lhe condiLion sLaLemenL because visual
8asic doesn'L perorm Lhese expensive condiLion calculaLions unless iL's necessary. However,
you need Lo Lhink careully abouL all Lhe possible condiLions LhaL your lj sLaLemenLs mighL
encounLer as variable sLaLes change during program execuLion.
Select Cose Decision Structures
WiLh visual 8asic, you can also conLrol Lhe execuLion o sLaLemenLs in your programs by
using Select Ccse decision sLrucLures. ou used Select Ccse sLrucLures in ChapLers 8 and 5
o Lhis book when you wroLe evenL procedures Lo process lisL box and combo box choices.
A Select Ccse sLrucLure is similar Lo an lj . . . 1hen . . . llselj
when Lhe branching depends on one key variable, or test ccse. ou can also use Select Ccse
sLrucLures Lo make your program code more readable.
1he synLax or a Select Ccse sLrucLure looks like Lhis.
Sel ect Case var i abl e
Case val ue1
st at ement s execut ed i f val ue1 mat ches var i abl e
Case val ue2
st at ement s execut ed i f val ue2 mat ches var i abl e
Case val ue3
l72 Part II Programmng fundamentaIs
st at ement s execut ed i f val ue3 mat ches var i abl e
. . .
Case El se
st at ement s execut ed i f no mat ch i s f ound
End Sel ect
A Select Ccse sLrucLure begins wiLh Lhe Select Ccse keywords and ends wiLh Lhe lnJ Select
keywords. ou replace vcricble wiLh Lhe variable, properLy, or oLher expression LhaL is Lo
be Lhe key value, or LesL case, or Lhe sLrucLure. ou replace vclue1, vclue2, and vclueJ wiLh
numbers, sLrings, or oLher values relaLed Lo Lhe LesL case being considered. l one o Lhe
values maLches Lhe variable, Lhe sLaLemenLs below Lhe Ccse clause are execuLed, and Lhen
visual 8asic jumps Lo Lhe line aLer Lhe lnJ Select sLaLemenL and picks up execuLion Lhere.
ou can include any number o Ccse clauses in a Select Ccse sLrucLure, and you can include
more Lhan one value in a Ccse clause. l you lisL mulLiple values aLer a case, separaLe Lhem
wiLh commas.
1he ollowing example shows how a Select Ccse sLrucLure could be used Lo prinL an
appropriaLe message abouL a person's age and culLural milesLones in a program. Since Lhe
Ae variable conLains a value o 8, Lhe sLring "ou can voLe now!" is assigned Lo Lhe 1ext
properLy o Lhe label objecL. (ou'll noLice LhaL Lhe "milesLones" have a U.S. slanL Lo Lhem,
please cusLomize reely Lo maLch your culLural seLLing.)
Di mAge As I nt eger
Age = 18
Sel ect Case Age
Case 16
Label 1. Text = " You can dr i ve now! "
Case 18
Label 1. Text = " You can vot e now! "
Case 21
Label 1. Text = " You can dr i nk wi ne wi t h your meal s. "
Case 65
Label 1. Text = " Ti me t o r et i r e and have f un! "
End Sel ect
A Select Ccse sLrucLure also supporLs a Ccse llse clause LhaL you can use Lo display a
message i none o Lhe preceding cases maLches Lhe Ae variable. Here's how Ccse llse
would work in Lhe ollowing example-noLe LhaL l've changed Lhe value o Ae Lo 25 Lo
Lrigger Lhe Ccse llse clause.
Di mAge As I nt eger
Age = 25
Sel ect Case Age
Case 16
Label 1. Text = " You can dr i ve now! "
Case 18
Label 1. Text = " You can vot e now! "
Case 21
Label 1. Text = " You can dr i nk wi ne wi t h your meal s. "
Chapter 6 Usng Decson Structures l75
Now you'll enLer Lhe program code Lo iniLialize Lhe lisL box.
9. Double-click Lhe orm.
1he lcrm1_lccJ evenL procedure appears in Lhe Code FdiLor.
l0. 1ype Lhe ollowing program code Lo iniLialize Lhe lisL box.
l st Count r yBox. I t ems. Add( " Engl and")
l st Count r yBox. I t ems. Add( " Ger many")
l st Count r yBox. I t ems. Add( " Mexi co" )
l st Count r yBox. I t ems. Add( " I t al y")
1hese lines use Lhe AJJ meLhod o Lhe lisL box objecL Lo add enLries Lo Lhe lisL box on
your orm.
ll. Click Lhe Form.vb [Design] Lab aL Lhe Lop o Lhe Code FdiLor Lo swiLch back Lo Lhe
Designer, and Lhen double-click Lhe lisL box objecL on your orm Lo ediL iLs evenL
procedure.
1he lstCcuntry3cx_SelecteJlnJexChcneJ evenL procedure appears in Lhe Code FdiLor.
l2. 1ype Lhe ollowing lines Lo process Lhe lisL box selecLion made by Lhe user.
l bl Count r y. Text = l st Count r yBox. Text
Sel ect Case l st Count r yBox. Sel ect edI ndex
Case 0
l bl Gr eet i ng. Text = "Hel l o, pr ogr ammer "
Case 1
l bl Gr eet i ng. Text = "Hal l o, pr ogr ammi er er "
Case 2
l bl Gr eet i ng. Text = "Hol a, pr ogr amador "
Case 3
l bl Gr eet i ng. Text = "Ci ao, pr ogr ammat or e"
End Sel ect
l76 Part II Programmng fundamentaIs
1ext properLy o Lhe
Lhird label on Lhe orm (which you renamed lblCcuntry). 1he mosL imporLanL properLy
used in Lhe sLaLemenL is lstCcuntry3cx.1ext, which conLains Lhe exacL LexL o Lhe iLem
selecLed in Lhe lisL box. 1he remaining sLaLemenLs are parL o Lhe Select Ccse decision
sLrucLure. 1he sLrucLure uses Lhe lstCcuntry3cx.SelecteJlnJex properLy as a LesL case
variable and compares iL Lo several values. 1he SelecteJlnJex properLy always conLains
Lhe number o Lhe iLem selecLed in Lhe lisL box, Lhe iLem aL Lhe Lop is 0 (zero), Lhe second
iLem is , Lhe nexL iLem is 2, and so on. 8y using SelecteJlnJex, Lhe Select Ccse sLrucLure
can quickly idenLiy Lhe user's choice and display Lhe correcL greeLing on Lhe orm.
l3. Display Lhe orm again, and Lhen double-click Lhe uiL buLLon (btnuit).
1he btnuit_Clicl evenL procedure appears in Lhe Code FdiLor.
l4. 1ype nd in Lhe evenL procedure.
l5. Click Lhe Save All buLLon on Lhe SLandard Loolbar Lo save your changes. Speciy Lhe
C.\vb0sbs\Chap06 older as Lhe locaLion.
Now run Lhe program, and see how Lhe Select Ccse sLaLemenL works.
1p 1he compleLe SelecL Case projecL is locaLed in Lhe C.\vb0sbs\Chap06\SelecL Case
older.
l6. Click Lhe SLarL Debugging buLLon on Lhe SLandard Loolbar Lo run Lhe program.
l7. Click each o Lhe counLry names in Lhe Choose A CounLry lisL box.
1he program displays a greeLing or each o Lhe counLries lisLed. 1he ollowing
screen shoL shows Lhe greeLing or lLaly.
l78 Part II Programmng fundamentaIs
4. 1ype Lhe ollowing program sLaLemenLs in Lhe lstCcuntry3cx_McuseHcver evenL
procedure.
I f l st Count r yBox. Sel ect edI ndex < 0 Then
l bl Gr eet i ng. Text = "Pl ease cl i ck t he count r y name"
End I f
1his lj sLaLemenL evaluaLes Lhe SelecteJlnJex properLy o Lhe lisL box objecL by using
a condiLional sLaLemenL. 1he evenL handler assumes LhaL i Lhe SelecteJlnJex properLy
is zero or greaLer, Lhe user doesn'L need help picking Lhe counLry name (because he or
she has already selecLed a counLry). 8uL i Lhe SelecteJlnJex properLy is less Lhan zero,
Lhe evenL handler displays Lhe message "Please click Lhe counLry name" in Lhe greeLing
label aL Lhe boLLom o Lhe orm. 1his Help message appears when Lhe user holds Lhe
poinLer over Lhe lisL box and disappears when a counLry name is selecLed.
5. Click Lhe SLarL Debugging buLLon Lo run Lhe program.
6. Hold Lhe poinLer over Lhe counLry lisL box, and waiL a ew momenLs.
1he message "Please click Lhe counLry name" appears in red LexL in Lhe label, as
shown here.
7. Click a counLry name in Lhe lisL box.
1he LranslaLed greeLing appears in Lhe label, and Lhe Help message disappears.
8. Click Lhe uiL buLLon Lo sLop Lhe program.
ou've learned how Lo process mouse evenLs in a program, and you've also learned
LhaL wriLing evenL handlers is quiLe simple. 1ry wriLing addiLional evenL handlers on
your own as you conLinue reading Lhis book-iL will help you learn more abouL Lhe
evenLs available Lo visual SLudio objecLs, and iL will give you more pracLice wiLh
lj . . . 1hen and Select Ccse decision sLrucLures.
l8l
ChapLer 7
Usng Loops and 1mers
After compIetng ths chapter, you wII be abIe to:
Use a lcr . . . Next loop Lo execuLe sLaLemenLs a seL number o Limes.
Display ouLpuL in a mulLiline LexL box by using sLring concaLenaLion.
Use a Dc .
Use Lhe 1imer .
CreaLe your own digiLal clock and Limed password uLiliLy.
Use Lhe lnserL SnippeL command Lo inserL ready-made code LemplaLes or snippeLs
inLo Lhe Code FdiLor.
ln ChapLer 6, "Using Decision SLrucLures," you learned how Lo use Lhe lj . . . 1hen and Select
Ccse decision sLrucLures Lo choose which sLaLemenLs Lo execuLe in a program. ou also
learned how Lo process user inpuL and evaluaLe dierenL condiLions in a program and how
Lo deLermine which block o program sLaLemenLs Lo execuLe based on changing condiLions.
Now you'll conLinue learning abouL program execuLion and by using lccs Lo
execuLe a block o sLaLemenLs over and over again. ou'll also creaLe a digiLal clock and
oLher inLeresLing uLiliLies LhaL perorm acLions aL seL Limes or in relaLion Lo inLervals on your
compuLer's sysLem clock.
ln Lhis chapLer, you'll use a lcr . . . Next loop Lo execuLe sLaLemenLs a seL number o Limes,
and you'll use a Dc loop Lo execuLe sLaLemenLs unLil a condiLional expression is meL. ou'll
also learn how Lo display more Lhan one line o LexL in a LexL box objecL by using Lhe sLring
concaLenaLion (&) operaLor, and you'll learn how Lo use Lhe MicrosoL visual SLudio 1imer
. Finally, you'll learn how Lo use
Lhe lnserL SnippeL command Lo inserL code LemplaLes inLo your programs-a Lime-saving
eaLure wiLhin Lhe visual SLudio lnLegraLed Design FnvironmenL (lDF).
writing Ior . . . Next Loops
WiLh a lcr . . . Next
number o Limes in an evenL procedure or a code module. 1his approach can be useul i
you're perorming several relaLed calculaLions, working wiLh elemenLs on Lhe screen, or
processing several pieces o user inpuL. A lcr . . . Next loop is really jusL a shorLhand way
o wriLing ouL a long lisL o program sLaLemenLs. 8ecause each group o sLaLemenLs in
such a lisL does
and requesL LhaL iL be execuLed as many Limes as you wanL.
l82 Part II Programmng fundamentaIs
1he synLax or a lcr . . . Next loop looks like Lhis.
For var i abl e = st ar t To end
st at ement s t o be r epeat ed
Next [ var i abl e]
ln Lhis synLax sLaLemenL, lcr, 1c, and Next are required keywords, as is Lhe equal Lo
operaLor (=). ou replace vcricble wiLh Lhe name o a numeric variable LhaL keeps Lrack
o Lhe currenL loop counL (Lhe variable aLer Next is opLional), and you replace stcrt and
enJ wiLh numeric values represenLing Lhe sLarLing and sLopping poinLs or Lhe loop. (NoLe
LhaL you musL declare vcricble beore iL's used in Lhe lcr . . . Next sLaLemenL and LhaL you
don'L Lype in Lhe brackeLs, which l include Lo indicaLe an opLional iLem.) 1he line or lines
beLween Lhe lcr and Next sLaLemenLs are Lhe insLrucLions LhaL are repeaLed each Lime
Lhe loop is execuLed.
For example, Lhe ollowing lcr . . . Next loop sounds our beeps in rapid succession rom
Lhe
Di mi As I nt eger
For i = 1 To 4
Beep( )
Next i
1his loop is Lhe uncLional equivalenL o wriLing Lhe 3ee sLaLemenL our Limes in a procedure.
1he compiler LreaLs iL Lhe same as.
Beep( )
Beep( )
Beep( )
Beep( )
1he variable used in Lhe loop is i
inLeger counLer in a lcr . . . Next loop and is declared as an lnteer Lype. Fach Lime Lhe
loop is execuLed, Lhe counLer variable is incremenLed by .
loop, Lhe variable conLains a value o , Lhe value o stcrt, Lhe lasL Lime Lhrough, iL conLains
a value o 4, Lhe value o enJ.) As you'll see in Lhe ollowing examples, you can use Lhis
counLer variable Lo greaL advanLage in your loops.
1p ln loops LhaL use counLer variables, Lhe usual pracLice is Lo use Lhe lnteer Lype or Lhe
variable declaraLion, as l did previously. However, you will geL similar perormance in visual 8asic
200 i you declare Lhe counLer variable as Lype lcn or Decimcl.
l84 Part II Programmng fundamentaIs
9. 1ype Lhe ollowing program sLaLemenLs in Lhe procedure.
Di mi As I nt eger
Di mWr ap As St r i ng
Wr ap = Chr ( 13) & Chr ( 10)
For i = 1 To 10
Text Box1. Text = Text Box1. Text & " Li ne " & i & Wr ap
Next i
1his evenL procedure declares Lwo variables, one o Lype lnteer (i) and one o Lype
Strin (Wrc). lL Lhen assigns a sLring value represenLing Lhe carriage reLurn characLer
Lo Lhe second variable.
1p ln programmer Lerms, a carriage reLurn characLer is Lhe equivalenL o pressing Lhe
FN1FR key on Lhe keyboard. l creaLed a special variable or Lhis characLer in Lhe program
code, which is made up o reLurn and lineeed elemenLs, Lo make coding a carriage reLurn
less cumbersome. 1he reLurn elemenL, Chr(8) moves Lhe l-beam Lo Lhe beginning o Lhe
line. 1he lineeed elemenL, Chr(0), reminiscenL o an older sLyle LypewriLer, moves Lhe
l-beam Lo Lhe nexL line.
ALer Lhe variable declaraLion and assignmenL, l use a lcr . . . Next loop Lo display
Line X 0 Limes in Lhe LexL box objecL, where X is Lhe currenL value o Lhe counLer
variable (in oLher words, Line Lhrough Line 0). 1he sLring concaLenaLion
characLers (&) join LogeLher Lhe componenL parLs o each line in Lhe LexL box. FirsL, Lhe
enLire value o Lhe LexL box, which is sLored in Lhe 1ext properLy, is added Lo Lhe objecL
so LhaL previous lines aren'L discarded when new ones are added. NexL, Lhe line sLring,
Lhe currenL line number, and Lhe carriage reLurn characLer (Wrc) are combined Lo
display a new line and move Lhe l-beam Lo Lhe leL margin and down one line. 1he Next
sLaLemenL compleLes Lhe loop.
NoLe LhaL visual SLudio auLomaLically adds Lhe Next sLaLemenL Lo Lhe boLLom o Lhe
loop when you Lype lcr Lo begin Lhe loop. ln Lhis case, l ediLed Lhe Next sLaLemenL Lo
include Lhe i .
(1he variable name makes iL clear which variable is being updaLed, especially in nesLed
lcr . . . Next loops.)
l0. Click Lhe Save All buLLon on Lhe SLandard Loolbar Lo save your changes, and speciy
Lhe C.\vb0sbs\Chap07 older as Lhe locaLion.
Now you're ready Lo run Lhe program.
1p 1he compleLe For Loop program is available in Lhe C.\vb0sbs\Chap07\For Loop
older.
ll. Click Lhe SLarL Debugging buLLon on Lhe SLandard Loolbar.
Chapter 7 Usng Loops and 1mers l85
l2. Click Lhe Loop buLLon.
1he lcr . . . Next loop displays 0 lines in Lhe LexL box, as shown here.
l3. Click Lhe Loop buLLon again.
1he lcr . . . Next loop displays anoLher 0 lines on Lhe orm. (ou can see any
nonvisible lines by using Lhe verLical scroll bar Lo scroll down.) Fach Lime Lhe loop is
repeaLed, iL adds 0 more lines Lo Lhe LexL box objecL.
1p Worried abouL running ouL o room in Lhe LexL box objecL lL will Lake a while i you're
displaying only simple LexL lines.
Mcxlenth properLy or a LexL box. 8y deaulL, Mcxlenth is seL Lo 82,767 characLers.
l you need more characLers, you can increase Lhis value. l you wanL more ormaLLing
opLions, you can use Lhe Rich1ext3cx conLrol in Lhe 1oolbox-a similar buL even more
capable conLrol or displaying and manipulaLing LexL.
l4. Click Lhe Close buLLon on Lhe orm Lo sLop Lhe program.
As you can see, a lcr . . . Next loop can considerably simpliy your code and reduce Lhe
LoLal number o sLaLemenLs LhaL you need Lo Lype. ln Lhe previous example, a loop
Lhree lines long processed Lhe equivalenL o 0 program sLaLemenLs each Lime you
clicked Lhe Loop buLLon.
Creating CompIex Ior . . . Next Loops
1he counLer variable in a lcr . . . Next loop can be a powerul Lool in your programs. WiLh
a liLLle imaginaLion, you can use iL Lo creaLe several useul sequences o numbers in your
loops. 1o creaLe a loop wiLh a counLer paLLern oLher Lhan , 2, 8, 4, and so on, you can
l88 Part II Programmng fundamentaIs
.
icons on your hard disk. ln Lhis example, you're loading Face0.ico, Face02.ico, Face08.
ico, and Face04.ico inLo Lhe picLure box.
xx.ico. 8y recognizing Lhe
paLLern, you can build a lcr . . . Next .
Note 1he message box uncLion (Ms3cx) is used primarily Lo slow Lhe acLion down so
LhaL you can see whaL's happening in Lhe lcr . . . Next loop. ln a normal applicaLion, you
probably wouldn'L use such a uncLion (buL you're welcome Lo).
8. Click Lhe Save All buLLon on Lhe SLandard Loolbar Lo save your changes. Speciy Lhe
C.\vb0sbs\Chap07 older as Lhe locaLion.
9. Click Lhe SLarL Debugging buLLon Lo run Lhe program, and Lhen click Lhe Display Four
Faces buLLon.
1he lcr . . . Next
message box.
Note l visual 8asic displays an error message, ensure LhaL your program code has no
. l
you insLalled Lhe Ste by Ste
be correcL.
Chapter 7 Usng Loops and 1mers l89
l0. Click OK Lo display Lhe nexL ace.
our screen looks someLhing like Lhis.
ll. Click OK Lhree more Limes Lo see Lhe enLire ace collecLion.
ou can repeaL Lhe sequence i you wanL.
l2. .
1he program sLops, and Lhe developmenL environmenL reLurns.
Usng a Counter 1hat Has Greater Scope
Are Lhere Limes when using a lcr . . . Next . ln acL,
Lhe preceding example, alLhough useul as a demonsLraLion, was a liLLle hampered by Lhe
inLrusive behavior o Lhe message box, which opened our Limes in Lhe lcr . . . Next loop and
disLracLed Lhe user rom Lhe orm, where we wanL his or her aLLenLion Lo be. ls Lhere a way
we can do away wiLh LhaL inLrusive message box
One soluLion is Lo remove boLh Lhe Ms3cx uncLion and Lhe lcr . . . Next loop, and subsLiLuLe
in Lheir place a counLer variable LhaL has greaLer scope LhroughouL Lhe orm. As you learned
in ChapLer 5, "visual 8asic variables and Formulas, and Lhe .NF1 Framework," you can declare
a variable LhaL has scope (or mainLains iLs value) LhroughouL Lhe enLire orm by placing a Dim
sLaLemenL or Lhe variable aL Lhe Lop o Lhe orm in Lhe Code FdiLor-a special locaLion above
Lhe evenL procedures. ln Lhe ollowing exercise, you'll use an lnteer variable named Ccunter
LhaL mainLains iLs value beLween calls Lo Lhe 3uttcn1_Clicl evenL procedure, and you'll use
Ms3cx uncLion Lo pause Lhe
acLion.
Chapter 7 Usng Loops and 1mers l9l
6. .
As you can see, Lhis soluLion is a liLLle more eleganL Lhan Lhe previous example because
Lhe user can click jusL one buLLon, noL a orm buLLon cnJ a message box buLLon. 1he
lcr . . . Next loop,
however, buL raLher Lhe limiLaLion l imposed LhaL Lhe 3uttcn1_Clicl evenL procedure use
only local variables (in oLher words, variables LhaL were declared wiLhin Lhe evenL procedure
iLsel). 8eLween buLLon clicks, Lhese local variables losL Lheir value, and Lhe only way l could
incremenL Lhe counLer was Lo build a loop. 8y using an lnteer variable wiLh a greaLer
scope, l can preserve Lhe value o Lhe Ccunter variable beLween clicks and use LhaL numeric
3uttcn1_Clicl evenL procedure.
The xit Ior Statement
MosL lcr . . . Next loops run Lo compleLion wiLhouL incidenL, buL now and Lhen you'll
lcr . . . Next loop i a parLicular "exiL condiLion"
occurs. visual 8asic allows or Lhis possibiliLy by providing Lhe lxit lcr sLaLemenL, which
you can use Lo LerminaLe Lhe execuLion o a lcr . . . Next loop early and move execuLion
.
For example, Lhe ollowing lcr . . . Next loop prompLs Lhe user or 0 names and
displays Lhem one by one in a LexL box unless Lhe user enLers Lhe word "Done".
Di mi As I nt eger
Di mI npName As St r i ng
For i = 1 To 10
I npName = I nput Box( " Ent er your name or t ype Done t o qui t . " )
I f I npName = "Done" Then Exi t For
Text Box1. Text = I npName
Next i
l Lhe user does enLer "Done," Lhe lxit lcr sLaLemenL LerminaLes Lhe loop, and execuLion
picks up wiLh Lhe sLaLemenL aLer Next.
l92 Part II Programmng fundamentaIs
writing Do Loops
As an alLernaLive Lo a lcr . . . Next loop, you can wriLe a Dc loop LhaL execuLes a group o
sLaLemenLs unLil a cerLain condiLion is 1rue. Dc loops are valuable because oLen you can'L
know in advance how many Limes a loop should repeaL. For example, you mighL wanL Lo leL
Lhe user enLer names in a daLabase unLil Lhe user Lypes Lhe word Dcne in an inpuL box. ln
LhaL case, you can use a Dc Dcne LexL sLring is enLered.
A Dc loop has several ormaLs, depending on where and how Lhe loop condiLion is evaluaLed.
1he mosL common synLax is.
Do Whi l e condi t i on
bl ock of st at ement s t o be execut ed
Loop
For example, Lhe ollowing Dc loop prompLs Lhe user or inpuL and displays LhaL inpuL in
a LexL box unLil Lhe word Dcne is Lyped in Lhe inpuL box.
Di mI npName As St r i ng
Do Whi l e I npName <> "Done"
I npName = I nput Box( "Ent er your name or t ype Done t o qui t . ")
I f I npName <> "Done" Then Text Box1. Text = I npName
Loop
1he condiLional sLaLemenL in Lhis loop is lnpName <> "Done", which Lhe visual 8asic
compiler LranslaLes Lo mean "loop so long as Lhe lnNcme variable doesn'L conLain Lhe
exacL word 'Done'." 1his brings up an inLeresLing acL abouL Dc loops. l Lhe condiLion aL
Lhe Lop o Lhe loop isn'L 1rue when Lhe Dc Dc loop is never
execuLed. Here, i Lhe lnNcme sLring variable did conLain Lhe "Done" value beore Lhe loop
sLarLed (perhaps rom an earlier assignmenL in Lhe evenL procedure), visual 8asic would skip
Lhe loop alLogeLher and conLinue wiLh Lhe line below Lhe lcc keyword.
l you always wanL Lhe loop Lo run aL leasL once in a program, puL Lhe condiLional LesL aL Lhe
boLLom o Lhe loop. For example, Lhe loop.
Di mI npName As St r i ng
Do
I npName = I nput Box( "Ent er your name or t ype Done t o qui t . ")
I f I npName <> "Done" Then Text Box1. Text = I npName
Loop Whi l e I npName <> " Done"
is essenLially Lhe same as Lhe previous Dc loop, buL here Lhe loop condiLion is LesLed aLer
a name is received rom Lhe lnut3cx uncLion. 1his has Lhe advanLage o updaLing Lhe
lnNcme variable beore Lhe condiLional LesL in Lhe loop so LhaL a preexisLing Dcne value
won'L cause Lhe loop Lo be skipped. 1esLing Lhe loop condiLion aL Lhe boLLom ensures LhaL
your loop is execuLed aL leasL once, buL oLen iL orces you Lo add a ew exLra sLaLemenLs Lo
process Lhe daLa.
l94 Part II Programmng fundamentaIs
1he new projecL is creaLed, and a blank orm opens in Lhe Designer. 1his Lime, you'll
place all Lhe code or your program in Lhe lcrm1_lccJ evenL procedure so LhaL visual
8asic immediaLely prompLs you or Lhe FahrenheiL LemperaLure when you sLarL Lhe
applicaLion. ou'll use an lnut3cx uncLion Lo requesL Lhe FahrenheiL daLa, and you'll
use a Ms3cx uncLion Lo display Lhe converLed value.
3. Double-click Lhe orm.
1he lcrm1_lccJ evenL procedure appears in Lhe Code FdiLor.
4. 1ype Lhe ollowing program sLaLemenLs in Lhe lcrm1_lccJ evenL procedure.
Di mFTemp, Cel si us As Si ngl e
Di mst r FTemp As St r i ng
Di mPr ompt As St r i ng = "Ent er a Fahr enhei t t emper at ur e. "
Do
st r FTemp = I nput Box( Pr ompt , "Fahr enhei t t o Cel si us")
I f st r FTemp <> " " Then
FTemp = CSng( st r FTemp)
Cel si us = I nt ( ( FTemp + 40) * 5 / 9 - 40)
MsgBox( Cel si us, , " Temper at ur e i n Cel si us")
End I f
Loop Whi l e st r FTemp <> ""
End
1p 8e sure Lo include Lhe lnJ sLaLemenL aL Lhe boLLom o Lhe lcrm1_lccJ evenL
procedure.
Lhe program LerminaLes.
1his code handles Lhe calculaLions or Lhe projecL.
single-precision variables, l1em and Celsius, Lo hold Lhe FahrenheiL and Celsius
LemperaLures, respecLively. 1he second line declares a sLring variable named
strl1em LhaL holds a sLring version o Lhe FahrenheiL LemperaLure. 1he Lhird line
declares a sLring variable named Prcmt, which will be used in Lhe lnut3cx uncLion,
and assigns iL an iniLial value. 1he Dc loop repeaLedly prompLs Lhe user or a FahrenheiL
LemperaLure, converLs Lhe number Lo Celsius, and Lhen displays iL on Lhe screen by
using Lhe Ms3cx uncLion.
1he value LhaL Lhe user enLers in Lhe inpuL box is sLored in Lhe strl1em variable. 1he
lnut3cx uncLion always reLurns a value o Lype Strin, even i Lhe user enLers numbers.
8ecause we wanL Lo perorm maLhemaLical calculaLions on Lhe enLered value, strl1em
musL be converLed Lo a number. 1he CSn uncLion is used Lo converL a sLring inLo Lhe
Sinle daLa Lype. CSn is one o many conversion uncLions you can use Lo converL a sLring
Lo a dierenL daLa Lype. 1he converLed single value is Lhen sLored in Lhe l1em variable.
1he loop execuLes unLil Lhe user clicks Lhe Cancel buLLon or unLil Lhe user presses
FN1FR or clicks OK wiLh no value in Lhe inpuL box. Clicking Lhe Cancel buLLon or
Chapter 7 Usng Loops and 1mers l95
enLering no value reLurns an empLy sLring (""). 1he loop checks or Lhe empLy sLring by
using a While condiLional LesL aL Lhe boLLom o Lhe loop. 1he program sLaLemenL.
Cel si us = I nt ( ( FTemp + 40) * 5 / 9 - 40)
handles Lhe conversion rom FahrenheiL Lo Celsius in Lhe program. 1his sLaLemenL
employs a sLandard conversion ormula, buL iL uses Lhe lnt uncLion Lo reLurn a value
LhaL conLains no decimal places Lo Lhe Celsius variable. (FveryLhing Lo Lhe righL o Lhe
decimal poinL is discarded.
unsighLly numbers such as 2., Lhe Celsius value or 70 degrees FahrenheiL.
5. Click Lhe Save All buLLon on Lhe SLandard Loolbar Lo save your changes. Speciy Lhe
C.\vb0sbs\Chap07 older as Lhe locaLion.
Now you'll Lry running Lhe program.
1p 1he compleLe Celsius Conversion program is available in Lhe C.\vb0sbs\Chap07\
Celsius Conversion older.
6. Click Lhe SLarL Debugging buLLon on Lhe SLandard Loolbar.
1he program sLarLs, and Lhe lnut3cx uncLion prompLs you or a FahrenheiL
LemperaLure.
7. 1ype 2l2.
our screen looks like Lhis.
8. Click OK.
1he LemperaLure 22 degrees FahrenheiL is converLed Lo 00 degrees Celsius, as shown
in Lhis message box.
l96 Part II Programmng fundamentaIs
9. Click OK. 1hen Lype 72 in Lhe inpuL box, and click OK again.
1he LemperaLure 72 degrees FahrenheiL is converLed Lo 22 degrees Celsius.
l0. Click OK, and Lhen click Cancel in Lhe inpuL box.
1he program closes, and Lhe developmenL environmenL reLurns.
Using the 0ntil Keyword in Do Loops
1he Dc loops you've worked wiLh so ar have used Lhe While keyword Lo execuLe
a group o sLaLemenLs so long as Lhe loop condiLion remains 1rue. WiLh visual 8asic,
you can also use Lhe Until keyword in Dc loops Lo cycle until a cerLain condiLion is 1rue.
Use Lhe Until keyword aL Lhe Lop or boLLom o a Dc loop Lo LesL a condiLion, jusL like
Lhe While keyword. For example, Lhe ollowing Dc loop uses Lhe Until keyword Lo loop
repeaLedly unLil Lhe user enLers Lhe word Dcne in Lhe inpuL box.
Di mI npName As St r i ng
Do
I npName = I nput Box( "Ent er your name or t ype Done t o qui t . ")
I f I npName <> "Done" Then Text Box1. Text = I npName
Loop Unt i l I npName = " Done"
As you can see, a loop LhaL uses Lhe Until keyword is similar Lo a loop LhaL uses Lhe While
keyword, excepL LhaL Lhe LesL condiLion usually conLains Lhe opposiLe operaLor-in Lhis
case, Lhe = (equal Lo) operaLor versus Lhe <> (noL equal Lo) operaLor. l using Lhe Until
keyword makes sense Lo you, eel ree Lo use iL wiLh LesL condiLions in your Dc loops.
The 7imer ControI
1imer conLrol, which you can
time intervcls. 1he
1imer conLrol is essenLially an invisible sLopwaLch LhaL gives you access Lo Lhe sysLem clock in
your programs. 1he 1imer conLrol can be used like an egg Limer Lo counL down rom a preseL
Lime, Lo cause a delay in a program, or Lo repeaL an acLion aL prescribed inLervals.
AlLhough Limer objecLs aren'L visible aL run Lime, each Limer is associaLed wiLh an evenL
procedure LhaL runs every Lime Lhe Limer's preseL inLerval has elapsed. ou seL a Limer's
inLerval by using Lhe lntervcl properLy, and you acLivaLe a Limer by seLLing Lhe Limer's lncbleJ
properLy Lo 1rue. Once a Limer is enabled, iL runs consLanLly-execuLing iLs evenL procedure
aL Lhe prescribed inLerval-unLil Lhe user sLops Lhe program or Lhe Limer objecL is disabled.
our job as a programmer is Lo conceive o how Lo use Lime in your programs creaLively.
ln oLher words, whaL evenLs in a program (or in lie) happen aL regular inLervals Can you
predicL or envision Lhe passage o Lime so LhaL iL can be inLegraLed inLo your code
Chapter 7 Usng Loops and 1mers l99
as Lhe Lime, use Lhe System.Dcte1ime.Ncw properLy insLead o Lhe 1imeStrin properLy.)
Only one sLaLemenL is required in Lhis program because you seL Lhe lntervcl properLy or
Lhe Limer by using Lhe ProperLies window. 1he Limer objecL handles Lhe resL.
8. Click Lhe Save All buLLon on Lhe SLandard Loolbar Lo save your changes. Speciy
C.\vb0sbs\Chap07 as Lhe older locaLion.
1p 1he compleLe DigiLal Clock program is available in Lhe C.\vb0sbs\Chap07\DigiLal
Clock older.
9. Click Lhe SLarL Debugging buLLon on Lhe SLandard Loolbar Lo run Lhe clock.
1he clock appears, as shown in Lhe ollowing screen shoL. (our Lime will be dierenL, o
course.)
l you used Lhe System.Dcte1ime.Ncw properLy, you'll also see Lhe daLe in Lhe clock,
as shown here.
l needed Lo enlarge Lhe label objecL and Lhe orm a liLLle here Lo geL Lhe daLe and Lime
Lo appear on one line. l your sysLem clock inormaLion appears wrapped, close Lhe
program and resize your label and orm.
l0. WaLch Lhe clock or a ew momenLs.
visual 8asic updaLes Lhe Lime every second.
ll. Click Lhe Close buLLon in Lhe LiLle bar Lo sLop Lhe clock.
1he DigiLal Clock program is so handy LhaL you mighL wanL Lo compile iL inLo an execuLable
. Feel ree Lo cusLomize iL by using your own
arLwork, LexL, and colors.
Chapter 7 Usng Loops and 1mers 20l
1rue sLarLs Lhe Limer running when Lhe program sLarLs. (l Lhe Limer wasn'L needed unLil
laLer in Lhe program, you could disable Lhis properLy and Lhen enable iL in an evenL
procedure.)
our orm looks like Lhis.
8. Double-click Lhe Limer objecL in Lhe componenL Lray, and Lhen Lype Lhe ollowing
sLaLemenLs in Lhe 1imer1_1icl evenL procedure.
MsgBox( " Sor r y, your t i me i s up. " )
End
second sLaLemenL sLops Lhe program. visual 8asic execuLes Lhis evenL procedure i Lhe
Limer inLerval reaches 5 seconds and a valid password hasn'L been enLered.
9. Display Lhe orm, double-click Lhe buLLon objecL, and Lhen Lype Lhe ollowing sLaLemenLs
in Lhe 3uttcn1_Clicl evenL procedure.
I f Text Box1. Text = " secr et " Then
Ti mer 1. Enabl ed = Fal se
MsgBox( " Wel come t o t he syst em! " )
End
El se
MsgBox( " Sor r y, f r i end, I don' t know you. ")
End I f
1his program code LesLs wheLher Lhe password enLered in Lhe LexL box is "secreL." l iL is,
Lhe Limer is disabled, a welcome message is displayed, and Lhe program ends. (A more
useul program would conLinue working raLher Lhan ending here.) l Lhe password
chance Lo enLer Lhe password. 8uL Lhe user has only 5 seconds Lo do so!
l0. Click Lhe Save All buLLon on Lhe SLandard Loolbar Lo save your changes. Speciy Lhe
C.\vb0sbs\Chap07 older as Lhe locaLion.
204 Part II Programmng fundamentaIs
2. CreaLe a new buLLon objecL in Lhe middle o Lhe orm, and seL Lhe 1ext properLy o Lhe
buLLon Lo "Display Windows version."
3. Double-click Lhe buLLon objecL Lo display Lhe 3uttcn1_Clicl evenL procedure.
Now you'll use Lhe lnserL SnippeL command Lo inserL a code LemplaLe LhaL auLomaLically
reLurns inormaLion abouL Lhe version o Windows insLalled on your compuLer. NoLe LhaL
Lhis parLicular snippeL is jusL one example rom a lisL o dozens o useul code LemplaLes.
4. Click Lhe FdiL menu, poinL Lo Lhe lnLelliSense submenu, and Lhen click Lhe lnserL SnippeL
command.
1he lnserL SnippeL lisL box appears in Lhe Code FdiLor, as shown in Lhe ollowing
screen shoL. Depending on whaL componenLs o visual SLudio you have insLalled, your
snippeL lisL will have some dierences.
1p ou can also open Lhe snippeL lisL by righL-clicking in Lhe Designer and selecLing
lnserL SnippeL.
1he lnserL SnippeL lisL box is a navigaLion Lool LhaL you can use Lo explore Lhe snippeL
library and inserL snippeLs inLo your program aL Lhe inserLion poinL. 1o open a older in
Lhe lisL box, double-click Lhe older name. 1o reLurn Lo Lhe previous older in Lhe older
hierarchy, press Lhe 8ACKSPACF key.
Chapter 7 Usng Loops and 1mers 205
5. Scroll down in Lhe lisL box, and Lhen double-click Lhe Windows SysLem - Logging,
Processes, RegisLry, Services older.
seLLings.
1p l you are using visual 8asic 200 Fxpress, you mighL noL see Lhe Windows SysLem -
Logging, Processes, RegisLry, Services older. l you do noL see Lhis older, you can jusL Lype
Lhe code lisLed in SLep 7.
6. Double-click Lhe Windows - SysLem lnormaLion older.
A lisL o sysLem inormaLion snippeLs appears. Now you'll selecL Lhe snippeL LhaL reLurns
inormaLion abouL Lhe currenL version o Windows.
7. Double-click Lhe snippeL enLiLled "DeLermine Lhe CurrenL Windows version."
visual SLudio inserLs Lhe ollowing line o code inLo Lhe 3uttcn1_Clicl evenL procedure
aL Lhe inserLion poinL.
Di mosVer si on = My. Comput er . I nf o. OSVer si on
1hese sLaLemenLs declare Lhe sLring variable csversicn Lo hold version inormaLion abouL
Lhe operaLing sysLem, and Lhen use Lhe Ccmuter.lnjc currenL
inormaLion. 1he snippeL also uses Lhe My namespace Lo gaLher inormaLion abouL your
compuLer. 1he My namespace is a "speed-dial" eaLure o visual 8asic designed Lo reduce Lhe
Lime iL Lakes Lo code common Lasks, and l will inLroduce iL more ully in ChapLer 8.
1his code snippeL is called a LemplaLe because iL supplies Lhe majoriLy o Lhe code
LhaL you need Lo inserL or a parLicular Lask, buL Lhe code is noL ully inLegraLed inLo
your projecL yeL. ln Lhis case, we should add a second variable Lo hold Lhe name o
Lhe operaLing sysLem (because Lhere are dierenL Windows versions), and we'll add
a Ms3cx uncLion Lo display Lhe resulLs or Lhe user. (ln oLher cases, you mighL need Lo
add conLrols Lo your orm, creaLe new variables or daLa sLrucLures, or wriLe addiLional
program sLaLemenLs LhaL use Lhe snippeL.)
8. Press Lhe FN1FR key Lwice Lo add a blank line below Lhe snippeL.
9. 1ype Lhe ollowing program sLaLemenLs.
Di mosName = My. Comput er . I nf o. OSFul l Name
MsgBox( osName & vbCr & osVer si on)
1hese sLaLemenLs declare a second sLring variable named csNcme LhaL will hold Lhe
Windows version reLrieved by Lhe OSlullNcme properLy o Lhe Ccmuter.lnjc objecL. 1here
is also a Ms3cx uncLion LhaL displays Lhe Lwo reLurned values. Lhe operaLing sysLem name
(csNcme) and Lhe operaLing sysLem version number (csversicn). As you probably know,
Lhe operaLing sysLem version number has now become quiLe deLailed in Windows because
206 Part II Programmng fundamentaIs
Windows has Lhe abiliLy Lo be updaLed auLomaLically over Lhe Web each Lime a new
securiLy updaLe or improvemenL is released. Fxamining Lhe version number is Lhereore
a handy way Lo see wheLher your sysLem is up-Lo-daLe and sae.
ou'll also noLice LhaL l used vbCr. 1his is a consLanL LhaL represenLs a carriage reLurn.
1his can be used as an alLernaLive Lo Lhe Chr(1J) sLaLemenL LhaL was used earlier in Lhe
chapLer. 1here are several o Lhese consLanLs LhaL can be helpul. When you Lype vb in
Lhe Code FdiLor, you'll see a lisL o all Lhese consLanLs. our screen looks like Lhis.
l0. Click Lhe Save All buLLon Lo save your changes, and speciy Lhe C.\vb0sbs\Chap07
older as Lhe locaLion.
ll. Click Lhe SLarL Debugging buLLon Lo run Lhe program.
visual SLudio runs Lhe program in Lhe lDF.
l2. Click Lhe Display Windows version buLLon Lo display Lhe version inormaLion reLurned
by Lhe snippeL.
our dialog box looks similar Lo Lhe ollowing.
l3. Click OK Lo close Lhe dialog box, and Lhen click Lhe Close buLLon Lo end Lhe program.
209
ChapLer 8
Debuggng VsuaI asc Programs
After compIetng ths chapter, you wII be abIe to:
ldenLiy dierenL Lypes o errors in your programs.
Use visual SLudio debugging Lools Lo seL breakpoinLs and correcL misLakes.
Use Lhe AuLos and WaLch windows Lo examine variables during program execuLion.
Use a visualizer Lo examine sLring daLa Lypes and complex daLa Lypes wiLhin Lhe lDF.
Use Lhe lmmediaLe and Command windows Lo change Lhe value o variables and
execuLe commands in visual SLudio.
Remove breakpoinLs.
ln Lhe pasL ew chapLers, you've had plenLy o opporLuniLy Lo make programming misLakes
in your code. Unlike human conversaLion, which usually works well despiLe occasional
grammaLical misLakes and mispronunciaLions, communicaLion beLween a soLware
developer and Lhe MicrosoL visual 8asic compiler is successul only when Lhe precise rules
and regulaLions o Lhe visual 8asic programming language are ollowed.
ln Lhis chapLer, you'll learn more abouL Lhe soLware deecLs, or bus, LhaL sLop visual 8asic
programs rom running. ou'll learn abouL Lhe dierenL Lypes o errors LhaL Lurn up in
programs and how Lo use Lhe MicrosoL visual SLudio debugging Lools Lo deLecL and correcL
Lhese deecLs. WhaL you learn will be useul as you experimenL wiLh Lhe programs in Lhis
book and when you wriLe longer programs in Lhe uLure.
Why ocus on debugging now Some programming books skip Lhis Lopic alLogeLher or place
iL near Lhe end o Lhe book (cjter you've learned all Lhe language eaLures o a parLicular
producL). 1here is a cerLain logic Lo posLponing Lhe discussion, buL l Lhink iL makes Lhe mosL
sense Lo masLer debugging Lechniques while you learn Lo program so LhaL deLecLing and
correcLing errors becomes parL o your sLandard approach Lo wriLing programs and solving
problems. AL Lhis poinL in Lhis book, you know jusL enough abouL objecLs, decision sLrucLures,
and sLaLemenL synLax Lo creaLe inLeresLing programs-buL also enough Lo geL yoursel inLo
a liLLle biL o Lrouble! As you'll soon see, however, visual SLudio 200 makes iL easy Lo uncover
your misLakes and geL back on Lhe sLraighL and narrow.
linding and Correcting rrors
1he deecLs you've encounLered in your programs so ar have probably been simple Lyping
misLakes or synLax errors. 8uL whaL i you discover a nasLier problem in your program-one
2l0 Part II Programmng fundamentaIs
you've used 1he visual SLudio lnLegraLed DevelopmenL FnvironmenL (lDF) conLains several
. 1hese Lools won'L sLop you
rom making misLakes, buL Lhey oLen ease Lhe pain when you encounLer one.
Three Types of rrors
1hree Lypes o errors can occur in a visual 8asic program. synLax errors, run-Lime errors,
and logic errors, as ollows.
A syntcx errcr (or ccmiler errcr) is a misLake (such as a misspelled properLy or keyword)
LhaL violaLes Lhe programming rules o visual 8asic. visual 8asic will poinL ouL several
Lypes o synLax errors in your programs while you enLer program sLaLemenLs, and iL
.
A run-time errcr is a misLake LhaL causes a program Lo sLop unexpecLedly during
execuLion. Run-Lime errors occur when an ouLside evenL or an undiscovered synLax
error orces a program Lo sLop while iL's running.
name when you use Lhe System.Drcwin.lmce.lrcmlile meLhod, or i you Lry Lo
read a disk drive and iL doesn'L conLain a CD or DvD, your code will generaLe a
run-Lime error.
A lcic errcr is a human error-a misLake LhaL causes Lhe program code Lo produce
Lhe wrong resulLs. MosL debugging eorLs are ocused on Lracking down logic errors
inLroduced by Lhe programmer.
l you encounLer a synLax error, you oLen can solve Lhe problem by using Lhe visual SLudio
misLake
by paying close aLLenLion Lo Lhe exacL synLax o Lhe uncLions, objecLs, meLhods, and
properLies LhaL you have used. ln Lhe Code FdiLor, incorrecL sLaLemenLs are underlined wiLh
a jagged line, and you can learn more abouL Lhe error by holding Lhe mouse poinLer over Lhe
sLaLemenL. 1he ollowing screen shoL shows Lhe error message LhaL appears in visual SLudio
when l Lype Lhe keyword Ccse incorrecLly as "Csae" and Lhen hold Lhe mouse poinLer over
Lhe error. 1his error message appears as a Screen1ip.
Chapter 8 Debuggng VsuaI asc Programs 2ll
1p 8y deaulL, a green jagged line indicaLes a warning, a red jagged line indicaLes a synLax
error, a blue jagged line indicaLes a compiler error, and a purple jagged line indicaLes some oLher
error. 1he color o Lhese iLems and mosL o Lhe eaLures in Lhe user inLerace can be adjusLed by
selecLing Lhe OpLions command on Lhe 1ools menu, clicking Lhe FonLs And Colors opLion under
FnvironmenL, and adjusLing Lhe deaulL values under Display lLems.
l you encounLer a run-Lime error, you oLen can address Lhe problem by correcLing your
Lyping. For example, i a biLmap loads incorrecLly inLo a picLure box objecL, Lhe problem
mighL simply be a misspelled paLh. However, many run-Lime errors require a more Lhorough
soluLion. ou can add a structureJ errcr hcnJler-a special block o program code LhaL
recognizes a run-Lime error when iL happens, suppresses any error messages, and adjusLs
program condiLions Lo handle Lhe problem-Lo your programs. l discuss Lhe new synLax or
sLrucLured error handlers in ChapLer 9, "1rapping Frrors by Using SLrucLured Frror Handling."
ldentifying Logic rrors
. 1hey're Lhe resulL o aulLy
reasoning and planning, noL a misundersLanding abouL visual 8asic synLax. Consider Lhe
ollowing lj . . . 1hen decision sLrucLure, which evaluaLes Lwo condiLional expressions and Lhen
displays one o Lwo messages based on Lhe resulL.
I f Age > 13 And Age < 20 Then
Text Box2. Text = "You' r e a t eenager "
El se
Text Box2. Text = "You' r e not a t eenager "
End I f
Can you spoL Lhe problem wiLh Lhis decision sLrucLure A Leenager is a person who is
beLween 8 and 9 years old, inclusive, buL Lhe sLrucLure ails Lo idenLiy Lhe person who's
exacLly 8. (For Lhis age, Lhe sLrucLure erroneously displays Lhe message "ou're noL a
Leenager.") 1his Lype o misLake isn'L a synLax error (because Lhe sLaLemenLs ollow Lhe rules
o visual 8asic), iL's a menLal misLake or logic error. 1he correcL decision sLrucLure conLains
a greaLer Lhan or equal Lo operaLor (>= lj . . . 1hen sLaLemenL,
as shown here.
I f Age >= 13 And Age < 20 Then
8elieve iL or noL, Lhis Lype o misLake is Lhe mosL common problem in a visual 8asic program.
Code LhaL produces Lhe expecLed resulLs mosL o Lhe Lime-buL noL all Lhe Lime-is Lhe
.
Chapter 8 Debuggng VsuaI asc Programs 2l3
4. l Lhe orm isn'L visible, display iL now.
1he Debug 1esL program prompLs Lhe user or his or her age. When Lhe user
clicks Lhe 1esL buLLon, Lhe program inorms Lhe user wheLher he or she is a Leenager.
1he
chapLer, however.
problem.
5. l Lhe Debug Loolbar isn'L visible, click Lhe view menu, poinL Lo 1oolbars, and Lhen
click Debug.
1he Debug Loolbar appears below or Lo Lhe righL o Lhe SLandard Loolbar.
6. Click Lhe SLarL Debugging buLLon on Lhe SLandard Loolbar.
1he program runs and Lhe Debug 1esL orm opens.
7. Remove Lhe 0 rom Lhe Age LexL box, Lype l4, and Lhen click Lhe 1esL buLLon.
1he program displays Lhe message "ou're a Leenager." So ar, Lhe program displays
Lhe correcL resulL.
8. 1ype l3 in Lhe Age LexL box, and Lhen click Lhe 1esL buLLon again.
1he program displays Lhe message "ou're noL a Leenager," as shown in Lhe ollowing
screen shoL.
.
9. Click Lhe uiL buLLon on Lhe orm, and Lhen open Lhe Code FdiLor.
l0. Move Lhe mouse poinLer Lo Lhe Margin lndicaLor bar (Lhe gray bar jusL beyond Lhe leL
margin o Lhe Code FdiLor window), nexL Lo Lhe sLaLemenL Ae = 1ext3cx1.1ext in Lhe
3uttcn1_Clicl evenL procedure, and Lhen click Lhe bar Lo seL a breakpoinL.
2l4 Part II Programmng fundamentaIs
1he breakpoinL immediaLely appears in red. See Lhe ollowing screen shoL or Lhe
breakpoinL's locaLion and shape.
ll. Click Lhe SLarL Debugging buLLon Lo run Lhe program again.
1he orm opens jusL as beore, and you can conLinue your LesLs.
l2. 1ype l3 in Lhe Age LexL box, and Lhen click 1esL.
visual 8asic opens Lhe Code FdiLor again and displays Lhe 3uttcn1_Clicl evenL
procedure-Lhe program code currenLly being execuLed by Lhe compiler. 1he
sLaLemenL LhaL you selecLed as a breakpoinL is highlighLed in yellow, and an arrow
appears in Lhe Margin lndicaLor bar, as shown in Lhe ollowing screen shoL.
ou can Lell LhaL visual SLudio is now in debugging mode because Lhe word
"Debugging" appears in iLs LiLle bar. ln debugging mode, you have an opporLuniLy Lo
see how Lhe logic in your program is evaluaLed.
Chapter 8 Debuggng VsuaI asc Programs 2l5
Note ou can also enLer debugging mode in a visual 8asic program by placing Lhe Stc
sLaLemenL in your program code where you'd like Lo pause execuLion. 1his is an older, buL
sLill reliable, meLhod or enLering debugging mode in a visual 8asic program.
l3. Place Lhe poinLer over Lhe Ae variable in Lhe Code FdiLor.
visual SLudio displays Lhe message "Age | 0" and a Liny pin icon appears nexL Lo Lhe
value. While you're in debugging mode, you can display Lhe value o variables or
properLies by simply holding Lhe mouse poinLer over Lhe value in Lhe program code.
Ae 1ext3cx1 LexL
box-LhaL sLaLemenL is Lhe nexL sLaLemenL Lhe compiler will evaluaLe.
1he pin icon is a new eaLure o visual SLudio 200 LhaL leLs you pin Lhe value o
an expression somewhere in Lhe lDF while you are debugging. 1he pinned expression
is called a Dctc1i, and Lhere are our commands on Lhe Debug menu LhaL are relaLed
Lo Lhis eaLure. 1ry using a DaLa1ip now Lo waLch Lhe value o Lhe Ae variable.
l4. Click Lhe pin icon Lo creaLe a DaLa1ip or Lhe Ae variable in Lhe lDF.
l5. Hold Lhe mouse over Lhe DaLa1ip LhaL appears unLil Lhree small buLLons are displayed
nexL Lo Lhe Ae variable.
our screen will look like Lhe ollowing.

UnLil you remove Lhis DaLa1ip, iL will display Lhe value o Lhe Ae variable in Lhe lDF.
l you click Lhe Unpin From Source buLLon, Lhe Ae variable will remain in iLs currenL
posiLion in Lhe lDF, even i you scroll Lhe Code FdiLor window up or down. 1he
CommenL buLLon leLs you add a descripLive commenL Lo Lhe Ae variable, and Lhe
Close buLLon leLs you remove Lhe DaLa1ip rom Lhe lDF.
l6. Click Lhe Close buLLon nexL Lo Lhe DaLa1ip Lo remove Lhe Ae variable and iLs value
o 0 or now.
As you can see, Lhis is a handy way Lo waLch variables change in a program as iL runs,
and you should eel ree Lo use DaLa1ips whenever you debug your code. 8eore you
use Lhem exclusively, however, experimenL wiLh some addiLional Lechniques in Lhe
ollowing sLeps.
2l6 Part II Programmng fundamentaIs
Note l you add more Lhan a ew DaLa1ips Lo your program code, be sure Lo use Lhe Clear
All DaLa1ips, lmporL DaLa1ips, and FxporL DaLa1ips commands on Lhe Debug menu. 1hese
eaLures are especially useul in large developmenL projecLs where you have numerous
variables and expressions and many DaLa1ips acLive. ln parLicular, Lhe lmporL and FxporL
commands will allow you Lo Lranser DaLa1ips rom one projecL Lo Lhe nexL.
l7. ConLinue by clicking Lhe SLep lnLo buLLon on Lhe SLandard Loolbar.
1he SLep lnLo buLLon execuLes Lhe nexL program sLaLemenL in Lhe evenL procedure (Lhe
line LhaL's currenLly highlighLed). 8y clicking Lhe SLep lnLo buLLon, you can see how Lhe
program sLaLe changes when jusL one more program sLaLemenL is evaluaLed. l you hold
Lhe poinLer over Lhe Ae variable now, you'll see LhaL iL conLains a value o 8.
l8. On Lhe Debug menu, poinL Lo Windows, and Lhen click AuLos.
1p l you are using visual 8asic 200 Fxpress, Lhe AuLos window is noL available.
AlLernaLively, you can open Lhe Locals window Lo see Lhe value o Lhe Age variable.
1he Locals window displays a dierenL seL o variables.
1he Windows submenu provides access Lo Lhe enLire seL o debugging windows in
visual SLudio. 1he AuLos window shows Lhe sLaLe o variables and properLies currenLly
being used (noL only Lhe properLies you are currenLly seLLing, buL oLhers as well).
As you can see in Lhe ollowing screen shoL, Lhe Ae variable holds a value o 8
and Lhe 1ext3cx1.1ext properLy holds a sLring o "8".
Chapter 8 Debuggng VsuaI asc Programs 2l7
l9. Click Lhe SLep lnLo buLLon Lwice more.
1he lj sLaLemenL evaluaLes Lhe condiLional expression Lo False, and Lhe compiler moves
Lo Lhe llse sLaLemenL in Lhe decision sLrucLure. Here's our bug-Lhe decision sLrucLure
logic is incorrecL because a 8-year-old is a Leenager. Do you recognize Lhe problem
>=
LesL or Lhis boundary case o 8.
logic error.
20. Click Lhe SLop Debugging buLLon on Lhe SLandard Loolbar.
2l. ln Lhe Code FdiLor, add Lhe equal Lo sign (= lj sLaLemenL so
LhaL iL reads.
I f Age >= 13 And Age < 20 Then
22. Run Lhe program again and LesL your soluLion, paying parLicular aLLenLion Lo Lhe
numbers 2, 8, 9, and 20-Lhe boundary, or "ringe," cases LhaL are likely Lo cause
problems.
Remember LhaL you sLill have a breakpoinL seL, so you'll enLer debugging mode
when you run Lhe program again. Use Lhe SLep lnLo buLLon Lo waLch Lhe program
lj sLaLemenL, and use Lhe AuLos window Lo Lrack Lhe value
o your variables as you compleLe Lhe LesLs. When Lhe orm opens, enLer a new
value and Lry Lhe LesL again. (ou'll learn how Lo remove Lhe breakpoinL laLer in
Lhe chapLer.)
23.
buLLon on Lhe SLandard Loolbar Lo end Lhe program.
in a program.
Tracking VariabIes by Using a watch window
1he AuLos window is useul or examining Lhe sLaLe o cerLain variables and properLies as
Lhey're evaluaLed by Lhe compiler, buL iLems in Lhe AuLos window ersist, or mainLain Lheir
values, only or Lhe currenL sLaLemenL (Lhe sLaLemenL highlighLed in Lhe debugger) and Lhe
previous sLaLemenL (Lhe sLaLemenL jusL execuLed). When your program goes on Lo execuLe
code LhaL doesn'L use Lhe variables, Lhey disappear rom Lhe AuLos window.
1o view Lhe conLenLs o variables and properLies thrcuhcut Lhe execuLion o a program,
you need Lo use a WaLch window, a special visual SLudio Lool LhaL Lracks imporLanL
values or you so long as you're working in debugging mode. ln visual SLudio, you can
Chapter 8 Debuggng VsuaI asc Programs 2l9
5. SelecL Lhe expression Ae < 29, and Lhen add iL Lo Lhe WaLch window.
Ae < 29 is a condiLional expression, and you can use Lhe WaLch window Lo display iLs
logical, or 8oolean, value. our WaLch window looks like Lhis.
Now sLep Lhrough Lhe program code Lo see how Lhe values in Lhe WaLch window change.
6. Click Lhe SLep lnLo buLLon on Lhe SLandard Loolbar.
1p lnsLead o clicking Lhe SLep lnLo buLLon on Lhe SLandard Loolbar, you can press Lhe
F8 key on Lhe keyboard.
1he Ae variable is seL Lo 20, and Lhe Ae < 29 condiLion evaluaLes Lo False. 1hese values
are displayed in red Lype in Lhe WaLch window because Lhey've jusL been updaLed.
7. Click Lhe SLep lnLo buLLon Lhree more Limes.
1he llse clause is execuLed in Lhe decision sLrucLure, and Lhe value o Lhe 1ext3cx2.1ext
properLy in Lhe WaLch window changes Lo "ou're noL a Leenager." 1his condiLional LesL
is operaLing correcLly.
LesL rom Lhe WaLch window.
8. Click Lhe Age < 20 row in Lhe WaLch window, and Lhen press Lhe DFLF1F key.
visual SLudio removes Lhe value rom Lhe WaLch window. As you can see, adding
and removing values rom Lhe WaLch window is a speedy process.
Leave visual SLudio running in debugging mode or now. ou'll conLinue using Lhe WaLch
window in Lhe nexL secLion.
Chapter 8 Debuggng VsuaI asc Programs 22l
3. SelecL Lhe 1exL visualizer opLion.
visual SLudio opens a dialog box and displays Lhe conLenLs o Lhe 1ext3cx2.1ext properLy.
our screen looks like Lhis.
AlLhough Lhis parLicular resulL oers liLLle more Lhan Lhe WaLch window did, Lhe
1ext properLy o
a mulLiline LexL box objecL is displayed, or when you examine variables or properLies
conLaining daLabase inormaLion or Web documenLs. ou'll experimenL wiLh Lhese more
sophisLicaLed daLa Lypes laLer in Lhe book.
4. Click Close Lo close Lhe 1exL visualizer dialog box.
Leave visual SLudio running in debugging mode. ou'll conLinue using Lhe WaLch window
in Lhe nexL secLion, Loo.
1p ln debugging mode, visualizers also someLimes appear in Lhe Code FdiLor nexL Lo
inLeresLing variables or properLies. l a visualizer appears, eel ree Lo click iL Lo geL more
inormaLion abouL Lhe underlying daLa, as you did in Lhe previous exercise.
Using the lmmediate and Command windows
So ar, you've used Lhe visual SLudio debugging Lools LhaL allow you Lo enLer debugging
mode, execuLe code one sLaLemenL aL a Lime, and examine Lhe value o imporLanL variables,
properLies, and expressions in your program. Now you'll learn how Lo change Lhe value o
a variable by using Lhe lmmediaLe window, and you'll learn how Lo run commands, such as
Save All or PrinL, wiLhin Lhe visual SLudio lDF by using Lhe Command window. 1he windows
conLain scroll bars, so you can execuLe more Lhan one command and view Lhe resulLs by
using Lhe arrow keys.
Chapter 8 Debuggng VsuaI asc Programs 223
1he WaLch window looks like Lhis.
As you can see, boLh iLems now conLain new values, and Lhis gives you Lhe opporLuniLy
Lo LesL Lhe program urLher.
5. Click Lhe SLep lnLo buLLon Lwo Limes Lo display Lhe Debug 1esL orm again.
NoLice LhaL Lhe 1ext properLy o Lhe 1ext3cx2 objecL has been changed, as you direcLed,
buL Lhe 1ext properLy o Lhe 1ext3cx1 objecL sLill holds a value o 20 (noL 7). 1his is
because you changed Lhe Ae variable in Lhe program, noL Lhe properLy LhaL assigned
a value Lo Ae. our screen looks like Lhe ollowing screen shoL.
1he lmmediaLe window has many uses-iL provides an excellenL companion Lo Lhe WaLch
.
Switching to the Command window
1he LexL-based Command window oers a complemenL Lo Lhe visual SLudio lmmediaLe
window. ReminiscenL o Lhe UNlX or MS-DOS command prompL, iL can be used Lo run
inLerace commands in Lhe visual SLudio lDF. For example, enLering Lhe lile.ScveAll command
. (1his command is Lhe
equivalenL o Lhe Save All command on Lhe File menu.) l you already have Lhe lmmediaLe
window open, you can swiLch beLween Lhe lmmediaLe and Lhe Command windows by
enLering Lhe >cmJ and immeJ commands, respecLively. ou can also click Lhe view menu,
poinL Lo OLher Windows, and Lhen click Command Window Lo open Lhe Command window.
ou'll pracLice using Lhe Command window in Lhe ollowing exercise.
227
ChapLer 9
1rappng frrors by Usng
Structured frror HandIng
After compIetng ths chapter, you wII be abIe to:
Manage run-Lime errors by using Lhe 1ry . . . Cctch error handler.
Cctch
sLaLemenL.
WriLe complex error handlers LhaL use Lhe lxceticn objecL and Lhe Messce properLy.
8uild nesLed 1ry . . . Cctch sLaLemenLs.
Use error handlers in combinaLion wiLh deensive programming Lechniques.
Leave error handlers premaLurely by using Lhe lxit 1ry sLaLemenL.
ln ChapLer 8, "Debugging visual 8asic Programs," you learned how Lo recognize run-Lime
errors in a MicrosoL visual 8asic program and how Lo locaLe logic errors and oLher deecLs
in your program code by using Lhe MicrosoL visual SLudio 200 debugging Lools. ln Lhis
chapLer, you'll learn how Lo build blocks o code LhaL handle run-Lime errors, also reerred
Lo as exceticns, which occur as a resulL o normal operaLing condiLions-or example, errors
prinLer. 1hese rouLines are called structureJ errcr hcnJlers (or structureJ exceticn hcnJlers),
and you can use Lhem Lo recognize run-Lime errors, suppress unwanLed error messages,
and adjusL program condiLions so LhaL your applicaLion can regain conLrol and run again.
ForLunaLely, visual 8asic oers Lhe powerul 1ry . . . Cctch code block or handling errors.
ln Lhis chapLer, you'll learn how Lo Lrap run-Lime errors by using 1ry . . . Cctch code blocks,
and you'll learn how Lo use Lhe lxceticn . ou'll
also learn how Lo use mulLiple Cctch
nesLed 1ry . . . Cctch code blocks, and use Lhe lxit 1ry sLaLemenL Lo exiL a 1ry . . . Cctch code
block premaLurely. 1he programming Lechniques you'll learn are similar Lo Lhe sLrucLured
error handlers provided by Lhe mosL advanced programming languages, such as Java
and C--. 1he mosL reliable, or rcbust, visual 8asic programs use several error handlers
Lo manage unoreseen circumsLances and provide users wiLh consisLenL and Lrouble-ree
compuLing experiences.
Processing rrors by Using the 7ry . . . Cotch Statement
A rcrcm crcsh is an unexpecLed problem rom which a program can'L recover. ou mighL
a
Chapter 9 1rappng frrors by Usng Structured frror HandIng 23l
.
digiLal cameras, and oLher deLachable media Lypically use "F," "F," or higher leLLers or
Lhe drive.
6. WiLh your CD or DvD sLill in drive D (or equivalenL), click Lhe SLarL Debugging buLLon
on Lhe SLandard Loolbar Lo run Lhe program.
1he orm or Lhe projecL opens, as shown here.
7. Click Lhe Check Drive buLLon on Lhe orm.
1he program loads Lhe Fileopen.
picLure box, as shown in Lhe ollowing screen shoL.
232 Part II Programmng fundamentaIs
1he SizeMcJe
Lhe enLire picLure box objecL. Now see whaL happens when Lhe CD or DvD isn'L in Lhe
.
8. Remove Lhe CD or DvD rom Lhe drive.
l you are using a dierenL media Lype, remove iL now. l you are LesLing wiLh a
removable sLorage device, ollow your usual procedure Lo saely remove or Lurn iL o,
and remove Lhe media conLaining Fileopen.bmp.
9. Click Lhe Check Drive buLLon again on Lhe orm.
unhcnJleJ
exceticn, which causes Lhe program Lo crash. visual SLudio enLers debugging mode,
highlighLing Lhe problem sLaLemenL.
our screen will look like Lhis.
NoLice how helpul visual SLudio is Lrying Lo be here, by oering LroubleshooLing
Lips Lo assisL you in locaLing Lhe source o Lhe unhandled excepLion LhaL has sLopped
Lhe program.
message LhaL is displayed aL Lhe Lop o Lhe dialog box.
l0. Click Lhe SLop Debugging buLLon on Lhe SLandard Loolbar Lo close Lhe program.
1he developmenL environmenL reLurns.
Now you'll modiy Lhe code Lo handle Lhis plausible error scenario in Lhe uLure.
238 Part II Programmng fundamentaIs
Cat ch ex As Syst em. I O. Fi l eNot FoundExcept i on ' i f Fi l e Not Found er r or
MsgBox( " Check pat hname and di sc dr i ve" )
Cat ch ex As Out Of Memor yExcept i on ' i f Out Of Memor y er r or
MsgBox( " I s t hi s r eal l y a bi t map?" , , ex. Message)
Cat ch ex As Except i on
MsgBox( " Pr obl eml oadi ng f i l e", , ex. Message)
End Tr y
1his code has Lhree Cctch sLaLemenLs. l Lhe lileNctlcunJlxceticn occurs during Lhe
a message box. l Lhe OutOjMemcrylxceticn occurs-probably Lhe resulL o loading
displayed. (l geL Lhis error i l accidenLally Lry Lo open a MicrosoL Word documenL in
a picLure box objecL by using Lhe lrcmlile meLhod.)
Cctch sLaLemenL handles all oLher run-Lime errors LhaL could poLenLially
prinLs a
rom Lhe Messce properLy in Lhe LiLle bar o Lhe message box.
2. Click Lhe SLarL Debugging buLLon Lo run Lhe program.
3. Remove Lhe CD or DvD rom drive D.
4. Click Lhe Check Drive buLLon.
1he error handler displays Lhe error message "Check paLhname and disc drive" in a
message box. Cctch sLaLemenL works.
5. Click OK, and Lhen click Lhe Close buLLon on Lhe orm Lo end Lhe program.
6. lnserL Lhe CD or DvD again, and Lhen use Windows Fxplorer or anoLher Lool Lo
copy a . For example, copy
a Word documenL or a MicrosoL Fxcel spreadsheeL Lo Lhe CD or DvD.
we hope) in your program's picLure box objecL. (l your CD or DvD soLware or drive
.)
7. ln Lhe Code FdiLor, change Lhe name o Lhe Fileopen. lrcmlile program
in drive D.
Lype o run-Lime error-an OuL o Memory excepLion, which occurs when visual
8asic
a picLure box.
Chapter 9 1rappng frrors by Usng Structured frror HandIng 239
8. Run Lhe program again, and Lhen click Lhe Check Drive buLLon.
1he error handler displays Lhe ollowing error message.
NoLice LhaL l have used Lhe Messce properLy Lo display a shorL descripLion o Lhe
problem ("OuL o memory.") in Lhe message box LiLle bar. Using Lhis properLy in your
error handler can give Lhe user a clearer idea o whaL has happened.
9. Click OK, and Lhen click Lhe Close buLLon on Lhe orm Lo sLop Lhe program.
l0. .bmp in Lhe lrcmlile meLhod. (ou'll use iL in Lhe
nexL exercise.)
1he Cctch sLaLemenL is very powerul. 8y using Cctch in combinaLion wiLh Lhe lxceticn
objecL and Messce properLy, you can wriLe sophisLicaLed error handlers LhaL recognize
and respond Lo several Lypes o excepLions.
kaising Your Own rrors
run-Lime errors in a program wiLh a Lechnique called thrcwin, or rcisin, excepLions. 1o
accomplish Lhis, you use Lhe 1hrcw sLaLemenL. For example, Lhe ollowing synLax uses
Lhe 1hrcw sLaLemenL Lo produce an excepLion and Lhen handles Lhe excepLion by using
a Cctch sLaLemenL.
Tr y
Thr ow New Except i on( " Ther e was a pr obl em")
Cat ch ex As Except i on
MsgBox( ex. Message)
End Tr y
When you learn how Lo wriLe your own procedures, you can generaLe your own errors
by using Lhis Lechnique and reLurn Lhem Lo Lhe calling rouLine.
Specfyng a Retry Perod
AnoLher sLraLegy LhaL you can use in an error handler is Lo Lry an operaLion a ew Limes and
Lhen disable iL i Lhe problem isn'L resolved. For example, in Lhe ollowing exercise, a
1ry . . . Cctch block employs a counLer variable named Retries Lo Lrack Lhe number o Limes
Lhe message "Please inserL Lhe disc in drive D!" is displayed, and aLer Lhe second Lime, Lhe
error handler disables Lhe Check Drive buLLon. 1he Lrick Lo Lhis Lechnique is declaring Lhe
Chapter 9 1rappng frrors by Usng Structured frror HandIng 24l
5. Click Lhe Check Drive buLLon.
1he error handler displays Lhe error message "Please inserL Lhe disc in drive D!"
in a message box, as shown here. 8ehind Lhe scenes, Lhe Retries variable is also
incremenLed Lo .
6. Click OK, and Lhen click Lhe Check Drive buLLon again.
1he Retries variable is seL Lo 2, and Lhe message "Please inserL Lhe disc in drive D!"
appears again.
7. Click OK, and Lhen click Lhe Check Drive buLLon a Lhird Lime.
1he Retries variable is incremenLed Lo 8, and Lhe llse clause is execuLed. 1he message
"File Load eaLure disabled" appears, as shown here.
8. Click OK in Lhe message box.
1he Check Drive buLLon is disabled on Lhe orm, as shown here.
242 Part II Programmng fundamentaIs
1he error handler has responded Lo Lhe disc drive problem by allowing Lhe user a ew
. (ln oLher
words, Lhe user can no longer click Lhe buLLon.) 1his disabling acLion sLops uLure
run-Lime errors, alLhough Lhe program mighL no longer uncLion exacLly as iL was
originally designed.
9. Click Lhe Close buLLon on Lhe orm Lo sLop Lhe program.
Usng Nested Try . . . Cctch Iocks
ou can also use nesLed 1ry . . . Cctch code blocks in your error handlers. For example, Lhe
ollowing disc drive error handler uses a second 1ry . . . Cctch
Tr y
Pi ct ur eBox1. I mage = _
Syst em. Dr awi ng. Bi t map. Fr omFi l e( "d: \ f i l eopen. bmp" )
Cat ch
MsgBox( " I nser t t he di sc i n dr i ve D, t hen cl i ck OK! ")
Tr y
Pi ct ur eBox1. I mage = _
Syst em. Dr awi ng. Bi t map. Fr omFi l e( " d: \ f i l eopen. bmp" )
Cat ch
MsgBox( "Fi l e Load f eat ur e di sabl ed")
But t on1. Enabl ed = Fal se
End Tr y
End Tr y
l Lhe user inserLs Lhe disc in Lhe drive as a resulL o Lhe message prompL, Lhe second 1ry
.
second Cctch
and Lhe buLLon is disabled.
ln general, nesLed 1ry . . . Cctch error handlers work well so long as you don'L have Loo many
LesLs or reLries Lo manage. l you do need Lo reLry a problemaLic operaLion many Limes, use
a variable Lo Lrack your reLries, or develop a uncLion conLaining an error handler LhaL can
be called repeaLedly rom your evenL procedures. (For more inormaLion abouL creaLing
uncLions, see ChapLer 0.)
Comparing rror HandIers with Defensive
Programming Techniques
Frror handlers aren'L Lhe only mechanism or proLecLing a program againsL run-Lime errors. For
example, Lhe ollowing program code uses Lhe lile.lxists meLhod in Lhe System.lO namespace
o Lhe .
opened.
I f Fi l e. Exi st s( "d: \ f i l eopen. bmp" ) Then
Pi ct ur eBox1. I mage = _
Chapter 9 1rappng frrors by Usng Structured frror HandIng 243
Syst em. Dr awi ng. Bi t map. Fr omFi l e( "d: \ f i l eopen. bmp" )
El se
MsgBox( " Cannot f i nd f i l eopen. bmp on dr i ve D. " )
End I f
1his lj . . . 1hen sLaLemenL isn'L an acLual error handler because iL doesn'L prevenL a run-Lime
error rom halLing a program. lnsLead, iL's a validaLion Lechnique LhaL some programmers
call Jejensive rcrcmmin. lL uses a handy meLhod in Lhe .NF1 Framework class library Lo
bejcre iL's acLually aLLempLed in Lhe program code. And in
.NF1 Framework meLhod
is acLually asLer Lhan waiLing or visual 8asic Lo issue an excepLion and recover rom a
run-Lime error using an error handler.
Note 1o geL Lhis parLicular program logic Lo work, Lhe ollowing sLaLemenL musL be included
in Lhe declaraLions secLion aL Lhe very Lop o Lhe orm's program code Lo make reerence Lo Lhe
.NF1 Framework class library LhaL's being invoked.
I mpor t s Syst em. I O
For more inormaLion abouL uLilizing Lhe lmcrts sLaLemenL Lo use Lhe objecLs, properLies,
and meLhods in Lhe .NF1 Framework class libraries, see ChapLer 5, "visual 8asic variables and
Formulas, and Lhe .NF1 Framework."
When should you use deensive programming Lechniques, and when should you use
sLrucLured error handlers 1he answer is really LhaL you should use a combinaLion o deensive
programming and sLrucLured error-handling Lechniques in your code. Deensive programming
. As l menLioned earlier
when discussing Lhe lj . . . 1hen code block, Lhe lile.lxists meLhod is acLually asLer Lhan using
a 1ry . . . Cctch error handler, so iL also makes sense Lo use a deensive programming Lechnique
i perormance issues are involved. ou should use deensive programming logic or errors
LhaL you expecL Lo occur requenLly in your program. Use sLrucLured error handlers or errors
LhaL you don'L expecL Lo occur very oLen. SLrucLured error handlers are essenLial i you have
more Lhan one condiLion Lo LesL and i you wanL Lo provide Lhe user wiLh numerous opLions
or responding Lo Lhe error. SLrucLured error handlers also allow you Lo graceully handle errors
LhaL you aren'L even aware o.
One Step lurther. The xit 7ry Statement
ou've learned a loL abouL error handlers in Lhis chapLer, now you're ready Lo puL Lhem Lo
work in your own programs. 8uL beore you move on Lo Lhe nexL chapLer, here's one more
synLax opLion or 1ry . . . Cctch lxit 1ry sLaLemenL.
lxit 1ry is a quick and slighLly abrupL Lechnique or exiLing a 1ry . . . Cctch code block
premaLurely. l you've wriLLen visual 8asic programs beore, you mighL noLice iLs similariLy Lo
Lhe lxit lcr and lxit Sub sLaLemenLs, which you can use Lo leave a sLrucLured rouLine early.
247
ChapLer 0
Creatng ModuIes and Procedures
After compIetng ths chapter, you wII be abIe to:
Fmploy sLrucLured programming Lechniques and creaLe modules conLaining public
.
PracLice using public variables LhaL have a global scope.
procedures.
.
Pass argumenLs Lo procedures by value and by reerence.
cs 3uttcn1_Clicl,
1imer1_1icl, and lcrm1_lccJ .
ln MicrosoL visual 8asic programming, all execuLable sLaLemenLs musL be placed inside
some procedure, only general declaraLions and insLrucLions Lo Lhe compiler can be placed
ouLside a procedure's scope. ln Lhis chapLer, you'll conLinue Lo organize your programs by
breaking compuLing Lasks inLo discreLe logical uniLs.
ou'll sLarL by learning how Lo creaLe mcJules, which are separaLe areas wiLhin a program
LhaL conLain global, or ublic, variables and FuncLion and Sub procedures. ou'll learn how Lo
declare and use public variables, and you'll learn how Lo build general-purpose procedures
LhaL save coding Lime and can be used in more Lhan one projecL. 1he skills you'll learn will be
especially applicable Lo larger programming projecLs and Leam developmenL eorLs.
working with ModuIes
As you wriLe longer programs, you're likely Lo have several orms and evenL procedures
LhaL use some o Lhe same variables and rouLines. 8y deaulL, variables are lcccl Lo an evenL
procedure-Lhey can be read or changed only wiLhin Lhe evenL procedure in which Lhey
were creaLed. ou can also declare variables aL Lhe Lop o a orm's program code and give
Lhe variables a greaLer scope LhroughouL Lhe orm. However, i you creaLe mulLiple orms in
a projecL, Lhe variables declared aL Lhe Lop o a orm are valid only in Lhe orm in which Lhey
were declared. Likewise, evenL procedures are by deaulL declared as privaLe and are only
local Lo Lhe orm in which Lhey are creaLed. For example, you can'L call Lhe 3uttcn1_Clicl
evenL procedure rom a second orm named Form2 i Lhe evenL procedure is declared Lo be
privaLe Lo Form. (ou'll learn how Lo add addiLional orms Lo your projecL in ChapLer 4,
"Managing Windows Forms and ConLrols aL Run 1ime.")
Chapter l0 Creatng ModuIes and Procedures 249
4. Click Lhe Add buLLon.
visual 8asic adds Module Lo your projecL. 1he module appears in Lhe Code FdiLor,
as shown here.
250 Part II Programmng fundamentaIs
1he MeLhod Name lisL box indicaLes LhaL Lhe general declaraLions secLion o Lhe
module is open. variables and procedures declared in Lhis secLion are available Lo Lhe
enLire projecL. (ou'll Lry declaring variables and procedures laLer.)
5. Double-click Lhe SoluLion Fxplorer LiLle bar Lo undock Lhe SoluLion Fxplorer window.
As shown previously, SoluLion Fxplorer lisLs Lhe module you added Lo Lhe program in
Lhe lisL o componenLs or Lhe projecL.
name o Lhe module. .
6. SelecL Module.vb in Lhe SoluLion Fxplorer.
7. Double-click Lhe ProperLies window LiLle bar Lo undock iL.
1he ProperLies window displays Lhe properLies or Module.vb, as shown here.
8ecause a module conLains only code, iL has only a ew properLies. 8y using Lhe mosL
lile Ncme
describe iLs purpose. Cive Lhis idenLiying label some LhoughL because laLer you mighL
wanL Lo incorporaLe your module inLo anoLher soluLion. 1he remaining properLies or
Lhe module are useul or more sophisLicaLed projecLs-you don'L need Lo worry abouL
Lhem now.
8. Change Lhe lile Ncme properLy Lo Math lunctions.vb
sounds impressive, and Lhen press FN1FR. (l'm granLing you considerable leeway here
because Lhis projecL is simply or LesLing purposes-you won'L acLually creaLe maLh
uncLions or any oLher "conLenL" or Lhe module, and laLer you'll discard iL.)
and Lhe Code FdiLor.
254 Part II Programmng fundamentaIs
5. ln SoluLion Fxplorer, click Form.vb, click Lhe view Designer buLLon, and Lhen
double-click Lhe Spin buLLon.
1he 3uttcn1_Clicl evenL procedure or Lhe Spin buLLon appears in Lhe Code FdiLor.
6. 1ype Lhe ollowing sLaLemenLs below Lhe 3ee() sLaLemenL in Lhe evenL procedure.
Wi ns = Wi ns + 1
l bl Wi ns. Text = "Wi ns: " & Wi ns
1his parL o Lhe program code incremenLs Lhe Wins public variable i a 7 appears
during a spin. 1he second sLaLemenL uses Lhe concaLenaLion operaLor (&) Lo assign
a sLring Lo Lhe lblWins objecL in Lhe ormaL Wins. X, in which X is Lhe number o wins.
1he compleLed evenL procedure looks like Lhis.
7. Click Lhe Save All buLLon on Lhe SLandard Loolbar Lo save all your changes Lo disk.
Save All saves your module changes as well as Lhe changes on your orm and in your
evenL procedures.
8. Click Lhe SLarL Debugging buLLon Lo run Lhe program.
9. Click Lhe Spin buLLon unLil you have won a ew Limes.
1he Wins label keeps Lrack o your jackpoLs. Fach Lime you win, iL incremenLs Lhe LoLal
by . ALer eighL spins, l had Lhe ouLpuL shown on Lhe ollowing page.
Note 1he exacL number o wins will be dierenL each Lime you run Lhe program due Lo
Lhe RcnJcmize sLaLemenL in Lhe lcrm1_lccJ evenL procedure.
Chapter l0 Creatng ModuIes and Procedures 255
l0. Click Fnd Lo exiL Lhe program.
1he public variable Wins was useul in Lhe previous procedure because iL mainLained iLs
value Lhrough several calls Lo Lhe 3uttcn1_Clicl evenL procedure. l you had declared
Wins locally in Lhe 3uttcn1_Clicl evenL procedure, Lhe variable would have reseL each
Lime, jusL as Lhe Lrip odomeLer in your car does when you reseL iL. 8y using a public
variable in a module, you can avoid "hiLLing Lhe reseL buLLon."
PubIic VariabIes vs. lorm VariabIes
ln Lhe preceding exercise, you used a public variable Lo Lrack Lhe number o wins in
Lhe sloL machine program. AlLernaLively, you could have declared Lhe Wins variable aL
Lhe Lop o Lhe orm's program code. 8oLh Lechniques produce Lhe same resulL because
boLh a public variable and a variable declared in Lhe general declaraLions area o a orm
have scope LhroughouL Lhe enLire orm. Public variables are unique, however, because
Lhey mainLain Lheir values in cll Lhe orms and modules you use in a projecL-in oLher
words, in all Lhe componenLs LhaL share Lhe same projecL namespace. 1he projecL
. ou can view
or change Lhe namespace name by selecLing Lhe projecL in SoluLion Fxplorer, clicking
Lhe 1rack Wins ProperLies command on Lhe ProjecL menu, and Lhen examining or
changing Lhe LexL in Lhe RooL Namespace LexL box on Lhe ApplicaLion Lab.
Creating Procedures
Procedures provide a way Lo group a seL o relaLed sLaLemenLs Lo perorm a Lask. visual 8asic
includes Lwo primary Lypes o procedures.
luncticn rcceJures are called by name rom evenL procedures or oLher procedures.
OLen used or calculaLions, uncLion procedures can receive argumenLs and always
reLurn a value in Lhe uncLion name.
Sub rcceJures are called by name rom evenL procedures or oLher procedures. 1hey
. Unlike
256 Part II Programmng fundamentaIs
uncLions, however, Sub procedures don'L reLurn values associaLed wiLh Lheir parLicular
Sub procedure names. Sub procedures are Lypically used Lo receive or process inpuL,
display ouLpuL, or seL properLies.
many users, creaLing procedures in a module is more useul because Lhen Lhe procedures
have scope LhroughouL Lhe enLire projecL. 1his is especially Lrue or procedures LhaL mighL
be called enercl-urcse rcceJures
serve in a varieLy o programming conLexLs.
For example, imagine a program LhaL has Lhree mechanisms or prinLing a biLmap on
dierenL orms. a menu command named PrinL, a PrinL Loolbar buLLon, and a drag-
and-drop prinLer icon. ou could place Lhe same prinLing sLaLemenLs in each o Lhe Lhree
evenL procedures, or you could handle prinLing requesLs rom all Lhree sources by using one
procedure in a module.
Advantages of GeneraI-Purpose Procedures
1hey enable you Lo associaLe a requenLly used group o program sLaLemenLs
wiLh a amiliar name.
1hey eliminaLe repeaLed lines.
program execuLe iL any number o Limes.
1hey make programs easier Lo read. A program divided inLo a collecLion o
small parLs is easier Lo Lake aparL and undersLand Lhan a program made up o
one large parL.
1hey simpliy program developmenL. Programs separaLed inLo logical uniLs
are easier Lo design, wriLe, and debug. Plus, i you're wriLing a program in
a group seLLing, you can exchange procedures and modules insLead o enLire
programs.
1hey can be reused in oLher projecLs and soluLions. ou can easily incorporaLe
sLandard-module procedures inLo oLher programming projecLs.
1hey exLend Lhe visual 8asic language. Procedures oLen can perorm Lasks
LhaL can'L be accomplished by individual visual 8asic keywords or MicrosoL
.NF1 Framework meLhods.
writing lunction Procedures
A FuncLion procedure is a group o sLaLemenLs locaLed beLween a luncticn sLaLemenL
and an lnJ luncticn sLaLemenL. 1he sLaLemenLs in Lhe uncLion do Lhe meaningul work-
Lypically processing LexL, handling inpuL, or calculaLing a numeric value. ou execuLe, or ccll,
Chapter l0 Creatng ModuIes and Procedures 257
a uncLion in a program by placing Lhe uncLion name in a program sLaLemenL along wiLh any
required argumenLs.
Aruments are Lhe daLa used Lo make uncLions work, and Lhey musL be included beLween
parenLheses and be separaLed by commas. 8asically, using a FuncLion procedure is exacLly
like using a builL-in uncLion or meLhod such as lnt, RnJ, or lrcmlile.
1p FuncLions declared in modules are public by deaulL. As a resulL, you can use Lhem in any
evenL procedure wiLhin Lhe projecL.
functon Syntax
1he basic synLax o a uncLion is as ollows.
Funct i on Funct i onName( [ ar gument s] ) As Type
f unct i on st at ement s
[ Ret ur n val ue]
End Funct i on
1he ollowing synLax iLems are imporLanL.
luncticnNcme is Lhe name o Lhe uncLion you're creaLing.
As 1ye . lL is sLrongly
. l you don'L provide a Lype, Lhe
reLurn Lype deaulLs Lo Object.
cruments is a lisL o opLional argumenLs (separaLed by commas) Lo be used in Lhe
uncLion. . (8y deaulL, visual
8asic adds Lhe 3yvcl keyword Lo each argumenL, indicaLing LhaL a copy o Lhe daLa is
passed Lo Lhe uncLion Lhrough Lhis argumenL buL LhaL any changes Lo Lhe argumenLs
won'L be reLurned Lo Lhe calling rouLine.)
juncticn stctements is a block o sLaLemenLs LhaL accomplishes Lhe work o Lhe uncLion.
Lhe uncLion, and Lhe remaining sLaLemenLs perorm Lhe work o Lhe uncLion.
Return allows you Lo reLurn a value Lo Lhe calling procedure and speciy LhaL value.
1he 1ye
keywords. When a Return sLaLemenL is execuLed, Lhe uncLion is exiLed, so i Lhere
are any uncLion sLaLemenLs aLer Lhe Return sLaLemenL, Lhese won'L be execuLed.
(AlLernaLively, you can reLurn a value Lo Lhe calling rouLine by assigning Lhe value Lo
luncticnNcme.)
8rackeLs ( [] ) enclose opLional synLax iLems. visual 8asic requires LhaL Lhose synLax
iLems are noL enclosed by brackeLs.
FuncLions always reLurn a value Lo Lhe calling procedure in Lhe uncLion's name
(luncticnNcme). For Lhis reason, Lhe lasL sLaLemenL in a uncLion is oLen an assignmenL
258 Part II Programmng fundamentaIs
luncticnNcme. For example, Lhe
FuncLion procedure 1ctcl1cx compuLes Lhe sLaLe and ciLy Laxes or an iLem and Lhen assigns
Lhe resulL Lo Lhe 1ctcl1cx name, as shown here.
Funct i on Tot al Tax( ByVal Cost as Si ngl e) As Si ngl e
Di mSt at eTax, Ci t yTax As Si ngl e
St at eTax = Cost * 0. 05 ' St at e t ax i s 5%
Ci t yTax = Cost * 0. 015 ' Ci t y t ax i s 1. 5%
Tot al Tax = St at eTax + Ci t yTax
End Funct i on
AlLernaLively, you can reLurn a value Lo Lhe calling procedure by using Lhe Return sLaLemenL,
as shown in Lhe ollowing uncLion declaraLion.
Funct i on Tot al Tax( ByVal Cost as Si ngl e) As Si ngl e
Di mSt at eTax, Ci t yTax As Si ngl e
St at eTax = Cost * 0. 05 ' St at e t ax i s 5%
Ci t yTax = Cost * 0. 015 ' Ci t y t ax i s 1. 5%
Ret ur n St at eTax + Ci t yTax
End Funct i on
l'll use Lhe Return synLax mosL oLen in Lhis book, buL you can use eiLher mechanism or re-
Lurning daLa rom a uncLion.
CaIIng a functon Procedure
1o call Lhe 1ctcl1cx uncLion in an evenL procedure, you use a sLaLemenL similar Lo Lhe
ollowing.
l bl Taxes. Text = Tot al Tax( 500)
1his sLaLemenL compuLes Lhe LoLal Laxes required or a S500 iLem and Lhen assigns Lhe resulL
Lo Lhe 1ext properLy o Lhe lbl1cxes objecL. 1he 1ctcl1cx uncLion can also Lake a variable as
an argumenL, as shown in Lhe ollowing sLaLemenLs.
Di mTot al Cost , Sal esPr i ce As Si ngl e
Sal esPr i ce = 500
Tot al Cost = Sal esPr i ce + Tot al Tax( Sal esPr i ce)
1he lasL sLaLemenL uses Lhe 1ctcl1cx uncLion Lo deLermine Lhe Laxes or Lhe number in Lhe
SclesPrice variable and Lhen adds Lhe compuLed Lax Lo SclesPrice Lo geL Lhe LoLal cosL o an
iLem. See how much clearer Lhe code is when a uncLion is used
Usng a functon to Perform a CaIcuIaton
ln Lhe ollowing exercise, you'll add a uncLion Lo Lhe 1rack Wins program Lo calculaLe Lhe win
raLe in Lhe game-in oLher words, Lhe percenLage o spins in which one or more 7s appear.
1o perorm Lhe calculaLion, you'll add a uncLion named HitRcte and a public variable named
260 Part II Programmng fundamentaIs
Per cent = Hi t s / Tr i es
Ret ur n For mat ( Per cent , "0. 0%")
End Funct i on
an lnJ luncticn sLaLemenL. ALer you Lype Lhe remainder o Lhe uncLion's code, your
screen looks like Lhis.
1he HitRcte uncLion deLermines Lhe percenLage o wins by dividing Lhe Hits argumenL
by Lhe 1ries argumenL and Lhen adjusLs Lhe appearance o Lhe resulL by using Lhe
lcrmct uncLion. 1he HitRcte uncLion is declared as a sLring because Lhe lcrmct
uncLion reLurns a sLring value. 1he Hits and Lhe 1ries argumenLs are placeholders or
Lhe Lwo shorL inLeger variables LhaL will be passed Lo Lhe uncLion during Lhe uncLion
call. 1he HitRcte uncLion is general-purpose enough Lo be used wiLh any shorLer
inLeger numbers or variables, noL only wiLh Wins and Sins.
6. Display Lhe orm again, and Lhen double-click Lhe Spin buLLon on Lhe Form.vb orm Lo
bring up Lhe 3uttcn1_Clicl evenL procedure.
7. 8elow Lhe ourLh line o Lhe evenL procedure (lcbelJ.1ext = CStr(lnt(RnJ() * 19))), Lype
Lhe ollowing sLaLemenL.
Spi ns = Spi ns + 1
1his sLaLemenL incremenLs Lhe Sins variable each Lime Lhe user clicks Spin, and new
numbers are placed in Lhe spin windows.
8. Scroll down in Lhe Code FdiLor, and Lhen, beLween Lhe lnJ lj and Lhe lnJ Sub sLaLemenLs,
Lype Lhe ollowing sLaLemenL as Lhe lasL line in Lhe 3uttcn1_Clicl evenL procedure.
l bl Rat e. Text = Hi t Rat e( Wi ns, Spi ns)
As you Lype Lhe HitRcte uncLion, noLice how visual SLudio auLomaLically displays Lhe
names and Lypes o Lhe argumenLs or Lhe HitRcte uncLion you jusL builL (a nice Louch).
1he purpose o Lhis sLaLemenL is Lo call Lhe HitRcte uncLion by using Lhe Wins and
Lhe Sins variables as argumenLs. 1he resulL reLurned is a percenLage in sLring ormaL,
262 Part II Programmng fundamentaIs
writing Sub Procedures
A Sub procedure is similar Lo a FuncLion procedure, excepL LhaL a Sub procedure doesn'L
reLurn a value associaLed wiLh iLs name. Sub procedures are Lypically used Lo geL inpuL
rom Lhe user, display or prinL inormaLion, or manipulaLe several properLies associaLed wiLh
a condiLion. Sub procedures can also be used Lo process and updaLe variables received in
an argumenL lisL during a procedure call and pass back one or more o Lhese values Lo Lhe
calling program.
Sub Procedure Syntax
1he basic synLax or a Sub procedure is.
Sub Pr ocedur eName( [ ar gument s] )
pr ocedur e st at ement s
End Sub
1he ollowing synLax iLems are imporLanL.
PrcceJureNcme is Lhe name o Lhe Sub procedure you're creaLing.
cruments is a lisL o opLional argumenLs (separaLed by commas i Lhere's more Lhan
one) Lo be used in Lhe Sub procedure. Fach argumenL should also be declared as
a . (visual SLudio adds Lhe 3yvcl keyword by deaulL Lo each argumenL,
indicaLing LhaL a copy o Lhe daLa is passed Lo Lhe uncLion Lhrough Lhis argumenL buL
LhaL any changes Lo Lhe argumenLs won'L be reLurned Lo Lhe calling rouLine.)
rcceJure stctements is a block o sLaLemenLs LhaL accomplishes Lhe work o Lhe
procedure.
ln Lhe Sub procedure call, Lhe number and Lype o argumenLs senL Lo Lhe procedure musL
maLch Lhe number and Lype o argumenLs in Lhe Sub procedure declaraLion, and Lhe enLire
group musL be enclosed in parenLheses.
during Lhe procedure, Lhe updaLed variables aren'L passed back Lo Lhe program unless Lhe
3yRej keyword. Sub procedures declared in
a module are public by deaulL, so Lhey can be called by any evenL procedure in a projecL.
Important All calls Lo a Sub procedure musL include parenLheses aLer Lhe procedure
name. A seL o empLy parenLheses is required even i no argumenLs are being passed Lo Lhe
procedure.
For example, Lhe ollowing Sub procedure receives a sLring argumenL represenLing a person's
name and uses a LexL box Lo wish LhaL person happy birLhday. l Lhis Sub procedure is
declared in a module, iL can be called rom any evenL procedure in Lhe program.
Chapter l0 Creatng ModuIes and Procedures 263
Sub Bi r t hdayGr eet i ng ( ByVal Per son As St r i ng)
Di mMsg As St r i ng
I f Per son <> " " Then
Msg = " Happy bi r t hday " & Per son & " ! "
El se
Msg = " Name not speci f i ed. "
End I f
MsgBox( Msg, , "Best Wi shes")
End Sub
1he 3irthJcyCreetin procedure receives Lhe name Lo be greeLed by using Lhe Perscn
argumenL, a sLring variable received by value during Lhe procedure call. l Lhe value o
Perscn isn'L empLy, or null
be displayed wiLh a Ms3cx uncLion. l Lhe argumenL is null, Lhe procedure displays Lhe
."
CaIIng a Sub Procedure
1o call a Sub procedure in a program, you speciy Lhe name o Lhe procedure, and Lhen lisL
Lhe argumenLs required by Lhe Sub procedure. For example, Lo call Lhe 3irthJcyCreetin
procedure, you could Lype Lhe ollowing sLaLemenL.
Bi r t hdayGr eet i ng( " Rober t " )
ln Lhis example, Lhe 3irthJcyCreetin procedure would inserL Lhe name "RoberL" inLo
a message sLring, and Lhe rouLine would display Lhe ollowing message box.
1he space-saving advanLages o a procedure become clear when you call Lhe procedure
many Limes using a variable, as shown in Lhe example below.
Di mNewName As St r i ng
Do
NewName = I nput Box( "Ent er a name f or gr eet i ng. " , " Bi r t hday Li st " )
Bi r t hdayGr eet i ng( NewName)
Loop Unt i l NewName = " "
Here Lhe user can enLer as many names or birLhday greeLings as he or she likes. 1he nexL
exercise gives you a chance Lo pracLice using a Sub procedure Lo handle anoLher Lype o
inpuL in a program.
266 Part II Programmng fundamentaIs
9. 1ype Lhe ollowing AJJNcme procedure beLween Lhe McJule McJule1 and lnJ McJule
sLaLemenLs.
Sub AddName( ByVal TeamAs St r i ng, ByRef Ret ur nSt r i ng As St r i ng)
Di mPr ompt , Nm, Wr apChar act er As St r i ng
Pr ompt = "Ent er a " & Team& " empl oyee. "
Nm= I nput Box( Pr ompt , " I nput Box" )
Wr apChar act er = Chr ( 13) + Chr ( 10)
Ret ur nSt r i ng = Nm& Wr apChar act er
End Sub
1his general-purpose Sub procedure uses Lhe lnut3cx uncLion Lo prompL Lhe user or
an employee name. lL receives Lwo argumenLs during Lhe procedure call. 1ecm, a sLring
conLaining Lhe deparLmenL name, and ReturnStrin, an empLy sLring variable LhaL will
conLain Lhe ormaLLed employee name. ReturnStrin is declared wiLh Lhe 3yRej keyword
so LhaL any changes made Lo Lhis argumenL in Lhe procedure will be passed back Lo Lhe
calling rouLine Lhrough Lhe argumenL.
8eore Lhe employee name is reLurned, carriage reLurn and lineeed characLers are
appended Lo Lhe sLring so LhaL each name in Lhe LexL box will appear on iLs own line.
ou can use Lhis general Lechnique in any sLring Lo creaLe a new line.
our Code FdiLor looks like Lhis.
l0.
(Lhe buLLon below Lhe Sales LexL box). 1ype Lhe ollowing sLaLemenLs in Lhe btnScles_
Clicl evenL procedure.
Di mSal esPosi t i on As St r i ng = ""
AddName( "Sal es" , Sal esPosi t i on)
t xt Sal es. Text = t xt Sal es. Text & Sal esPosi t i on
1he call Lo Lhe AJJNcme Sub procedure includes one argumenL passed by value
(Scles) and one argumenL passed by reerence (SclesPcsiticn). 1he lasL line uses Lhe
argumenL passed by reerence Lo add LexL Lo Lhe txtScles LexL box. 1he concaLenaLion
operaLor (&) adds Lhe new name Lo Lhe end o Lhe LexL in Lhe LexL box.
268 Part II Programmng fundamentaIs
3. Click Lhe OK buLLon Lo add Lhe name Lo Lhe Sales LexL box.
.
4. Click Lhe Add Name buLLon under Lhe MarkeLing LexL box, Lype kaymond long in Lhe
MarkeLing inpuL box, and Lhen press FN1FR.
1he name appears in Lhe MarkeLing LexL box. our screen looks like Lhis.
5. FnLer a ew more names in each o Lhe LexL boxes. 1his is your chance Lo creaLe your
.
Fach name appears on iLs own line in Lhe LexL boxes. 1he LexL boxes don'L scroll
auLomaLically, so you won'L see every name you've enLered i you enLer more names
. ou can use Lhe scroll bars Lo access names LhaL aren'L visible.
6. .
ou've demonsLraLed LhaL one Sub procedure can manage inpuL Lasks rom Lwo or more
evenL procedures. Using Lhis basic concepL as a sLarLing poinL, you can now creaLe more
sophisLicaLed programs LhaL use Sub and FuncLion procedures as organizing Lools and LhaL
place common Lasks in logical uniLs LhaL can be called over and over again.
One Step lurther. Passing Arguments by VaIue
and by keference
ln Lhe discussion o Sub and FuncLion procedures, you learned LhaL argumenLs are passed
Lo procedures by value or by reerence. Using Lhe 3yvcl keyword indicaLes LhaL variables
should be passed Lo a procedure by value (Lhe deaulL). Any changes made Lo a variable
passed in by value aren'L passed back Lo Lhe calling procedure. However, as you learned
in Lhe 1exL 8ox Sub program, using Lhe 3yRej keyword indicaLes LhaL variables should be
passed Lo a procedure by reerence, meaning LhaL any changes made Lo Lhe variable in Lhe
Chapter l0 Creatng ModuIes and Procedures 269
procedure are passed back Lo Lhe calling rouLine.
advanLages, so long as you're careul noL Lo change a variable uninLenLionally in a procedure.
For example, consider Lhe ollowing Sub procedure declaraLion and call.
Sub Cost Pl usI nt er est ( ByRef Cost As Si ngl e, ByRef Tot al As Si ngl e)
Cost = Cost * 1. 05 ' add 5%t o cost . . .
Tot al = I nt ( Cost ) ' t hen make i nt eger and r et ur n
End Sub
.
.
.
Di mPr i ce, Tot al Pr i ce As Si ngl e
Pr i ce = 100
Tot al Pr i ce = 0
Cost Pl usI nt er est ( Pr i ce, Tot al Pr i ce)
MsgBox( Pr i ce & " at 5% i nt er est i s " & Tot al Pr i ce)
ln Lhis example, Lhe programmer passes Lwo single-precision variables by reerence Lo Lhe
CosLPluslnLeresL procedure. Price and 1ctclPrice. 1he programmer plans Lo use Lhe updaLed
1ctclPrice variable in Lhe subsequenL Ms3cx call buL has unorLunaLely orgoLLen LhaL Lhe
Price variable was also updaLed in an inLermediaLe sLep in Lhe CosLPluslnLeresL procedure.
(8ecause Price was passed by reerence, changes Lo Ccst auLomaLically resulL in Lhe same
changes Lo Price.) 1his produces Lhe ollowing erroneous resulL when Lhe program is run.
However, Lhe programmer probably wanLed Lo show Lhe ollowing message.
easiesL way is Lo declare Lhe Ccst argumenL by using Lhe 3yvcl keyword, as shown in Lhe
ollowing program sLaLemenL.
Sub Cost Pl usI nt er est ( ByVal Cost As Si ngl e, ByRef Tot al As Si ngl e)
273
ChapLer
Usng Arrays to Manage Numerc
and Strng Data
After compIetng ths chapter, you wII be abIe to:
.
Preserve array daLa when you redimension arrays.
Use arrays in your code Lo manage large amounLs o daLa.
Use Lhe Scrt and Reverse meLhods in Lhe Arrcy class Lo reorder arrays.
Use Lhe Prcress3cr conLrol in your programs Lo show how long a Lask is Laking.
Managing inormaLion in a MicrosoL visual 8asic applicaLion is an imporLanL Lask, and as
your programs become more subsLanLial, you'll need addiLional Lools Lo sLore and process
daLa. A quick-and-dirLy approach Lo daLa managemenL in programs is Lo sLore and reLrieve
SLring Processing." However, Lhe mosL comprehensive approach is sLoring and reLrieving
inormaLion by using daLabases, and you'll sLarL learning how Lo inLegraLe visual 8asic
programs wiLh daLabases in ChapLer 8, "CeLLing SLarLed wiLh ADO.NF1."
ln Lhis chapLer, you'll learn how Lo organize variables and oLher inormaLion inLo useul
conLainers called crrcys. ou'll learn how Lo sLreamline daLa-managemenL Lasks wiLh
o daLa. ou'll learn how Lo redimension arrays and preserve Lhe daLa in arrays when you
decide Lo change an array's size. 1o demonsLraLe how large arrays can be processed, you'll
use Lhe Scrt and Reverse meLhods in Lhe MicrosoL .NF1 Framework Arrcy class Lo reorder
an array conLaining random six-digiL inLeger values. Finally, you'll learn Lo use Lhe Prcress3cr
conLrol Lo give your users an indicaLion o how long a process (array-relaLed or oLherwise) is
Laking. 1he Lechniques you'll learn provide a solid inLroducLion Lo Lhe daLabase programming
Lechniques LhaL you'll explore laLer in Lhe book.
working with Arrays of VariabIes
ln Lhis secLion, you'll learn abouL arrays, a useul meLhod or sLoring almosL any amounL
o daLa during program execuLion. Arrays are a powerul and Lime-LesLed mechanism or
sLoring logically relaLed values in a program. 1he developers o 8ASlC, Pascal, C, and oLher
popular programming languages incorporaLed arrays inLo Lhe earliesL versions o Lhese
producLs Lo reer Lo a group o values by using one name and Lo process Lhose values
individually or collecLively.
Chapter ll Usng Arrays to Manage Numerc and Strng Data 275
1p Arrays LhaL conLain a seL number o elemenLs are called . Arrays LhaL conLain
a variable number o elemenLs (arrays LhaL can expand during Lhe execuLion o Lhe program) are
called Jyncmic crrcys.
DecIarng a fxed-Sze Array
Di mAr r ayName( Di m1I ndex, Di m2I ndex, . . . ) As Dat aType
1he ollowing argumenLs are imporLanL.
Dim is Lhe keyword LhaL declares Lhe array. Use Public insLead i you place Lhe array
in a module.
ArrcyNcme is Lhe variable name o Lhe array.
Dim1lnJex
o elemenLs minus .
Dim2lnJex is Lhe upper bound o Lhe second dimension o Lhe array, which is Lhe
number o elemenLs minus . (AddiLional dimensions can be included i Lhey're
separaLed by commas.)
Dctc1ye is a keyword corresponding Lo Lhe Lype o daLa LhaL will be included in Lhe
array.
For example, Lo declare a one-dimensional sLring array named lmlcyees LhaL has room
or 0 employee names (numbered 0 Lhrough 9), you can Lype Lhe ollowing in an evenL
procedure.
Di mEmpl oyees( 9) As St r i ng
ln a module, Lhe same array declaraLion looks like Lhis.
Publ i c Empl oyees( 9) As St r i ng
ou can also expliciLly speciy Lhe lower bound o Lhe array as zero by using Lhe ollowing
code in an evenL procedure.
Di mEmpl oyees( 0 To 9) As St r i ng
1his "0 Lo 9" synLax is included Lo make your code more readable-newcomers Lo your
program will undersLand immediaLely LhaL Lhe lmlcyees array has 0 elemenLs numbered
0 Lhrough 9. However, Lhe lower bound o Lhe array musL always be zero. ou cannoL use Lhis
synLax Lo creaLe a dierenL lower bound or Lhe array.
276 Part II Programmng fundamentaIs
Settng Asde Memory
When you creaLe an array, visual 8asic seLs aside room or iL in memory. 1he ollowing screen
shoL shows concepLually how Lhe 0-elemenL lmlcyees array is organized. 1he elemenLs are
numbered 0 Lhrough 9 raLher Lhan Lhrough 0 because array indexes always sLarL wiLh 0.
9
8
7
6
5
4
8
2

0
Fmployees
1o declare a public Lwo-dimensional array named SccrebccrJ LhaL has room or Lwo rows
and nine columns o Shcrt inLeger daLa, you can Lype Lhis sLaLemenL in an evenL procedure
or aL Lhe Lop o Lhe orm.
Di mScor eboar d( 1, 8) As Shor t
Using Lhe synLax LhaL emphasizes Lhe lower (zero) bound, you can also declare Lhe array
as ollows.
Di mScor eboar d( 0 To 1, 0 To 8) As Shor t
ALer you declare such a Lwo-dimensional array and visual 8asic seLs aside room or iL in
memory, you can use Lhe array in your program as i iL were a Lable o values, as shown in
Lhe ollowing screen shoL. (ln Lhis case, Lhe array elemenLs are numbered 0 Lhrough and 0
Lhrough 8.)
0
0 2 8 4 5 6 7 8

Rows
Columns
Scoreboard
Chapter ll Usng Arrays to Manage Numerc and Strng Data 277
Workng wth Array fIements
1o reer Lo an elemenL o an array, you use Lhe array name and an array index enclosed
in parenLheses. 1he index musL be an inLeger or an expression LhaL resulLs in an inLeger.
For example, Lhe index could be a number such as 5, an inLeger variable such as num, or
an expression such as num-1. (1he counLer variable o a lcr . . . Next loop is oLen used.)
For example, Lhe ollowing sLaLemenL assigns Lhe value "Leslie" Lo Lhe elemenL wiLh an
index o 5 in Lhe lmlcyees array example in Lhe previous secLion.
Empl oyees( 5) = "Lesl i e"
1his sLaLemenL produces Lhe ollowing resulL in our lmlcyees array.
9
8
7
6
5
4
8
2

0
Fmployees
Lesile
Similarly, Lhe ollowing sLaLemenL assigns Lhe number 4 Lo row 0, column 2 (Lhe Lop o Lhe
Lhird inning) in Lhe SccrebccrJ array example in Lhe previous secLion.
Scor eboar d( 0, 2) = 4
1his sLaLemenL produces Lhe ollowing resulL in our SccrebccrJ array.
0
0 2
4
8 4 5 6 7 8

Rows
Columns
Scoreboard
ou can use Lhese indexing Lechniques Lo assign or reLrieve any array elemenL.
278 Part II Programmng fundamentaIs
DecIarng an Array and Assgnng It IntaI VaIues
lL is also possible Lo declare an array and assign iL iniLial values aL Lhe same Lime. 1his
sLaLemenL synLax is somewhaL parallel Lo whaL you learned abouL assigning an iniLial value Lo
a variable aL Lhe momenL o declaraLion, and iL is useul when you know in advance jusL how
large an array needs Lo be and whaL iLs conLenLs are.
1o creaLe an array in Lhis manner, you use whaL is called an crrcy litercl. An array liLeral consisLs o
a lisL o comma-separaLed values LhaL are enclosed in braces ((}). When using Lhis synLax, you can
eiLher supply Lhe array Lype or leL visual 8asic use tye injerence Lo deLermine whaL Lype Lhe array
should be. For example, Lo declare a one-dimensional array named Wciters o Lype Strin
iL wiLh seven names, you would use Lhe ollowing synLax.
Di mWai t er s( ) As St r i ng = {"Ben" , " Sue" , " Lee" , " Ki m", " Pat ", " Eve", "Sal "}
NoLe LhaL Lhe size o Lhis array is deLermined auLomaLically by visual 8asic when Wciters is
declared. ln addiLion, i you don'L indicaLe an array Lype, visual 8asic will use Lype inerence
Lo deLermine Lhe righL array daLa Lype or you. Obviously i all Lhe values are Lhe same
Lype, iL should be clear Lo Lhe compiler whaL daLa Lype should be used or Lhe array. 8uL i
Lhere is a mixLure o Lypes, such as an assorLmenL o inLeger, single, and double-precision
numbers, MicrosoL visual SLudio will pick a daLa Lype or Lhe array LhaL is large enough Lo
accommodaLe all Lhe values. ln many cases, Lhis will be Lhe daLa Lype Object because Object
.
1he ollowing sLaLemenL declares an array named lnvestments and uses an array liLeral Lo add
our values Lo Lhe array when iL is creaLed.
Lhe array elemenLs and deLermines LhaL in Lhis case, Lhe Object Lype is mosL appropriaLe.
Di mI nvest ment s( ) = {5000, 20350. 50, 499. 99, 10000}
Note l Lhe compiler's OpLion lner seLLing is seL Lo On, Lhe Dcuble
Lhe above sLaLemenL is execuLed. See ChapLer or help adjusLing Lhis seLLing.
A mulLi-dimensional array can also be declared in Lhis way, alLhough you need Lo Lake care
.
For example, Lhe ollowing sLaLemenL declares a Lwo-dimensional array named Rectcnle
and assigns our values Lo Lhe array.
Di mRect angl e = {{10, 20}, {50, 60}}
1his array has Lwo rows and Lwo columns. Array elemenL (0, 0-LhaL is, row 0, column 0)
now conLains a value o 0 and elemenL (0, -LhaL is, row 0, column ) now conLains
Chapter ll Usng Arrays to Manage Numerc and Strng Data 279
a value o 20. Also, noLice LhaL Lhere are Lhree seLs o braces used in Lhe declaraLion,
Lhese braces clariy which elemenLs are being assigned and keep Lhem in Lhe proper order.
1he ollowing screen shoL shows Lhe visual SLudio Code FdiLor wiLh Lhe Lhree examples o
array liLeral declaraLions LhaL l have shown in Lhis secLion. NoLice LhaL Lhe Code FdiLor is in
debugging mode (or break mode) and Lhe WaLch window is visible and shows Lhe conLenLs
o Lhe Wciters array. (Debugging mode and Lhe WaLch window were inLroduced in ChapLer 8,
"Debugging visual 8asic Programs.") A lcr . . . Next loop is also being used Lo display Lhe
conLenLs o Lhe Wciters array in a message box, alLhough you cannoL see Lhe resulLs o LhaL
loop on Lhis screen. lcr . . . Next loops are excellenL Lools Lo process arrays, as you'll see in Lhe
nexL secLion.
Creatng a fxed-Sze Array to HoId 1emperatures
1he ollowing exercise uses a one-dimensional array named 1emerctures Lo record Lhe
daily high LemperaLures or a seven-day week. 1he program demonsLraLes how you can use
an array Lo sLore and process a group o relaLed values on a orm. 1he 1emerctures array
variable is declared aL Lhe Lop o Lhe orm, and Lhen LemperaLures are assigned Lo Lhe array
by using an lnut3cx uncLion and a lcr . . . Next loop, which you learned abouL in ChapLer 7,
Chapter ll Usng Arrays to Manage Numerc and Strng Data 28l
our orm looks like Lhe one shown in Lhe ollowing screen shoL.
7. ln SoluLion Fxplorer, click Lhe view Code buLLon Lo display Lhe Code FdiLor.
8. Scroll Lo Lhe Lop o Lhe orm's program code, and direcLly below Lhe Public Clcss lcrm1
sLaLemenL, Lype Lhe ollowing array declaraLion.
Di mTemper at ur es( 0 To 6) As Si ngl e
1his sLaLemenL creaLes an array named 1emerctures (o Lhe Lype Sinle) LhaL conLains
seven elemenLs numbered 0 Lhrough 6. 8ecause Lhe array has been declared aL Lhe Lop
o Lhe orm, iL is available in all Lhe evenL procedures in Lhe orm.
9. Display Lhe orm again, and Lhen double-click Lhe FnLer 1emps buLLon (3uttcn1).
1he 3uttcn1_Clicl evenL procedure appears in Lhe Code FdiLor.
l0. 1ype Lhe ollowing program sLaLemenLs Lo prompL Lhe user or LemperaLures and Lo
load Lhe inpuL inLo Lhe array.
Di mPr ompt , Ti t l e As St r i ng
Di mi As Shor t
Pr ompt = " Ent er t he day' s hi gh t emper at ur e. "
For i = 0 To UBound( Temper at ur es)
Ti t l e = " Day " & ( i + 1)
Temper at ur es( i ) = I nput Box( Pr ompt , Ti t l e)
Next
1he lcr . . . Next loop uses Lhe shorL inLeger counLer variable i as an array index Lo load
LemperaLures inLo array elemenLs 0 Lhrough 6. lcr
loop synLax.
For i = 0 t o 6
282 Part II Programmng fundamentaIs
Lo process Lhe array, l chose a slighLly more complex synLax involving Lhe U3cunJ
. 1he lcr loop consLrucLion.
For i = 0 To UBound( Temper at ur es)
deLermines Lhe upper bound o Lhe array by using Lhe U3cunJ sLaLemenL. 1his
lcr
loop auLomaLically adjusLs iLsel Lo Lhe new array size.
lnut3cx uncLion,
which displays Lhe currenL day by using Lhe lcr loop counLer.
ll. Display Lhe orm again, and Lhen double-click Lhe Display 1emps buLLon (3uttcn2).
l2. 1ype Lhe ollowing sLaLemenLs in Lhe 3uttcn2_Clicl evenL procedure.
Di mResul t As St r i ng
Di mi As Shor t
Di mTot al As Si ngl e = 0
Resul t = " Hi gh t emper at ur es f or t he week: " & vbCr Lf & vbCr Lf
For i = 0 To UBound( Temper at ur es)
Resul t = Resul t & " Day " & ( i + 1) & vbTab & _
Temper at ur es( i ) & vbCr Lf
Tot al = Tot al + Temper at ur es( i )
Next
Resul t = Resul t & vbCr Lf & _
" Aver age t emper at ur e: " & For mat ( Tot al / 7, " 0. 0" )
Text Box1. Text = Resul t
1his evenL procedure uses a lcr . . . Next loop Lo cycle Lhrough Lhe elemenLs in Lhe
array, and iL adds each elemenL in Lhe array Lo a sLring variable named Result, which is
declared aL Lhe Lop o Lhe evenL procedure. l've used several liLeral sLrings, consLanLs,
and sLring concaLenaLion operaLors (&) Lo pad and ormaL Lhe sLring by using carriage
reLurns (vbCrlj), Lab characLers (vb1cb), and headings. 1he vbCrlj consLanL, used
. 1he vb1cb
Lo puL some disLance beLween Lhe day and LemperaLure values in Lhe Result sLring. AL
Lhe end o Lhe evenL procedure, an average or Lhe LemperaLures is deLermined, and
1ext properLy o Lhe LexL box objecL, as shown in Lhis
sLaLemenL.
Text Box1. Text = Resul t
l3. Click Lhe Save All buLLon on Lhe SLandard Loolbar Lo save Lhe projecL. Speciy Lhe
C.\vb0sbs\Chap older as Lhe locaLion.
Now you'll run Lhe program.
1p 1he compleLe Fixed Array program is locaLed in Lhe C.\vb0sbs\Chap\Fixed Array
older.
Chapter ll Usng Arrays to Manage Numerc and Strng Data 283
l4. Click Lhe SLarL Debugging buLLon on Lhe SLandard Loolbar Lo run Lhe program.
l5. Click Lhe FnLer 1emps buLLon, and when prompLed by Lhe lnut3cx uncLion, enLer seven
dierenL LemperaLures. (How abouL using Lhe LemperaLures rom your lasL vacaLion)
1he lnut3cx uncLion dialog box looks like Lhis.
l6. ALer you've enLered Lhe LemperaLures, click Lhe Display 1emps buLLon.
Using Lhe array, visual 8asic displays each o Lhe LemperaLures in Lhe LexL box and
prinLs an average aL Lhe boLLom. our screen looks similar Lo Lhis.
l7. Click Lhe Close buLLon on Lhe orm Lo end Lhe program.
Creatng a Dynamc Array
As you can see, arrays are quiLe handy or working wiLh lisLs o numbers, especially i you
process Lhem by using lcr . . . Next loops. 8uL whaL i you're noL sure how much array space
you'll need beore you run your program For example, whaL i you wanL Lo leL Lhe user
choose how many LemperaLures are enLered inLo Lhe Fixed Array program
Jyncmic
crrcy.
286 Part II Programmng fundamentaIs
9. Save your changes Lo disk.
1p On Lhe companion CD, l gave Lhis projecL a separaLe name Lo keep iL disLincL rom
Lhe Fixed Array projecL. 1he compleLe Dynamic Array projecL is locaLed in Lhe C.\vb0sbs\
Chap\Dynamic Array older.
l0. Click Lhe SLarL Debugging buLLon Lo run Lhe program.
ll. Click Lhe FnLer 1emps buLLon.
l2. 1ype 5 when you're prompLed or Lhe number o days you wanL Lo record, and Lhen
click OK.
l3. .
l4. .
.
our screen looks similar Lo Lhe ollowing screen shoL.
l5. Click Lhe Close buLLon on Lhe orm Lo end Lhe program.
Chapter ll Usng Arrays to Manage Numerc and Strng Data 287
ou've pracLiced using Lhe Lwo mosL common array Lypes in visual 8asic programming.
When you wriLe your own programs, you'll soon use much larger arrays, buL Lhe concepLs
are Lhe same, and you'll be amazed aL how asL visual 8asic can compleLe array-relaLed
compuLaLions.
Preserving Array Contents by Using ReDim Preserve
ln Lhe previous exercise, you used Lhe ReDim sLaLemenL Lo speciy Lhe size o a dynamic array
aL run Lime. However, one poLenLial shorLcoming associaLed wiLh Lhe ReDim sLaLemenL is LhaL
i you redimension an array LhaL already has daLa in iL, all Lhe exisLing daLa is irreLrievably
losL. ALer Lhe ReDim sLaLemenL is execuLed, Lhe conLenLs o a dynamic array are seL Lo
Lheir deaulL value, such as zero or null. Depending on your ouLlook, Lhis can be considered
a useul eaLure or empLying Lhe conLenLs o arrays, or iL can be an irksome eaLure LhaL
requires a workaround.
ForLunaLely, visual 8asic provides Lhe Preserve keyword, which you use Lo preserve Lhe
daLa in an array when you change iLs dimensions. 1he synLax or Lhe Preserve keyword is
as ollows.
ReDi mPr eser ve Ar r ayName( Di m1El ement s, Di m2El ement s, . . . )
ln such a ReDim sLaLemenL, Lhe array musL conLinue Lo have Lhe same number o dimensions
and conLain Lhe same Lype o daLa. ln addiLion, Lhere's a caveaL LhaL you can resize only
Lhe lasL array dimension. For example, i your array has Lwo or more dimensions, you can
change Lhe size o only Lhe lasL dimension and sLill preserve Lhe conLenLs o Lhe array.
(Single-dimension arrays auLomaLically pass Lhis LesL, so you can reely expand Lhe size o
dynamic arrays by using Lhe Preserve keyword.)
1he ollowing examples show how you can use Preserve Lo increase Lhe size o Lhe lasL
dimension in a dynamic array wiLhouL erasing any exisLing daLa conLained in Lhe array.
l you originally declared a dynamic sLring array named Philcschers by using Lhe synLax.
Di mPhi l osopher s( ) As St r i ng
you can redimension Lhe array and add daLa Lo iL by using code similar Lo Lhe ollowing.
ReDi mPhi l osopher s( 200)
Phi l osopher s( 200) = "Davi d Pr obst "
ou can expand Lhe size o Lhe Philcschers array Lo 80 elemenLs (0-800), and preserve Lhe
exisLing conLenLs, by using Lhe ollowing synLax.
ReDi mPr eser ve Phi l osopher s( 300)
288 Part II Programmng fundamentaIs
Usng ReDim for 1hree-DmensonaI Arrays
A more complex example involving a Lhree-dimensional array uses a similar synLax. lmagine
myCube in your program. ou can declare Lhe myCube array by using Lhe ollowing synLax.
Di mmyCube( , , ) As Si ngl e
ou can Lhen redimension Lhe array and add daLa Lo iL by using Lhe ollowing code.
ReDi mmyCube( 25, 25, 25)
myCube( 10, 1, 1) = 150. 46
aLer which you can expand Lhe size o Lhe Lhird dimension in Lhe array (while preserving Lhe
array's conLenLs) by using Lhis synLax.
ReDi mPr eser ve myCube( 25, 25, 50)
second dimensions cannoL be changed i you redimension Lhe array by using Lhe Preserve
keyword.
produces a run-Lime error when Lhe ReDim Preserve sLaLemenL is execuLed.
FxperimenL a liLLle wiLh ReDim Preserve, and see how you can use iL Lo make your own arrays
.
One Step lurther. Processing Large Arrays
by Using Methods in the Arroy CIass
ln previous secLions, you learned abouL using arrays Lo sLore inormaLion during program
execuLion. ln Lhis secLion, you'll learn abouL using meLhods in Lhe Arrcy class o Lhe .NF1
Framework, which you can use Lo quickly sorL, search, and reverse Lhe elemenLs in an array,
as well as perorm oLher uncLions. 1he sample program l've creaLed demonsLraLes how
Lhese eaLures work especially well wiLh very large arrays. ou'll also learn how Lo use Lhe
Prcress3cr conLrol.
1he Arrcy CIass
8asic or implemenLing arrays wiLhin user-creaLed programs. 1his Arrcy class also provides
a collecLion o meLhods LhaL you can use Lo manipulaLe arrays while Lhey are acLive in
programs. 1he mosL useul meLhods include Arrcy.Scrt, Arrcy.linJ, Arrcy.Reverse, Arrcy
.Ccy, and Arrcy.Clecr. ou can locaLe oLher inLeresLing meLhods by experimenLing wiLh
Lhe Arrcy class in Lhe Code FdiLor (by using MicrosoL lnLelliSense) and by checking Lhe
290 Part II Programmng fundamentaIs
1his orm looks similar Lo Lhe earlier projecLs in Lhis chapLer and eaLures a LesL box
or displaying array daLa. However, iL also conLains Lhree buLLons or manipulaLing
large arrays and a progress bar objecL LhaL gives Lhe user eedback during longer
array operaLions. (visual eedback is useul when compuLaLions Lake longer Lhan a ew
seconds Lo compleLe, and i you use Lhis code Lo sorL an array o 8,000 array elemenLs,
a slighL delay is ineviLable.)
3. Click Lhe progress bar on Lhe orm.
1he Prcress3cr1 objecL is selecLed on Lhe orm and is lisLed in Lhe ProperLies window.
l creaLed Lhe progress bar objecL by using Lhe Prcress3cr conLrol on Lhe Common
ConLrols Lab in Lhe 1oolbox. A progress bar is designed Lo display Lhe progress o
a compuLaLion by displaying an appropriaLe number o colored recLangles arranged
in a horizonLal progress bar.
recLangles. (ln Windows 7 and Windows visLa, a smooLhing eecL is applied so LhaL
eecL.
or insLalled programs wiLhin Windows. Now you can creaLe one in your own programs!
1he imporLanL properLies LhaL make a progress bar work are Lhe Minimum, Mcximum,
and vclue properLies, and Lhese are Lypically manipulaLed using program code. (1he
oLher progress bar properLies, which you can examine in Lhe ProperLies window, conLrol
how Lhe progress bar looks and uncLions.) ou can examine how Lhe Minimum and
Mcximum properLies are seL by looking aL Lhis program's lcrm1_lccJ evenL procedure.
4. Double-click Lhe orm Lo display Lhe lcrm1_lccJ evenL procedure.
ou see Lhe ollowing code.
Chapter ll Usng Arrays to Manage Numerc and Strng Data 29l
For a progress bar Lo display an accuraLe indicaLion o how long a compuLing Lask will
Lake Lo compleLe, you need Lo seL relaLive measuremenLs or Lhe beginning and Lhe end
o Lhe bar. 1his is accomplished wiLh Lhe Minimum and Mcximum properLies, which are
. As l have
Lhe
size o Lhe array, so l have used Lhe U3cunJ uncLion Lo reLurn LhaL number and seL Lhe
progress bar Mcximum properLy accordingly. 1he array LhaL we are manipulaLing in Lhis
exercise is RcnJArrcy, a lcn inLeger array declared iniLially Lo hold 500 elemenLs
(0 Lo 499).
5. Click Lhe SLarL Debugging buLLon Lo run Lhe program.
1he program runs, and Lhe Array Class SorLs orm opens on Lhe screen. ln iLs
lcrm1_lccJ evenL procedure, Lhe program declared an array named RcnJArrcy
and dimensioned iL wiLh 500 elemenLs. A progress bar objecL was calibraLed Lo Lrack
a calculaLion o 500 uniLs (Lhe array size), and Lhe number 500 appears Lo Lhe righL o
Lhe progress bar (Lhe work o a label objecL and Lhe U3cunJ uncLion).
6. Click Lhe Fill Array buLLon.
1he program loads RcnJArrcy wiLh 500 random numbers (derived by Lhe RnJ uncLion),
and displays Lhe numbers in Lhe LexL box.
. our
1he code LhaL produced Lhis resulL is Lhe 3uttcn1_Clicl evenL procedure, which conLains
Lhe ollowing program sLaLemenLs.
' Fi l l t he ar r ay wi t h r andomnumber s and di spl ay i n t ext box
Pr i vat e Sub But t on1_Cl i ck( ByVal sender As Syst em. Obj ect , _
ByVal e As Syst em. Event Ar gs) Handl es But t on1. Cl i ck
292 Part II Programmng fundamentaIs
Di mi As I nt eger
For i = 0 To UBound( RandAr r ay)
RandAr r ay( i ) = I nt ( Rnd( ) * 1000000)
Text Box1. Text = Text Box1. Text & RandAr r ay( i ) & vbCr Lf
Pr ogr essBar 1. Val ue = i ' move pr ogr ess bar
Next i
End Sub
1o geL random numbers LhaL are inLegers, l used Lhe lnt and RnJ uncLions LogeLher,
as l did in ChapLer 2, "WriLing our FirsL Program," and l mulLiplied Lhe random
number produced by RnJ by ,000,000 Lo geL whole numbers LhaL are six digiLs or
less. Assigning Lhese numbers Lo Lhe array is aciliLaLed by using a lcr . . . Next loop
wiLh an array index LhaL maLches Lhe loop counLer (i). Filling Lhe array is an exLremely
asL operaLion, Lhe slowdown (and Lhe need or Lhe progress bar) is caused by Lhe
assignmenL o array elemenLs Lo Lhe LexL box objecL one aL a Lime. 1his involves
updaLing a user inLerace componenL on Lhe orm 500 Limes, and Lhe process Lakes a
ew seconds Lo compleLe. lL is insLrucLional, however-Lhe delay provides a way or me
Lo show o Lhe Prcress3cr conLrol. Since Lhe progress bar objecL has been calibraLed
Lo use Lhe number o array elemenLs as iLs maximum, assigning Lhe loop counLer (i) Lo
Lhe progress bar's vclue properLy allows Lhe bar Lo display exacLly how much o Lhe
calculaLion has been compleLed.
7. Click Lhe SorL Array buLLon.
1he program ollows a similar process Lo sorL RcnJArrcy, Lhis Lime using Lhe Arrcy.
Scrt meLhod Lo reorder Lhe array in ascending order. (1he 500 elemenLs are lisLed rom
lowesL Lo highesL.) our screen looks like Lhis.
1he code LhaL produced Lhis resulL is Lhe 3uttcn2_Clicl evenL procedure, which conLains
Lhe ollowing program sLaLemenLs.
' Sor t t he ar r ay usi ng t he Ar r ay. Sor t met hod and di spl ay
Pr i vat e Sub But t on2_Cl i ck( ByVal sender As Syst em. Obj ect , _
Chapter ll Usng Arrays to Manage Numerc and Strng Data 293
ByVal e As Syst em. Event Ar gs) Handl es But t on2. Cl i ck
Di mi As I nt eger
Text Box1. Text = ""
Ar r ay. Sor t ( RandAr r ay)
For i = 0 To UBound( RandAr r ay)
Text Box1. Text = Text Box1. Text & RandAr r ay( i ) & vbCr Lf
Pr ogr essBar 1. Val ue = i ' move pr ogr ess bar
Next i
End Sub
1his evenL procedure clears Lhe LexL box objecL when Lhe user clicks Lhe SorL Array
buLLon, and Lhen sorLs Lhe array by using Lhe Arrcy.Scrt meLhod described earlier. 1he
sorLing process is very quick. Again, Lhe only slowdown is rebuilding Lhe LexL box objecL
one line aL a Lime in Lhe lcr . . . Next loop, a process LhaL is reporLed by Lhe Prcress3cr1
objecL and iLs vclue properLy. See how simple iL is Lo use Lhe Arrcy.Scrt meLhod
8. Click Lhe Reverse buLLon.
1he program uses Lhe Arrcy.Reverse meLhod Lo manipulaLe RcnJArrcy, reordering Lhe
.
Note 1his meLhod does noL always produce a sorLed lisL, Lhe array elemenLs are in
descending order only because RcnJArrcy had been sorLed previously in ascending order by
Lhe Arrcy.Scrt meLhod. (1o examine Lhe lisL more closely, use Lhe scroll bars or Lhe
arrow keys.)
our screen looks like Lhis.
294 Part II Programmng fundamentaIs
1he code LhaL produced Lhis resulL is Lhe 3uttcnJ_Clicl evenL procedure, which conLains
Lhe ollowing program sLaLemenLs.
' Rever se t he or der of ar r ay el ement s usi ng Ar r ay. Rever se
Pr i vat e Sub But t on3_Cl i ck( ByVal sender As Syst em. Obj ect , _
ByVal e As Syst em. Event Ar gs) Handl es But t on3. Cl i ck
Di mi As I nt eger
Text Box1. Text = ""
Ar r ay. Rever se( RandAr r ay)
For i = 0 To UBound( RandAr r ay)
Text Box1. Text = Text Box1. Text & RandAr r ay( i ) & vbCr Lf
Pr ogr essBar 1. Val ue = i ' move pr ogr ess bar
Next i
End Sub
1his evenL procedure is idenLical Lo Lhe 3uttcn2_Clicl evenL procedure, wiLh Lhe
ollowing excepLion.
Ar r ay. Sor t ( RandAr r ay)
has become.
Ar r ay. Rever se( RandAr r ay)
9. Click Lhe SLop Debugging buLLon Lo end Lhe program.
l0. Scroll Lo Lhe Lop o Lhe Code FdiLor, and locaLe Lhe program sLaLemenL LhaL declares Lhe
RcnJArrcy array.
Di mRandAr r ay( 0 To 499) As Long
ll. Replace 499 in Lhe array declaraLion sLaLemenL wiLh 2999.
1he sLaLemenL now looks like Lhis.
Di mRandAr r ay( 0 To 2999) As Long
l2.
aecLs program perormance.
8ecause processing 8,000 elemenLs is much more work, visual 8asic Lakes a liLLle while
RcnJArrcy.
However, Lhe progress bar keeps you posLed, and you can see LhaL wiLh jusL a small
change, you can adapL whaL you've learned in Lhis chapLer Lo dierenL siLuaLions.
(1he secreL was using Lhe U3cunJ uncLion Lo reporL Lhe size o Lhe array Lo Lhe
program's evenL procedures, raLher Lhan "hard coding" Lhe upper bound aL 499.)
ou can urLher experimenL wiLh Lhis program by adding a RcnJcmize sLaLemenL Lo Lhe
lcrm1_lccJ evenL procedure (Lo make Lhe resulLs Lruly random each Lime LhaL you run Lhe
program), or by Lrying addiLional array sizes and array Lypes. (1ry an array size o 00, 800,
2,000, or 5,000 elemenLs, or example.) l you Lry larger numbers, you'll evenLually exceed Lhe
amounL o daLa LhaL Lhe LexL box objecL can display, buL iL Lakes a while beore you exceed
Lhe maximum array size allowed by visual 8asic.
297
ChapLer 2
Workng wth CoIIectons
After compIetng ths chapter, you wII be abIe to:
ManipulaLe Lhe Ccntrcls collecLion on a orm.
Use a lcr lcch . . . Next loop Lo cycle Lhrough objecLs in a collecLion.
CreaLe your own collecLions or managing Web siLe URLs and oLher inormaLion.
.
ln Lhis chapLer, you'll learn how Lo use groups o objecLs called ccllecticns in a MicrosoL
visual 8asic program. ou'll learn how Lo manage inormaLion wiLh collecLions and process
collecLion objecLs by using lcr lcch . . . Next loops. When you combine collecLion-processing
skills wiLh whaL you learned abouL arrays in ChapLer , "Using Arrays Lo Manage Numeric
and SLring DaLa," you'll have much o whaL you need Lo know abouL managing daLa
collecLions exposed by MicrosoL visual SLudio 200 and popular Windows applicaLions.
working with Object CoIIections
ln Lhis secLion, you'll learn abouL collecLions, a powerul mechanism or conLrolling objecLs
and oLher daLa in a visual 8asic program. 1he MicrosoL .NF1 Framework mainLains several
sLandard objecL collecLions LhaL you can use when you wriLe your programs. ou can use
visual SLudio Lo browse your sysLem or collecLions and oLher applicaLion objecLs.
. 8uL did you
also know LhaL visual 8asic considers Lhe objecLs Lo be members o Lhe same group ln visual
SLudio Lerminology, Lhe enLire seL o objecLs on a orm is called Lhe Ccntrcls ccllecticn. 1he
Ccntrcls collecLion is creaLed auLomaLically when you open a new orm, and when you add
objecLs Lo Lhe orm, Lhey become parL o LhaL collecLion.
Fach collecLion in a program has iLs own name so LhaL you can reerence iL as a disLincL uniL
in Lhe program code. For example, you use Lhe Ccntrcls name Lo reerence Lhe collecLion o
objecLs on a orm. 1his grouping meLhod is similar Lo Lhe way arrays group a lisL o elemenLs
LogeLher under one name, and like visual 8asic arrays, Lhe Ccntrcls collecLion is zero-based.
l you have more Lhan one orm in a projecL, you can creaLe public variables associaLed wiLh
Lhe orm names and use Lhose variables Lo dierenLiaLe one Ccntrcls collecLion rom anoLher.
(ou'll learn more abouL using public variables Lo sLore orm daLa in ChapLer 4, "Managing
Windows Forms and ConLrols aL Run 1ime.") ou can even add conLrols programmaLically Lo
Lhe Ccntrcls collecLion in a orm.
298 Part II Programmng fundamentaIs
Referencng Objects n a CoIIecton
ou can reerence Lhe objecLs in a collecLion, or Lhe individual members o Lhe collecLion,
by speciying Lhe inJex csiticn o Lhe objecL in Lhe group. visual 8asic sLores collecLion
objecLs in Lhe reverse order o LhaL in which Lhey were creaLed, so you can use an objecL's
"birLh order" Lo reerence Lhe objecL individually, or you can use a loop Lo sLep Lhrough
several objecLs. For example, Lo idenLiy Lhe lasL objecL creaLed on a orm, you can speciy
Lhe 0 (zero) index, as shown in Lhis example.
Cont r ol s( 0) . Text = " Busi ness"
1his sLaLemenL seLs Lhe 1ext properLy o Lhe lasL objecL on Lhe orm Lo "8usiness." (1he
second-Lo-lasL objecL creaLed has an index o , Lhe Lhird-Lo-lasL objecL creaLed has an index
o 2, and so on.) Considering Lhis logic, iL's imporLanL LhaL you don'L always associaLe a
parLicular objecL on Lhe orm wiLh an index value because i a new objecL is added Lo Lhe
collecLion, Lhe new objecL Lakes Lhe 0 index spoL and Lhe remaining objecL indexes are
incremenLed by .
1he ollowing lcr . . . Next loop uses a message box Lo display Lhe names o Lhe lasL our
conLrols added Lo a orm.
Di mi As I nt eger
For i = 0 To 3
MsgBox( Cont r ol s( i ) . Name)
Next i
NoLe LhaL l've direcLed Lhis loop Lo cycle rom 0 Lo 8 because Lhe lasL conLrol objecL added Lo
a orm is in Lhe 0 posiLion.
wriLing such a loop.
Wrtng For Lcch . . . Next Loops
AlLhough you can reerence Lhe members o a collecLion individually, Lhe mosL useul way
Lo work wiLh objecLs in a collecLion is Lo process Lhem as a group. ln acL, Lhe reason LhaL
. For example, you
mighL wanL Lo display, move, sorL, rename, or resize an enLire collecLion o objecLs aL once.
1o handle Lhis kind o Lask, you can use a special loop called lcr lcch . . . Next Lo cycle
Lhrough objecLs in a collecLion one aL a Lime. A lcr lcch . . . Next loop is similar Lo a
lcr . . . Next loop. When a lcr lcch . . . Next loop is used wiLh Lhe Ccntrcls collecLion, iL
looks like Lhis.
Di mCt r l Var As Cont r ol
. . .
For Each Ct r l Var I n Cont r ol s
pr ocess obj ect
Next Ct r l Var
1he Ctrlvcr variable is declared as a Ccntrcl Lype and represenLs Lhe currenL objecL in Lhe
lcr lcch . . . Next loop. Ccntrcls (noLe Lhe "s") is Lhe collecLion class LhaL l inLroduced earlier
LhaL represenLs all Lhe conLrol objecLs on Lhe currenL orm. 1he body o Lhe loop is used Lo
300 Part II Programmng fundamentaIs
1his lcr lcch . . . Next loop sLeps Lhrough Lhe Ccntrcls collecLion on Lhe orm one
conLrol aL a Lime and seLs each conLrol's 1ext properLy Lo "Click Me!" 1he loop uses ctrl
as an objecL variable in Lhe loop, which you'll declare in Lhe ollowing sLep.
6. Scroll Lo Lhe Lop o Lhe orm's program code, and direcLly above Lhe sLaLemenL Public
Clcss lcrm1, Lype Lhe ollowing sLaLemenL.
Opt i on I nf er Of f
1his sLaLemenL Lells Lhe compiler LhaL iL should noL Lry Lo iner Lhe Lype o variables.
Since you will be expliciLly declaring Lhe variable Lypes, Lhis iner opLion is noL
needed. l Oticn lnjer is on and you Lry Lo run Lhe code in Lhis chapLer, you may see
a warning message indicaLing LhaL Lhe Lype or a variable you are using cannoL be
inerred. (For more inormaLion, see ChapLer , "Fxploring Lhe visual SLudio lnLegraLed
DevelopmenL FnvironmenL.")
7. DirecLly below Lhe sLaLemenL Public Clcss lcrm1, Lype Lhe ollowing commenL
and variable declaraLion.
' Decl ar e a var i abl e of t ype Cont r ol t o r epr esent f or mcont r ol s
Di mct r l As Cont r ol
1his global variable declaraLion creaLes a variable in Lhe Ccntrcl class Lype LhaL
represenLs Lhe currenL orm's conLrols in Lhe program. ou're declaring Lhis variable in
Lhe general declaraLions area o Lhe orm so LhaL iL is valid LhroughouL all Lhe orm's
evenL procedures.
Now you're ready Lo run Lhe program and change Lhe 1ext properLy or each buLLon on
Lhe orm.
8. Click Lhe SLarL Debugging buLLon on Lhe SLandard Loolbar Lo run Lhe program.
9. 3uttcn1).
1he 3uttcn1_Clicl evenL procedure changes Lhe 1ext properLy or each conLrol in Lhe
Ccntrcls collecLion. our orm looks like Lhis.
302 Part II Programmng fundamentaIs
4. .
1he buLLons on Lhe orm change Lo "Click Me!", and Lhen each Lime you click Lhe
second buLLon, Lhe objecLs on Lhe orm gradually move Lo Lhe righL. our screen looks
5. Click Lhe Close buLLon on Lhe orm Lo sLop Lhe program.
6. Click Lhe Save All buLLon Lo save your changes.
ou won'L always wanL Lo move all Lhe objecLs on a orm as a group. WiLh visual 8asic,
you can process collecLion members individually. ln Lhe nexL exercise, you'll learn
how Lo keep Lhe Lhird buLLon objecL in one place while Lhe oLher Lwo buLLons move
Lo Lhe righL.
Usng the Ncme Property n a For Lcch . . . Next Loop
l you wanL Lo process one or more members o a collecLion dierenLly Lhan you process Lhe
oLhers, you can use Lhe Ncme .
ou've seL Lhe Ncme properLy periodically in Lhis book Lo make your program code more
readable, buL Ncme
program.
1o use Lhe Ncme properLy programmaLically, single ouL Lhe objecLs Lo which you wanL Lo
give special LreaLmenL, and Lhen noLe Lheir Ncme properLies. 1hen as you loop Lhrough Lhe
objecLs on Lhe orm by using a lcr lcch . . . Next loop, you can use one or more lj sLaLemenLs
Lo LesL or Lhe imporLanL Ncme properLies and handle Lhose objecLs dierenLly. For example,
leL's say you wanL Lo consLrucL a lcr lcch . . . Next loop LhaL moves one objecL more slowly
across Lhe orm Lhan Lhe oLher objecLs. ou could use an lj . . . 1hen sLaLemenL Lo spoL Lhe
Ncme properLy o Lhe slower objecL and Lhen move LhaL objecL a shorLer disLance, by noL
incremenLing iLs lejt properLy as much as Lhose o Lhe oLher objecLs.
304 Part II Programmng fundamentaIs
5. Click Lhe Lhird buLLon objecL six or seven Limes.
As you click Lhe buLLon, Lhe Lop Lwo buLLon objecLs move across Lhe screen. 1he Lhird
buLLon sLays in Lhe same place, however, as shown here.
6. Click Lhe Close buLLon on Lhe orm Lo sLop Lhe program.
Civing one objecL in a collecLion special LreaLmenL can be very useul. ln Lhis case, using Lhe
Ncme properLy in Lhe lcr lcch . . . Next loop improved Lhe readabiliLy o Lhe program code,
suggesLing numerous poLenLial uses or a game or graphics program. As you use oLher Lypes
o collecLions in visual 8asic, be sure Lo keep Lhe Ncme properLy in mind.
Creating Your Own CoIIections
WiLh visual 8asic, you can also creaLe your own collecLions Lo Lrack daLa in a program
and manipulaLe iL sysLemaLically. AlLhough collecLions are oLen creaLed Lo hold objecLs,
such as user inLerace conLrols, you can also use collecLions Lo sLore numeric or sLring
values while a program is running. ln Lhis way, collecLions nicely complemenL Lhe
capabiliLies o arrays, which you learned abouL in ChapLer .
DecIarng New CoIIectons
New collecLions are declared as variables in a program, and Lhe locaLion in which you declare
Lhem deLermines Lheir scope, or Lhe exLenL Lo which Lheir assigned values persisL. 8ecause
collecLions are so useul, l usually declare Lhem aL Lhe Lop o a orm or in a module.
New collecLion declaraLions require Lhe synLax.
Di mCol l ect i onName As New Col l ect i on( )
where CcllecticnNcme is Lhe name o your collecLion. l you place Lhe collecLion declaraLion
in a module, you use Lhe Public keyword insLead o Lhe Dim keyword. ALer you creaLe
306 Part II Programmng fundamentaIs
1his sLaLemenL creaLes a new collecLion and assigns iL Lhe variable name URlsvisiteJ.
8ecause you're placing Lhe declaraLion in Lhe declaraLion area or Lhe orm, Lhe
collecLion has scope LhroughouL all Lhe orm's evenL procedures.
8. Display Lhe orm again, double-click Lhe visiL SiLe buLLon, and Lhen Lype Lhe ollowing
code in Lhe 3uttcn1_Clicl evenL procedure.
URLsVi si t ed. Add( Text Box1. Text )
Syst em. Di agnost i cs. Pr ocess. St ar t ( Text Box1. Text )
1his program code uses Lhe AJJ culcte, Lhe collecLion wiLh
members. When Lhe user clicks Lhe 3uttcn1 objecL, Lhe program assumes LhaL a valid
lnLerneL address has been placed in Lhe 1ext3cx1 objecL. Fvery Lime Lhe 3uttcn1
objecL is clicked, Lhe currenL URL in 1ext3cx1 is copied Lo Lhe URlsvisiteJ collecLion
as a sLring. NexL, Lhe System.Dicncstics.Prccess.Stcrt meLhod is called wiLh Lhe URL
as a parameLer. 8ecause Lhe parameLer is a URL, Lhe Stcrt meLhod aLLempLs Lo open
Lhe URL by using Lhe deaulL Web browser on Lhe sysLem. (l Lhe URL is invalid or
an lnLerneL connecLion cannoL be esLablished, Lhe Web browser handles Lhe error.)
Note 1he only URLs LhaL Lhis program adds Lo Lhe URlsvisiteJ collecLion are Lhose you've
1ext3cx1 objecL. l you browse Lo addiLional Web siLes by using your Web
browser, Lhose siLes won'L be added Lo Lhe collecLion.
9. Display Lhe orm again, and Lhen double-click Lhe LisL RecenL SiLes buLLon.
l0. 1ype Lhe ollowing program code using Lhe Code FdiLor.
Di mURLName As St r i ng = " ", Al l URLs As St r i ng = " "
For Each URLName I n URLsVi si t ed
Al l URLs = Al l URLs & URLName & vbCr Lf
Next URLName
MsgBox( Al l URLs, MsgBoxSt yl e. I nf or mat i on, " Web si t es vi si t ed")
1his evenL procedure prinLs Lhe enLire collecLion by using a lcr lcch . . . Next loop and a
Ms3cx uncLion. 1he rouLine declares a sLring variable named URlNcme Lo hold each
member o Lhe collecLion as iL's processed and iniLializes Lhe variable Lo empLy (""). 1he
value is added Lo a sLring named AllURls by using Lhe concaLenaLion operaLor (&), and
Lhe vbCrlj sLring consLanL is used Lo place each URL on iLs own line.
Finally, Lhe AllURls sLring, which represenLs Lhe enLire conLenLs o Lhe URlsvisiteJ
collecLion, is displayed in a message box. l added Lhe Ms3cxStyle.lnjcrmcticn
argumenL in Lhe Ms3cx uncLion Lo emphasize LhaL Lhe LexL being displayed is general
inormaLion and noL a warning. (Ms3cxStyle.lnjcrmcticn is also a builL-in visual 8asic
consLanL.)
ll. Click Lhe Save All buLLon Lo save your changes. Speciy Lhe C.\vb0sbs\Chap2 older as
Lhe locaLion.
308 Part II Programmng fundamentaIs
3. Click Lhe orm again. (ou mighL need Lo click Lhe orm's icon on Lhe Windows Laskbar.)
4. Click Lhe LisL RecenL SiLes buLLon.
visual 8asic execuLes Lhe evenL procedure or Lhe 3uttcn2 objecL. ou see a message
box LhaL looks like Lhis.
5. Click OK in Lhe message box, Lype a dierenL Web siLe in Lhe orm's LexL box, and Lhen
click Lhe visiL SiLe buLLon.
1p ou mighL wanL Lo visiL Lhe MicrosoL visual 8asic Developer CenLer siLe, locaLed aL
htt.//msJn.micrcscjt.ccm/vbcsic/, Lo learn more abouL visual 8asic.
6. visiL a ew more Web siLes by using Lhe URL CollecLion orm, and Lhen click Lhe LisL
RecenL SiLes buLLon.
Fach Lime you click LisL RecenL SiLes, Lhe Ms3cx uncLion expands Lo show Lhe growing
URL hisLory lisL, as shown here.
l you visiL more Lhan a ew dozen Web siLes, you'll need Lo replace Lhe Ms3cx uncLion
wiLh a mulLiline LexL box on Lhe orm.
7.
browser.
CongraLulaLions! ou've learned how Lo use Lhe Ccntrcls collecLion and how Lo process
collecLions by using a lcr lcch . . . Next loop. 1hese skills will be useul whenever you work
wiLh collecLions. As you become more amiliar wiLh classic compuLer science daLa sLrucLures
and algoriLhms relaLed Lo lisL managemenL (sLacks, queues, dicLionaries, hash Lables,
Chapter l2 Workng wth CoIIectons 309
and .NF1 Framework provide
equivalenLs Lo help you manage inormaLion in exLremely innovaLive ways. (For a ew book
ideas relaLed Lo daLa sLrucLures and algoriLhms, see Lhe secLion enLiLled "Ceneral 8ooks
AbouL Programming and CompuLer Science" in Lhe Appendix, "Where Lo Co or More
lnormaLion.")
One Step lurther. VBA CoIIections
collecLions play a big role in Lhe objecL models o MicrosoL Word, MicrosoL Fxcel, MicrosoL
Access, MicrosoL PowerPoinL, and several oLher applicaLions LhaL supporL Lhe visual 8asic or
ApplicaLions (v8A) programming language. ln Word, or example, all Lhe open documenLs
are sLored in Lhe Dccuments collecLion, and each paragraph in Lhe currenL documenL is
sLored in Lhe Pcrcrchs collecLion. ou can manipulaLe Lhese collecLions wiLh a lcr
lcch . . . Next loop jusL as you did Lhe collecLions in Lhe preceding exercises.
.
1p As a soLware developer, you should be aware LhaL companies and individual users oLen
.
.
1he ollowing sample code comes rom a Word v8A macro LhaL uses a lcr lcch . . . Next
loop Lo search each open documenL in Lhe Dccuments
.doc. Scve meLhod.
l
C.\vb0sbs\Chap2 older.
Di maDoc As Document
Di mdocFound As Bool ean
Di mdocLocat i on As St r i ng
docFound = Fal se
docLocat i on = " c: \ vb10sbs\ chap12\ myl et t er . doc"
For Each aDoc I n Document s
I f I nSt r ( 1, aDoc. Name, "myl et t er . doc" , 1) Then
docFound = Tr ue
aDoc. Save
Exi t For
End I f
Next aDoc
I f docFound = Fal se Then
Document s. Open Fi l eName: =docLocat i on
End I f
1he macro begins by declaring Lhree variables. 1he cDcc objecL variable represenLs Lhe
currenL collecLion elemenL in Lhe lcr lcch . . . Next loop. 1he JcclcunJ 8oolean variable
3l0 Part II Programmng fundamentaIs
assigns a 8oolean value o 1rue i Lhe documenL is ound in Lhe Dccuments collecLion. 1he
Jcclcccticn sLring variable conLains Lhe paLh o Lhe MyLeLLer. . (1his rouLine
assumes LhaL Lhe MyLeLLer. .)
1he lcr lcch . . . Next loop cycles Lhrough each documenL in Lhe Dccuments collecLion,
. lnStr uncLion (which deLecLs one
.
using Lhe Oen meLhod o Lhe Dccuments objecL.
Also noLe Lhe lxit lcr sLaLemenL, which l use Lo exiL Lhe lcr lcch . . . Next loop when Lhe
. lxit lcr is a special program sLaLemenL LhaL you
can use Lo exiL a lcr . . . Next loop or a lcr lcch . . . Next loop when conLinuing will cause
unwanLed resulLs. ln Lhis example, i Lhe MyLeLLer.
conLinuing Lhe search is ruiLless, and Lhe lxit lcr sLaLemenL aords a graceul way Lo sLop
Lhe loop as soon as iLs Lask is compleLed.
fnterng the Word Macro
l've included Lhis sample Word macro Lo show you how you can use collecLions in visual
8asic or ApplicaLions, buL Lhe source code is designed or Word, noL Lhe visual SLudio
lnLegraLed DevelopmenL FnvironmenL (lDF). l you aren'L working in Word, Lhe Dccuments
collecLion won'L have any meaning Lo Lhe compiler.
1he sLeps LhaL you will ollow Lo Lry Lhe macro depend on Lhe version o Word you are using.
l you are using Word 2007 or Word 200, you'll need Lo sLarL Word, click Lhe Developer Lab,
click Lhe Macros command, speciy a name or Lhe macro (l used OpenMyDoc), click CreaLe,
and Lhen enLer Lhe code by using Lhe visual 8asic FdiLor. (l Lhe Developer Lab is noL shown,
you will need Lo enable iL in Lhe Word OpLions dialog box.) l you are using Word 2008, you'll
need Lo sLarL Word, go Lo Lhe Macro submenu o Lhe 1ools menu, click Lhe Macros command,
speciy a name or Lhe macro, click CreaLe, and Lhen enLer Lhe code by using Lhe visual 8asic
FdiLor.
ln Lhe visual 8asic FdiLor, Lhe compleLed macro looks like Lhe ollowing screen shoL. ou can
run Lhe macro by clicking Lhe Run Sub/UserForm buLLon on Lhe Loolbar, jusL as you would
run a program in Lhe visual SLudio lDF. ALer Lhe macro runs, click Lhe Word applicaLion
again, and you'll see LhaL Lhe MyLeLLer documenL has been opened or you.
1p Word macros are generally compaLible beLween versions, alLhough l have someLimes run
. l you are
using a dierenL version o Word, you may need Lo slighLly modiy Lhe sample code shown on
Lhe ollowing page.
3l3
ChapLer 8
fxpIorng 1ext fIes
and Strng Processng
After compIetng ths chapter, you wII be abIe to:
Use Lhe My namespace, a Lime-saving "speed dial" eaLure wiLhin visual SLudio 200.
RecJAll1ext meLhod and Lhe
OenlileDiclc conLrol.
WriteAll1ext meLhod and Lhe ScvelileDiclc
conLrol.
Use sLring processing Lechniques in Lhe Strin class Lo compare, combine, sorL,
and encrypL sLrings.
Managing elecLronic documenLs is an imporLanL uncLion in any modern business, and
MicrosoL visual 8asic 200 provides numerous mechanisms or working wiLh dierenL
documenL Lypes and manipulaLing Lhe inormaLion in documenLs. 1he mosL basic documenL
Lype is Lhe , which is made up o non-ormaLLed words and paragraphs, leLLers,
numbers, and a varieLy o special-purpose characLers and symbols.
.
. ou'll also learn more abouL managing sLrings in your
programs, and you'll use meLhods in Lhe MicrosoL .NF1 Framework Strin, StrecmRecJer,
and StrecmWriter .
keading Text liIes
A consisLs o one or more lines o numbers, words, or characLers.
rom and Web ces, which conLain ormaLLing codes, and rom executcble
, which conLain insLrucLions or Lhe operaLing sysLem.
exLension .LxL, .ini, .log, or .in.
. As you have
learned, you can creaLe LexL box objecLs in any size.
.
Chapter l3 fxpIorng 1ext fIes and Strng Processng 3l5
1he My namespace is Lruly a "speed dial" eaLure, ully explorable via Lhe MicrosoL
lnLelliSense eaLure o Lhe Code FdiLor. For example, Lo use a message box Lo display Lhe
name o Lhe currenL compuLer ollowed by Lhe name o Lhe currenL user in a program, you
can simply Lype.
MsgBox( My. User . Name)
1his produces ouLpuL similar Lo Lhe ollowing.
1he My.Ccmuter objecL can display many caLegories o inormaLion abouL your compuLer
. For example, Lhe ollowing sLaLemenL displays Lhe currenL sysLem Lime (Lhe local
daLe and Lime) mainLained by Lhe compuLer.
MsgBox( My. Comput er . Cl ock. Local Ti me)
1his produces ouLpuL like Lhis (your daLe and Lime will probably be dierenL).
ou can use Lhe My.Ccmuter.lileSystem objecL along wiLh Lhe RecJAll1ext meLhod Lo open
a . Here's Lhe synLax you can use
i you have a LexL box objecL on your orm named txtNcte (as in Lhe lasL sample program)
and OenlileDiclc1 Lo geL Lhe name
o
Di mAl l Text As St r i ng = " "
OpenFi l eDi al og1. Fi l t er = "Text f i l es ( *. t xt ) | *. t xt "
I f OpenFi l eDi al og1. ShowDi al og( ) = Di al ogResul t . OK Then ' di spl ay Open di al og box
Al l Text = My. Comput er . Fi l eSyst em. ReadAl l Text ( OpenFi l eDi al og1. Fi l eName)
t xt Not e. Text = Al l Text ' di spl ay f i l e
End I f
1he RecJAll1ext
variable or objecL (in Lhis case, a sLring variable named All1ext), so in Lerms o perormance
and coding Lime, RecJAll1ext .
3l6 Part II Programmng fundamentaIs
8ecause o Lhis speed acLor, Lhe My namespace provides an excellenL shorLcuL Lo many
common programming Lasks. lL is imporLanL Lo Lake noLe o Lhis eaLure and iLs possible uses,
buL Lhe My .
l you orgeL Lhe synLax or Lhe RecJAll1ext meLhod, you can quickly inserL an example by
using Lhe lnserL SnippeL command. As described in ChapLer 7, "Using Loops and 1imers,"
Lhe lnserL SnippeL command allows you Lo inserL common code snippeLs in Lhe Code
FdiLor. 1o inserL Lhe RecJAll1ext meLhod, display Lhe Code FdiLor, and on Lhe FdiL menu,
click lnLelliSense, and Lhen click lnserL SnippeL. ln Lhe lnserL SnippeL lisL box, double-click
FundamenLals - CollecLions, DaLa 1ypes, File SysLem, MaLh, double-click File SysLem -
Processing Drives, Folders, And Files, and Lhen double-click Read 1exL From A File. 1his
inserLs Lhe ollowing code snippeL.
Di mf i l eCont ent s1 As St r i ng
f i l eCont ent s1 = My. Comput er . Fi l eSyst em. ReadAl l Text ( " C: \ Test . t xt " )
1he StrecmRecder CIass
1he StrecmRecJer class in Lhe .NF1 Framework library allows you Lo open and display LexL
. l'll use Lhis Lechnique several Limes in Lhis book when l work wiLh LexL
. 1o make iL
easier Lo use Lhe StrecmRecJer class, you add Lhe ollowing lmcrts sLaLemenL Lo Lhe Lop
o your code, as discussed in ChapLer 5, "visual 8asic variables and Formulas, and Lhe .NF1
Framework".
I mpor t s Syst em. I O
box by using Lhe ollowing program code. .LxL,
and Lhe code assumes LhaL an objecL named 1ext3cx1 has been creaLed on your orm.)
Di mSt r eamToDi spl ay As St r eamReader
St r eamToDi spl ay = New St r eamReader ( "C: \ vb10sbs\ chap13\ t ext br owser \ badbi l l s. t xt " )
Text Box1. Text = St r eamToDi spl ay. ReadToEnd
St r eamToDi spl ay. Cl ose( )
ln Lhis StrecmRecJer example, l declare a variable named Strecm1cDislcy o Lhe Lype
StrecmRecJer
l wanL Lo open. Strecm1cDislcy variable
by using Lhe RecJ1clnJ
1ext
properLy o Lhe LexL box objecL. StrecmRecJer. Closing Lhe
Chapter l3 fxpIorng 1ext fIes and Strng Processng 3l9
5. Open Lhe C.\vb0sbs\Chap8\1exL 8rowser older.
1he conLenLs o Lhe 1exL 8rowser older are shown here.
6. .
dangers o counLereiL money, appears in Lhe LexL box, as shown here.
7. Use Lhe scroll bars Lo view Lhe enLire documenL. Memorize number 5.
8.
and Lhen click Lhe FxiL command Lo quiL Lhe program.
1he program sLops, and Lhe lDF reLurns.
Now you'll look aL Lwo imporLanL evenL procedures in Lhe program.
Chapter l3 fxpIorng 1ext fIes and Strng Processng 32l
3. Display Lhe Clcse1cclStriMenultem_Clicl evenL procedure, which is execuLed when Lhe
Close menu command is clicked.
1he evenL procedure looks like Lhis.
t xt Not e. Text = "" ' cl ear t ext box
l bl Not e. Text = "Load a t ext f i l e wi t h t he Open command. "
Cl oseTool St r i pMenuI t em. Enabl ed = Fal se ' di sabl e Cl ose command
OpenTool St r i pMenuI t em. Enabl ed = Tr ue ' enabl e Open command
1he procedure clears Lhe LexL box, updaLes Lhe lblNcte label, disables Lhe Close
command, and enables Lhe Open command.
Now you can use Lhis simple program as a LemplaLe or more advanced programs LhaL
. ln Lhe nexL secLion, you'll learn how Lo Lype your own LexL inLo a LexL box
.
writing Text liIes
meLhods and keywords used in Lhe lasL example.
Lo Lhem is useul i you plan Lo generaLe cusLom reporLs or logs, save imporLanL calculaLions
or values, or creaLe a special-purpose word processor or LexL ediLor. Here's an overview o Lhe
sLeps you'll need Lo ollow in Lhe program.
l. CeL inpuL rom Lhe user or perorm maLhemaLical calculaLions, or do boLh.
2. Assign Lhe resulLs o your processing Lo one or more variables. For example, you could
assign Lhe conLenLs o a LexL box Lo a sLring variable.
3. PrompL Lhe user or a paLh by using a ScvelileDiclc conLrol. ou use Lhe ShcwDiclc
meLhod Lo display Lhe dialog box.
4. .
5. .
6. .
1he WriteAllText Method
ln Lhe previous example, we used Lhe My.Ccmuter.lileSystem objecL wiLh Lhe RecJAll1ext
meLhod. NoL surprisingly, Lhis objecL also includes Lhe WriteAll1ext meLhod. 1he WriteAll1ext
. . Here's Lhe synLax
you can use i you have a LexL box objecL on your orm named txtNcte (as in Lhe lasL sample
ScvelileDiclc1 Lo geL Lhe
SaveFi l eDi al og1. Fi l t er = "Text f i l es ( *. t xt ) | *. t xt "
I f SaveFi l eDi al og1. ShowDi al og( ) = Di al ogResul t . OK Then
' copy t ext t o di sk
322 Part II Programmng fundamentaIs
My. Comput er . Fi l eSyst em. Wr i t eAl l Text ( _
SaveFi l eDi al og1. Fi l eName, t xt Not e. Text , Fal se)
End I f
WriteAll1ext Lakes Lhree parameLers.
ScvelileDiclc1).
txtNcte LexL box). 1he lasL parameLer
wheLher Lo append Lhe LexL or overwriLe Lhe exisLing LexL. A value o False or Lhe lasL
parameLer direcLs visual 8asic Lo overwriLe Lhe exisLing LexL.
1he StrecmWriter CIass
Similar Lo iLs companion, Lhe StrecmRecJer class, Lhe StrecmWriter class in Lhe .NF1
. 1o make iL easier Lo use
Lhe StrecmWriter class, you add Lhe ollowing lmcrts sLaLemenL Lo Lhe Lop o your code.
I mpor t s Syst em. I O
using Lhe ollowing program code. .LxL, and Lhe code
assumes an objecL named 1ext3cx1 has been creaLed on your orm.)
Di mSt r eamToWr i t e As St r eamWr i t er
St r eamToWr i t e = New St r eamWr i t er ( " C: \ vb10sbs\ chap13\ out put . t xt " )
St r eamToWr i t e. Wr i t e( Text Box1. Text )
St r eamToWr i t e. Cl ose( )
ln Lhis StrecmWriter example, l declare a variable named Strecm1cWrite o Lhe Lype
StrecmWriter . NexL, l wriLe Lhe
Write meLhod.
StrecmWriter. Closing Lhe StrecmWriter can be imporLanL because i you Lry Lo read or wriLe
.
ou can also use a combinaLion o Lhe My namespace and Lhe StrecmWriter class. 1he
. 1he Oen1extlileWriter meLhod in Lhe My
namespace opens a StrecmWriter. 1he Writeline . When you
StrecmWriter, you should close iL by calling Lhe Clcse meLhod.
Di mLi neOf Text As St r i ng = ""
Di mSt r eamToWr i t e As St r eamWr i t er
St r eamToWr i t e = My. Comput er . Fi l eSyst em. OpenText Fi l eWr i t er ( _
" C: \ vb10sbs\ chap13\ out put . t xt " , Fal se)
' get l i ne of t ext
Li neOf Text = I nput Box( " Ent er l i ne" )
Do Unt i l Li neOf Text = " "
' wr i t e l i ne t o f i l e
St r eamToWr i t e. Wr i t eLi ne( Li neOf Text )
Chapter l3 fxpIorng 1ext fIes and Strng Processng 325
6. On Lhe File menu, click Lhe lnserL DaLe command.
1he lnserL DaLe command provides a handy way Lo include Lhe currenL Lime sLamp in
a .
7. On Lhe File menu, click Lhe Save As command.
1he program displays a Save As dialog box wiLh all Lhe expecLed eaLures. 1he deaulL
.LxL. our screen looks like Lhe ollowing.
8. ln Lhe Save As dialog box, open Lhe C.\vb0sbs\Chap8\uick NoLe older i iL isn'L
already open. 1hen Lype Badcoins.txt in Lhe File Name LexL box, and click Save.
1he LexL o your documenL is saved in Lhe new 8adcoins. .
9. On Lhe File menu, click Lhe FxiL command.
1he program sLops, and Lhe developmenL environmenL reLurns.
Now you'll look aL Lhe evenL procedures in Lhe program.
330 Part II Programmng fundamentaIs
ln Lhe 980s, l8M exLended ASCll wiLh codes 28 Lhrough 255, which represenL accenLed,
Creek, and graphic characLers, as well as miscellaneous symbols. ASCll and Lhese addiLional
characLers and symbols are Lypically known as Lhe l3M extenJeJ chcrccter set.
1he ASCll characLer seL is sLill Lhe mosL imporLanL numeric code or beginning programmers
Lo learn, buL iL isn'L Lhe only characLer seL. As Lhe markeL or compuLers and applicaLion
soLware has become more global, a more comprehensive sLandard or characLer
represenLaLion called UniccJe has emerged. Unicode can hold up Lo 65,586 symbols-plenLy
o space Lo represenL Lhe LradiLional symbols in Lhe ASCll characLer seL plus mosL (wriLLen)
inLernaLional languages and symbols. A sLandards body mainLains Lhe Unicode characLer
seL and adds symbols Lo iL periodically. Windows XP, Windows visLa, Windows 7, and visual
. (For
more inormaLion abouL Lhe relaLionship beLween Unicode, ASCll, and visual 8asic daLa
.)
ln Lhe ollowing secLions, you'll learn more abouL using Lhe ASCll characLer seL Lo process
sLrings in your programs. As your applicaLions become more sophisLicaLed and you sLarL
planning or Lhe global disLribuLion o your soLware, you'll need Lo learn more abouL
Unicode and oLher inLernaLional seLLings.
Workng wth ASCII Codes
1o deLermine Lhe ASCll code o a parLicular leLLer, you can use Lhe visual 8asic Asc uncLion.
For example, Lhe ollowing program sLaLemenL assigns Lhe number 22 (Lhe ASCll code or
Lhe lowercase leLLer z) Lo Lhe AscCcJe shorL inLeger variable.
Di mAscCode As Shor t
AscCode = Asc( " z" )
Conversely, you can converL an ASCll code Lo a leLLer wiLh Lhe Chr uncLion. For example, Lhis
program sLaLemenL assigns Lhe leLLer z Lo Lhe leLLer characLer variable.
Di ml et t er As Char
l et t er = Chr ( 122)
1he same resulL could also be achieved i you used Lhe AscCcJe variable jusL declared, as
shown here.
l et t er = Chr ( AscCode)
How can you compare one LexL sLring or ASCll code wiLh anoLher ou simply use one o Lhe
six relaLional operaLors visual 8asic supplies or working wiLh LexLual and numeric elemenLs.
1hese relaLional operaLors are shown in 1able 8-8.
Chapter l3 fxpIorng 1ext fIes and Strng Processng 333
3. 1ype Lhe ollowing LexL, or some LexL o your own, in Lhe LexL box.
Zebra
GoriIIa
Moon
Banana
AppIe
TurtIe
4. Click Lhe SorL 1exL command on Lhe File menu.
1he LexL you Lyped is sorLed and redisplayed in Lhe LexL box as ollows.
5. Click Lhe Open command on Lhe File menu, and Lhen open Lhe Abc.
C.\vb0sbs\Chap8 older, as shown here.
1he Abc. . Fach line begins wiLh eiLher a leLLer or a
number rom Lhrough 0.
Chapter l3 fxpIorng 1ext fIes and Strng Processng 335
1he enLire Scrt1ext1cclStriMenultem_Clicl evenL procedure looks like Lhis.
Di mst r Ar r ay( ) As St r i ng
Di msText As St r i ng
Di mi As Shor t
sText = t xt Not e. Text
' r epl ace di f f er ent new l i ne char act er s wi t h one ver si on
sText = sText . Repl ace( vbCr Lf , vbCr )
sText = sText . Repl ace( vbLf , vbCr )
' r emove l ast car r i age r et ur n i f i t exi st s
I f sText . EndsWi t h( vbCr ) Then
sText = sText . Subst r i ng( 0, sText . Lengt h - 1)
End I f
' spl i t each l i ne i n t o an ar r ay
st r Ar r ay = sText . Spl i t ( vbCr )
' sor t ar r ay
Shel l Sor t ( st r Ar r ay, st r Ar r ay. Lengt h)
' t hen di spl ay sor t ed ar r ay i n t ext box
sText = ""
For i = 0 To st r Ar r ay. Lengt h - 1
sText = sText & st r Ar r ay( i ) & vbCr Lf
Next i
t xt Not e. Text = sText
t xt Not e. Sel ect ( 0, 0) ' r emove t ext sel ect i on
1he Slit meLhod creaLes an array LhaL has Lhe same number o elemenLs as Lhe LexL
box has lines o LexL. ALer Lhe array is ull o LexL, l call Lhe ShellScrt procedure locaLed
in Lhe Module.vb module, which l discussed earlier in Lhis chapLer. ALer Lhe array is
sorLed, l use a lcr loop (as discussed in ChapLer 7) Lo reconsLrucL Lhe lines and copy
Lhem inLo Lhe LexL box.
3. Display Lhe code or Lhe Module.vb module in Lhe Code FdiLor.
ShellScrt procedure. 1he ShellScrt procedure
uses an lj sLaLemenL and Lhe <= relaLional operaLor (as discussed in ChapLers 6, 8,
and Lhis chapLer) Lo compare array elemenLs and swap any LhaL are ouL o order.
1he procedure looks like Lhis.
Sub Shel l Sor t ( ByVal sor t ( ) As St r i ng, ByVal numOf El ement s As Shor t )
Di mt emp As St r i ng
Di mi , j , span As Shor t
' The Shel l Sor t pr ocedur e sor t s t he el ement s of sor t ( )
' ar r ay i n descendi ng or der and r et ur ns i t t o t he cal l i ng
' pr ocedur e.
span = numOf El ement s \ 2
Do Whi l e span > 0
336 Part II Programmng fundamentaIs
For i = span To numOf El ement s - 1
For j = ( i - span) To 0 St ep - span
I f sor t ( j ) <= sor t ( j + span) Then Exi t For
' swap ar r ay el ement s t hat ar e out of or der
t emp = sor t ( j )
sor t ( j ) = sor t ( j + span)
sor t ( j + span) = t emp
Next j
Next i
span = span \ 2
Loop
End Sub
1he meLhod o Lhe sorL is Lo conLinually divide Lhe main lisL o elemenLs inLo sublisLs
LhaL are smaller by hal. 1he sorL Lhen compares Lhe Lops and Lhe boLLoms o Lhe
sublisLs Lo see wheLher Lhe elemenLs are ouL o order. l Lhe Lop and boLLom are ouL o
order, Lhey're exchanged. 1he resulL is an array named scrt() LhaL's sorLed alphabeLically
in descending order. 1o change Lhe direcLion o Lhe sorL, simply reverse Lhe relaLional
operaLor (change <= Lo >=).
1he remaining evenL procedures in Form (Oen1cclStriMenultem_Clicl,
Clcse1cclStriMenultem_Clicl, ScveAs1cclStriMenultem_Clicl, lnsertDcte1cclStriMenultem_
Clicl, and lxit1cclStriMenultem_Clicl) are all similar Lo Lhe procedures LhaL you sLudied in Lhe
1exL 8rowser and Lhe uick NoLe programs. (See my explanaLions earlier in Lhis chapLer or Lhe
deLails.)
LeL's move on Lo anoLher variaLion o Lhis program LhaL manipulaLes Lhe sLrings in a LexL box
.
Protecting Text with Basic ncryption
Now LhaL you've had some experience wiLh ASCll codes, you can begin Lo wriLe simple
encrypLion rouLines LhaL shiL Lhe ASCll codes in your documenLs and "scramble" Lhe LexL
Lo hide iL rom inLruding eyes. 1his process, known as encryticn, maLhemaLically alLers
. O course, Lo
use encrypLion successully, you also need Lo be able Lo reverse Lhe process-oLherwise,
you'll simply be . And you'll wanL Lo creaLe
an encrypLion scheme or ley LhaL can'L be easily recognized, a complicaLed process
LhaL's only begun by Lhe sample programs in Lhis chapLer.
1he ollowing exercises show you how Lo encrypL and decrypL LexL sLrings saely. ou'll
run Lhe FncrypL 1exL program now Lo see a simple encrypLion scheme in acLion. As l noLe aL
Lhe end o Lhis chapLer, Lhese exercises are jusL Lhe Lip o Lhe iceberg or using encrypLion,
o inLeresL or programmers in Lhe lasL decade or so. SLill, even basic encrypLion is un
and a useul demonsLraLion o LexL-processing Lechniques.
Chapter l3 fxpIorng 1ext fIes and Strng Processng 339
For i = 0 To char sI nFi l e - 1
l et t er = t xt Not e. Text . Subst r i ng( i , 1)
' det er mi ne ASCI I code and add one t o i t
Encr ypt = Encr ypt & Chr ( Asc( l et t er ) + 1)
Next
' wr i t e encr ypt ed t ext t o f i l e
My. Comput er . Fi l eSyst em. Wr i t eAl l Text ( SaveFi l eDi al og1. Fi l eName, Encr ypt , Fal se)
t xt Not e. Text = Encr ypt
t xt Not e. Sel ect ( 0, 0) ' r emove t ext sel ect i on
mnuCl oseI t em. Enabl ed = Tr ue
Cat ch ex As Except i on
MsgBox( "An er r or occur r ed. " & vbCr Lf & ex. Message)
End Tr y
End I f
NoLe especially Lhe sLaLemenL.
Encr ypt = Encr ypt & Chr ( Asc( l et t er ) + 1)
which deLermines Lhe ASCll code o Lhe currenL leLLer, adds Lo iL, converLs Lhe ASCll
code back Lo a leLLer, and Lhen adds iL Lo Lhe lncryt sLring.
2. Now display Lhe mnuOenltem_Clicl evenL procedure in Lhe Code FdiLor Lo see how
Lhe program reverses Lhe encrypLion.
1his program code is nearly idenLical Lo LhaL o Lhe Save FncrypLed File As command,
buL raLher Lhan adding Lo Lhe ASCll code or each leLLer, iL subLracLs . Here's Lhe
compleLe mnuOenltem_Clicl evenL procedure, wiLh noLeworLhy sLaLemenLs in bold.
Di mAl l Text As St r i ng
Di mi , char sI nFi l e As Shor t
Di ml et t er As Char
Di mDecr ypt As St r i ng = " "
OpenFi l eDi al og1. Fi l t er = "Text f i l es ( *. t xt ) | *. t xt "
I f OpenFi l eDi al og1. ShowDi al og( ) = Di al ogResul t . OK Then ' di spl ay Open di al og box
I f My. Comput er . Fi l eSyst em. Fi l eExi st s( OpenFi l eDi al og1. Fi l eName) Then
Tr y ' open f i l e and t r ap any er r or s usi ng handl er
Al l Text = My. Comput er . Fi l eSyst em. ReadAl l Text ( OpenFi l eDi al og1. Fi l eName)
' now, decr ypt st r i ng by subt r act i ng one f r omASCI I code
char sI nFi l e = Al l Text . Lengt h ' get l engt h of st r i ng
For i = 0 To char sI nFi l e - 1 ' l oop once f or each char
l et t er = Al l Text . Subst r i ng( i , 1) ' get char act er
Decr ypt = Decr ypt & Chr ( Asc( l et t er ) - 1) ' subt r act 1
Next i ' and bui l d new st r i ng
t xt Not e. Text = Decr ypt ' t hen di spl ay conver t ed st r i ng
l bl Not e. Text = OpenFi l eDi al og1. Fi l eName
t xt Not e. Sel ect ( 0, 0) ' r emove t ext sel ect i on
t xt Not e. Enabl ed = Tr ue ' al l ow t ext cur sor
mnuCl oseI t em. Enabl ed = Tr ue ' enabl e Cl ose command
mnuOpenI t em. Enabl ed = Fal se ' di sabl e Open command
Cat ch ex As Except i on
MsgBox( " An er r or occur r ed. " & vbCr Lf & ex. Message)
End Tr y
End I f
End I f
340 Part II Programmng fundamentaIs
1his Lype o simple encrypLion mighL be all you need Lo conceal Lhe inormaLion in your LexL
. . 8y searching or possible
equivalenLs o common characLers such as Lhe space characLer, deLermining Lhe ASCll shiL
required Lo resLore Lhe common characLer, and running Lhe conversion or Lhe enLire LexL
. Also, Lhis
sorL o encrypLion doesn'L prevenL a malicious user rom physically Lampering wiLh Lhe
iL in . 8uL i you jusL wanL Lo hide inormaLion quickly, Lhis simple encrypLion
scheme should do Lhe Lrick.
One Step lurther. Using the Xor Operator
1he
characLer code value up by jusL . However, you'll wanL Lo be careul abouL shiLing ASCll
. Keep in mind
LhaL dramaLic shiLs in ASCll codes (such as adding 500 Lo each characLer code) won'L
produce acLual ASCll characLers LhaL can be decrypLed laLer. For example, adding 500 Lo Lhe
ASCll code or Lhe leLLer A (65) would give a resulL o 565. 1his value couldn'L be LranslaLed
inLo a characLer by Lhe Chr uncLion and would generaLe an error.
One way around Lhis problem is Lo converL Lhe
Lhe numbers are. l you ollowed Lhis line o LhoughL, you could Lhen apply maLhemaLical
uncLions-mulLiplicaLion, logariLhms, and so on-Lo Lhe numbers so long as you knew how
Lo reverse Lhe resulLs.
One Lool or encrypLing numeric values is already builL inLo visual 8asic. 1his Lool is Lhe Xcr
cerctcr, which perorms Lhe "exclusive or" operaLion, a uncLion carried ouL on Lhe biLs LhaL
make up Lhe number iLsel. 1he Xcr operaLor can be observed by using a simple Ms3cx
uncLion. For example, Lhe program sLaLemenL.
MsgBox( Asc( " A") Xor 50)
would display a numeric resulL o 5 in a message box when Lhe visual 8asic compiler
execuLes iL. Likewise, Lhe program sLaLemenL.
MsgBox( 115 Xor 50)
would display a resulL o 65 in a message box, Lhe ASCll code or Lhe leLLer A (our original
value). ln oLher words, Lhe Xcr operaLor produces a resulL LhaL can be reversed-i Lhe
original Xcr . 1his inLeresLing behavior
o Lhe Xcr uncLion is used in many popular encrypLion algoriLhms. lL can make your secreL
.
342 Part II Programmng fundamentaIs
Xcr operaLor and Lhe
.
l0. On Lhe File menu, click Lhe FxiL command Lo end Lhe program.
fxamnng the fncrypton Program Code
1he Xcr operaLor is used in boLh Lhe mnuScveAsltem_Clicl and Lhe mnuOenltem_Clicl evenL
procedures. 8y now, Lhese generic menu processing rouLines will be airly amiliar Lo you. 1he
mnuScveAsltem_Clicl evenL procedure consisLs o Lhese program sLaLemenLs (noLeworLhy
lines in bold).
Di ml et t er As Char
Di mst r Code As St r i ng
Di mi , char sI nFi l e, Code As Shor t
Di mSt r eamToWr i t e As St r eamWr i t er = Not hi ng
SaveFi l eDi al og1. Fi l t er = "Text f i l es ( *. t xt ) | *. t xt "
I f SaveFi l eDi al og1. ShowDi al og( ) = Di al ogResul t . OK Then
Tr y
st r Code = I nput Box( "Ent er Encr ypt i on Code")
I f st r Code = " " Then Exi t Sub ' i f cancel cl i cked
' save t ext wi t h encr ypt i on scheme
Code = CShor t ( st r Code)
char sI nFi l e = t xt Not e. Text . Lengt h
St r eamToWr i t e = My. Comput er . Fi l eSyst em. OpenText Fi l eWr i t er ( _
SaveFi l eDi al og1. Fi l eName, Fal se)
For i = 0 To char sI nFi l e - 1
l et t er = t xt Not e. Text . Subst r i ng( i , 1)
' conver t t o number w/ Asc, t hen use Xor t o encr ypt
St r eamToWr i t e. Wr i t e( Asc( l et t er ) Xor Code) ' and save i n f i l e
' separ at e number s wi t h a space
St r eamToWr i t e. Wr i t e( " " )
Next
mnuCl oseI t em. Enabl ed = Tr ue
Cat ch ex As Except i on
Chapter l3 fxpIorng 1ext fIes and Strng Processng 343
MsgBox( "An er r or occur r ed. " & vbCr Lf & ex. Message)
Fi nal l y
I f St r eamToWr i t e I sNot Not hi ng Then
St r eamToWr i t e. Cl ose( )
End I f
End Tr y
End I f
ln Lhe Write meLhod Lhe Xcr operaLor is used Lo converL each leLLer in Lhe LexL box
Lo a numeric code, which is Lhen saved Lo disk one number aL Lime. 1he numbers are
separaLed wiLh spaces.
even Lhe nosiesL snooper.
produced by Lhe preceding encrypLion rouLine, displayed in NoLepad. (l've enabled Word
Wrap so LhaL you can see all Lhe code.)
1he mnuOenltem_Clicl evenL procedure conLains Lhe ollowing program sLaLemenLs.
(Again, pay parLicular aLLenLion Lo Lhe lines in bold.)
Di mAl l Text As St r i ng
Di mi As Shor t
Di mch As Char
Di mst r Code As St r i ng
Di mCode, Number As Shor t
Di mNumber s( ) As St r i ng
Di mDecr ypt As St r i ng = " "
OpenFi l eDi al og1. Fi l t er = "Text f i l es ( *. t xt ) | *. t xt "
I f OpenFi l eDi al og1. ShowDi al og( ) = Di al ogResul t . OK Then ' di spl ay Open di al og box
Tr y ' open f i l e and t r ap any er r or s usi ng handl er
st r Code = I nput Box( "Ent er Encr ypt i on Code")
I f st r Code = " " Then Exi t Sub ' i f cancel cl i cked
344 Part II Programmng fundamentaIs
Code = CShor t ( st r Code)
' r ead encr ypt ed number s
Al l Text = My. Comput er . Fi l eSyst em. ReadAl l Text ( OpenFi l eDi al og1. Fi l eName)
Al l Text = Al l Text . Tr i m
' spl i t number s i n t o an ar r ay based on space
Number s = Al l Text . Spl i t ( " " )
' l oop t hr ough ar r ay
For i = 0 To Number s. Lengt h - 1
Number = CShor t ( Number s( i ) ) ' conver t st r i ng t o number
ch = Chr ( Number Xor Code) ' conver t wi t h Xor
Decr ypt = Decr ypt & ch ' and bui l d st r i ng
Next
t xt Not e. Text = Decr ypt ' t hen di spl ay conver t ed st r i ng
l bl Not e. Text = OpenFi l eDi al og1. Fi l eName
t xt Not e. Sel ect ( 0, 0) ' r emove t ext sel ect i on
t xt Not e. Enabl ed = Tr ue ' al l ow t ext cur sor
mnuCl oseI t em. Enabl ed = Tr ue ' enabl e Cl ose command
mnuOpenI t em. Enabl ed = Fal se ' di sabl e Open command
Cat ch ex As Except i on
MsgBox( "An er r or occur r ed. " & vbCr Lf & ex. Message)
End Tr y
End I f
When Lhe user clicks Lhe Open FncrypLed File command, Lhis evenL procedure opens Lhe
Lhe LexL box objecL. 1he RecJAll1ext . 1he Slit meLhod spliLs
Lhe numbers as sLrings inLo an array and uses Lhe space as a separaLor. 1he lcr loop reads
each sLring in Lhe array, converLs Lhe sLring Lo a number, and sLores iL in Lhe Number shorL
inLeger variable. 1he Number variable is Lhen combined wiLh Lhe CcJe variable by using Lhe
Xcr operaLor, and Lhe resulL is converLed Lo a characLer by using Lhe Chr uncLion. 1hese
characLers (sLored in Lhe ch variable o Lype Chcr) are Lhen concaLenaLed wiLh Lhe Decryt
ch = Chr ( Number Xor Code) ' conver t wi t h Xor
Decr ypt = Decr ypt & ch ' and bui l d st r i ng
FncrypLion Lechniques like Lhis are useul, and Lhey can also be very insLrucLional. 8ecause
encrypLion relies so much on sLring-processing Lechniques, iL's a good way Lo pracLice
a undamenLal and imporLanL visual 8asic programming skill. As you become more
experienced, you can also use Lhe encrypLion services provided by Lhe .NF1 Framework Lo
add much more sophisLicaLed securiLy and crypLography services Lo your programs. For
an inLroducLion Lo Lhese Lopics, search or "CrypLographic 1asks" in Lhe visual SLudio Help
documenLaLion. 8ecause Lhese services rely somewhaL on your undersLanding o classes,
and lv o Lhis book beore you experimenL wiLh Lhem.
Well, now-congraLulaLions! l you've worked rom ChapLers 5 Lo here, you've compleLed Lhe
on creaLing proessional-qualiLy user inLeraces in your programs. ou have come a long way
349
ParL lll
Desgnng the User Interface
In ths part:
Chapter l4: Managng Wndows forms and ControIs at Run 1me . . . . . . . . . . 35l
Chapter l5: Addng Graphcs and Anmaton fffects . . . . . . . . . . . . . . . . . . . . . . 375
Chapter l6: Inhertng forms and Creatng ase CIasses . . . . . . . . . . . . . . . . . . . 393
Chapter l7: Workng wth Prnters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4l5
ln ParL ll, you learned many o Lhe core developmenL skills necessary or wriLing MicrosoL
visual 8asic applicaLions. ou learned how Lo use variables, operaLors, decision sLrucLures,
and Lhe MicrosoL . procedures,
and sLrucLured error handlers, how Lo debug your programs, and how Lo organize
.
Fach exercise you have worked wiLh so ar concenLraLed on one or more o Lhese core skills
in a simple, sLand-alone program. Real-world programs are rarely so simple. 1hey usually
require you Lo combine Lhe Lechniques in various ways and wiLh various enhancemenLs.
our programs will quiLe oLen require mulLiple orms, used as dialog boxes, inpuL and
ouLpuL orms, reporLs, and oLher elemenLs. 8ecause visual 8asic LreaLs each orm as a
separaLe objecL, you can Lhink o Lhem as simple building blocks LhaL you can combine Lo
creaLe powerul programs.
ln ParL lll, you'll ocus again on Lhe user inLerace, and you'll learn how Lo add mulLiorm
projecLs, animaLion eecLs, visual inheriLance, and prinLing supporL Lo your visual 8asic
applicaLions.
Chapter l4 Managng Wndows forms and ControIs at Run 1me 353
ou'll see a dialog box similar Lo Lhe ollowing.
ou use Lhe Add New lLem dialog box Lo add orms, classes, modules, and oLher
componenLs Lo your visual 8asic projecL. AlLhough you selecLed Lhe Add Windows
Form command, orms aren'L Lhe only componenLs lisLed here. (1he Windows Form
LemplaLe is selecLed by deaulL, however.) 1o view Lhe available LemplaLes by caLegory,
click Lhe iLems in Lhe leL pane o Lhe Add New lLem dialog box.
1p l especially recommend LhaL you experimenL wiLh Lhe Fxplorer Form LemplaLe in Lhe
Windows Forms caLegory, which allows you Lo add a Windows Fxplorer-sLyle browser Lo
your applicaLion, compleLe wiLh menus, Loolbar, and a older hierarchy pane.
4. 1ype HeIplnfo.vb in Lhe Name LexL box, and Lhen click Add.
A second orm named Helplno.vb is added Lo Lhe Lucky Seven Help projecL, and Lhe
orm opens in SoluLion Fxplorer, as shown here.
Chapter l4 Managng Wndows forms and ControIs at Run 1me 355
ll. Double-click OK Lo display Lhe 3uttcn1_Clicl evenL procedure in Lhe Code FdiLor.
l2. 1ype Lhe ollowing program sLaLemenL.
Me. Di al ogResul t = Di al ogResul t . OK
1he Helplno.vb orm acLs as a dialog box in Lhis projecL because Lhe Lucky Seven orm
opens iL using Lhe ShcwDiclc meLhod. ALer Lhe user has read Lhe Help inormaLion
displayed by Lhe dialog box, he or she will click OK, which seLs Lhe DiclcResult
properLy o Lhe currenL orm Lo DialogResulL.OK. (1he Me keyword is used here Lo reer
Lo Lhe Helplno.vb orm, and you'll see Lhis shorLhand synLax rom Lime Lo Lime when
a reerence is being made Lo Lhe currenL instcnce o a class or sLrucLure in which Lhe
code is execuLing.)
DialogResulL.OK is a visual 8asic consLanL LhaL indicaLes Lhe dialog box has been closed
and should reLurn a value o "OK" Lo Lhe calling procedure. A more sophisLicaLed
dialog box mighL allow or oLher values Lo be reLurned by parallel buLLon evenL
procedures, such as DiclcResult.Ccncel, DiclcResult.Nc, and DiclcResult.Yes.
When Lhe DiclcResult properLy is seL, however, Lhe orm is auLomaLically closed.
l3. AL Lhe Lop o Lhe Code FdiLor, Lype Lhe ollowing lmcrts sLaLemenL above Lhe Public
Clcss declaraLion.
I mpor t s Syst em. I O
1his sLaLemenL makes iL easier Lo reerence Lhe StrecmRecJer class in your code. 1he
StrecmRecJer
jusL using iL as a quick way Lo add LexLual inormaLion Lo Lhe new orm l'm creaLing.
l4. Display Lhe Helplno.vb orm again, and Lhen double-click Lhe orm background.
1he Hellnjc_lccJ evenL procedure appears in Lhe Code FdiLor. 1his is Lhe evenL
Lhe screen.
l5. 1ype Lhe ollowing program sLaLemenLs.
Di mSt r eamToDi spl ay As St r eamReader
St r eamToDi spl ay = _
New St r eamReader ( " c: \ vb10sbs\ chap14\ l ucky seven hel p\ r eadme. t xt " )
Text Box1. Text = St r eamToDi spl ay. ReadToEnd
St r eamToDi spl ay. Cl ose( )
Text Box1. Sel ect ( 0, 0)
1ext properLy o Lhe LexL box
objecL (which would Lake a long Lime), l've used Lhe StrecmRecJer class Lo open, read,
and display an appropriaLe Readme. .
operaLing insLrucLions and general conLacL inormaLion.
1he StrecmRecJer class was inLroduced in ChapLer 8, "Fxploring 1exL Files and
SLring Processing," buL you mighL noL have experimenLed wiLh iL yeL. As you learned,
StrecmRecJer is a .
My.Ccmuter.lileSystem objecL. 1o make iL easier Lo use StrecmRecJer in code, you
358 Part III Desgnng the User Interface
3. Click Lhe Help buLLon.
visual 8asic opens Lhe second orm in Lhe projecL, Helplno.vb, and displays Lhe
Readme. . 1he orm looks like Lhis.
4. .
5. 1ry Lo click Lhe Spin buLLon on Lhe LuckySeven.vb orm.
NoLice LhaL you cannoL acLivaLe Lhe LuckySeven.vb orm while Lhe Helplno.vb orm is
acLive. 8ecause Lhe Helplno.vb orm is a dialog box (a modal orm), you musL address iL
beore you can conLinue wiLh Lhe program.
6. Click OK Lo close Lhe Helplno.vb orm.
1he orm closes, and Lhe LuckySeven.vb orm becomes acLive again.
7. Click Lhe Spin buLLon a ew more Limes, and Lhen click Lhe Help buLLon again.
1he Helplno.vb orm opens again and is ully uncLional.
8. Click OK, and Lhen click Fnd on Lhe LuckySeven.vb orm.
1he program sLops, and Lhe developmenL environmenL reLurns.
Usng the DiclogResult Property n the CaIIng form
AlLhough l didn'L demonsLraLe iL in Lhe sample program, you can use Lhe DiclcResult
properLy LhaL you assigned Lo Lhe dialog box Lo greaL eecL in a visual 8asic program. As
l menLioned earlier, a more sophisLicaLed dialog box mighL provide addiLional buLLons Lo Lhe
Chapter l4 Managng Wndows forms and ControIs at Run 1me 359
user-Cancel, es, No, AborL, and so on. Fach dialog box buLLon can be associaLed wiLh a
dierenL Lype o acLion in Lhe main program. And in each o Lhe dialog box's buLLon evenL
procedures, you can assign Lhe DiclcResult properLy or Lhe orm LhaL corresponds Lo Lhe
buLLon name, such as Lhe ollowing program sLaLemenL.
Me. Di al ogResul t = Di al ogResul t . Cancel ' user cl i cked Cancel but t on
ln Lhe calling evenL procedure-in oLher words, in Lhe 3uttcnJ_Clicl evenL procedure o
LuckySeven.vb-you can wriLe addiLional program code Lo deLecL which buLLon Lhe user
clicked in Lhe dialog box. 1his inormaLion is sLored in Lhe orm's DiclcResult properLy,
which can be evaluaLed using a basic decision sLrucLure such as lj . . . 1hen or Select . . . Ccse.
For example, Lhe ollowing code can be used in Lhe 3uttcnJ_Clicl evenL procedure Lo veriy
wheLher Lhe user clicked OK, Cancel, or anoLher buLLon in Lhe dialog box.
new, buL reminds you o Lhe Helplno orm name LhaL you are using in Lhis example.)
My. For ms. Hel pI nf o. ShowDi al og( )
I f Hel pI nf o. Di al ogResul t = Di al ogResul t . OK Then
MsgBox( " The user cl i cked OK" )
El seI f Hel pI nf o. Di al ogResul t = Di al ogResul t . Cancel Then
MsgBox( " The user cl i cked Cancel ")
El se
MsgBox( " Anot her but t on was cl i cked" )
End I f
8y using creaLive evenL procedures LhaL declare, open, and process dialog box choices, you
can add any number o orms Lo your programs, and you can creaLe a user inLerace LhaL
.
Positioning lorms on the windows Desktop
ou've learned how Lo add orms Lo your visual 8asic projecL and how Lo open and close
orms by using program code. 8uL which Lool or seLLing deLermines Lhe placemenL o
orms on Lhe Windows deskLop when your program runs As you mighL have noLiced, Lhe
placemenL o orms on Lhe screen aL run Lime is dierenL rom Lhe placemenL o orms wiLhin
Lhe visual SLudio developmenL environmenL aL design Lime. ln Lhis secLion, you'll learn how
Lo posiLion your orms jusL where you wanL Lhem aL run Lime so LhaL users see jusL whaL you
wanL Lhem Lo see.
1he Lool you use isn'L a graphical layouL window buL a properLy named Desltc3cunJs LhaL
is mainLained or each orm in your projecL. Desltc3cunJs can be read or seL only aL run
Chapter l4 Managng Wndows forms and ControIs at Run 1me 36l
Changing Lhe StcrtPcsiticn properLy Lo CenLerScreen direcLs visual 8asic Lo display Lhe
orm in Lhe cenLer o Lhe Windows deskLop when you run Lhe program.
5. Click Lhe SLarL Debugging buLLon Lo run Lhe applicaLion.
visual 8asic loads Lhe orm and displays iL in Lhe middle o Lhe screen, as shown here.
6. Click Lhe Close buLLon on Lhe orm Lo sLop Lhe program.
1he lDF reLurns.
7. SeL Lhe StcrtPcsiticn properLy Lo Manual.
1he Mcnucl properLy seLLing direcLs visual 8asic Lo posiLion Lhe orm based on Lhe
values in Lhe lcccticn properLy.
8. SeL Lhe lcccticn properLy Lo 00, 50.
1he lcccticn
Lhe orm.
9. Click Lhe SLarL Debugging buLLon Lo run Lhe applicaLion.
visual 8asic loads Lhe orm and Lhen displays iL on Lhe Windows deskLop 00 pixels rom
Lhe leL and 50 pixels rom Lhe Lop, as shown in Lhe screen shoL on Lhe ollowing page.
Chapter l4 Managng Wndows forms and ControIs at Run 1me 363
' Di spl ay t he f or mas a modal di al og box
f or m2. ShowDi al og( )
When Lhe user clicks Lhe CreaLe Form buLLon, Lhis evenL procedure creaLes a new orm
. 1o use program code Lo creaLe
a new orm, you use Lhe Dim sLaLemenL and speciy a variable name or Lhe orm
and Lhe lcrm class, which is auLomaLically included in projecLs as parL o Lhe System.
WinJcws.lcrms namespace. ou can Lhen seL properLies such as 1ext, lcrm3crJerStyle,
StcrtPcsiticn, and Desltc3cunJs.
1he StcrtPcsiticn properLy is seL Lo lcrmStcrtPcsiticn.Mcnucl Lo indicaLe LhaL Lhe
posiLion will be seL manually. 1he Desltc3cunJs properLy sizes and posiLions Lhe
orm and requires an argumenL o Lype Rectcnle. 1he Rectcnle Lype is a sLrucLure
LhaL projecLs.
Using Lhe Dim sLaLemenL, Lhe lcrm2Rect variable is declared o Lype Rectcnle
and iniLialized wiLh Lhe orm posiLion and size values. AL Lhe boLLom o Lhe evenL
procedure, Lhe new orm is opened as a dialog box using Lhe ShcwDiclc meLhod.
AlLhough l usually recommend placing your Dim sLaLemenLs LogeLher aL Lhe Lop o Lhe
orm, here l have placed one a liLLle lower in Lhe code Lo make iL easier Lo undersLand
Lhe conLexL and use o Lhe variable.
1p 1he compleLe DeskLop 8ounds program is locaLed in Lhe C.\vb0sbs\Chap4\DeskLop
8ounds older.
4. Click Lhe SLarL Debugging buLLon Lo run Lhe program.
.
5. Click Lhe CreaLe Form buLLon.
visual 8asic displays Lhe My New Form dialog box wiLh Lhe size and posiLion you
364 Part III Desgnng the User Interface
NoLice LhaL you can'L resize Lhe second orm because lcrm3crJerStyle was seL Lo
FixedDialog.
6. .
our program sLops running, and Lhe lDF reLurns.
7. Click Lhe Save All buLLon, and Lhen speciy Lhe C.\vb0sbs\Chap4 older as Lhe locaLion.
Mnmzng, Maxmzng, and Restorng Wndows
ln addiLion Lo esLablishing Lhe size and locaLion o a visual 8asic orm, you can minimize
a orm Lo Lhe Windows Laskbar, maximize a orm so LhaL iL Lakes up Lhe enLire screen, or
resLore a orm Lo iLs normal shape. 1hese seLLings can be changed aL design Lime or aL run
Lime based on currenL program condiLions.
minimize and maximize boxes are available. Using Lhe ProperLies window or program code,
you speciy Lhe ollowing seLLings.
f or m2. Maxi mi zeBox = Tr ue
f or m2. Mi ni mi zeBox = Tr ue
1hen, in program code or by using Lhe ProperLies window, you seL Lhe WinJcwStcte
properLy or Lhe orm Lo Minimized, Maximized, or Normal. (ln code, you need Lo add Lhe
lcrmWinJcwStcte consLanL, as shown below.) For example, Lhe ollowing program sLaLemenL
minimizes orm2 Lo Lhe Windows Laskbar.
f or m2. Wi ndowSt at e = For mWi ndowSt at e. Mi ni mi zed
l you wanL Lo conLrol Lhe maximum or minimum size o a orm, seL Lhe McximumSize
or MinimumSize properLies aL design Lime by using Lhe ProperLies window. 1o seL Lhe
McximumSize or MinimumSize in code, you'll need Lo use a Size sLrucLure (which is similar
Lo Lhe Rectcnle sLrucLure used in Lhe previous exercise), as shown here.
Di mFor mSi ze As New Si ze( 400, 300)
f or m2. Maxi mumSi ze = For mSi ze
Adding ControIs to a lorm at kun Time
1hroughouL Lhis book, you've added objecLs Lo orms by using Lhe 1oolbox and Lhe Designer.
However, as Lhe previous exercise demonsLraLed, you can also creaLe visual 8asic objecLs
on orms aL run Lime, eiLher Lo save developmenL Lime (i you're copying rouLines you have
used beore) or Lo respond Lo a currenL need in Lhe program. For example, you mighL wanL
Lo generaLe a simple dialog box conLaining objecLs LhaL process inpuL only under cerLain
condiLions.
366 Part III Desgnng the User Interface
5. 1ype Lhe ollowing program code.
' Decl ar e new f or mand cont r ol obj ect s
Di mf or m2 As New For m
Di ml bl Dat e As New Label
Di mbt nCancel As New But t on
' Set l abel pr oper t i es
l bl Dat e. Text = "Cur r ent dat e i s: " & Dat eSt r i ng
l bl Dat e. Si ze = New Si ze( 150, 50)
l bl Dat e. Locat i on = New Poi nt ( 80, 50)
' Set but t on pr oper t i es
bt nCancel . Text = " Cancel "
bt nCancel . Locat i on = New Poi nt ( 110, 100)
' Set f or mpr oper t i es
f or m2. Text = "Cur r ent Dat e"
f or m2. Cancel But t on = bt nCancel
f or m2. St ar t Posi t i on = For mSt ar t Posi t i on. Cent er Scr een
' Add new obj ect s t o Cont r ol s col l ect i on
f or m2. Cont r ol s. Add( l bl Dat e)
f or m2. Cont r ol s. Add( bt nCancel )
' Di spl ay f or mas a di al og box
f or m2. ShowDi al og( )
1his evenL procedure displays a new orm conLaining a label objecL and a buLLon
objecL on Lhe screen. 1he label objecL conLains Lhe currenL daLe as recorded by your
compuLer's sysLem clock (reLurned Lhrough DcteStrin). 1he 1ext properLy o Lhe buLLon
objecL is seL Lo "Cancel."
As l menLioned earlier, you add conLrols Lo a orm by declaring a variable Lo hold Lhe
conLrol, seLLing objecL properLies, and adding Lhe objecLs Lo Lhe Ccntrcls collecLion. ln
Lhis exercise, l also demonsLraLe Lhe Size and Ccncel3uttcn .
1he Size properLy requires a Size sLrucLure. 1he New keyword is used Lo immediaLely
creaLe Lhe Size sLrucLure. 1he Ccncel3uttcn properLy allows Lhe user Lo close Lhe dialog
box by pressing FSC or clicking Lhe Cancel buLLon. (1he Lwo acLions are equivalenL.)
6. Click Lhe Save All buLLon, and Lhen speciy Lhe C.\vb0sbs\Chap4 older as Lhe locaLion.
1p 1he compleLe Add ConLrols program is locaLed in Lhe C.\vb0sbs\Chap4\Add
ConLrols older.
7. Click Lhe SLarL Debugging buLLon Lo run Lhe program.
.
8. Click Lhe Display DaLe buLLon.
Chapter l4 Managng Wndows forms and ControIs at Run 1me 367
visual 8asic displays Lhe second orm. 1his orm conLains Lhe label and buLLon objecLs
. 1he label objecL conLains Lhe currenL daLe, as
shown here.
9. Click Lhe Cancel buLLon Lo close Lhe new orm.
l0. Click Lhe Display DaLe buLLon again.
.
ll. Press FSC Lo close Lhe orm.
8ecause you seL Lhe Ccncel3uttcn properLy Lo Lhe btnCcncel objecL, clicking Cancel
and pressing FSC produce Lhe same resulL.
l2. Click Lhe Close buLLon on Lhe orm Lo end Lhe program.
1he program sLops, and Lhe developmenL environmenL reLurns.
Organizing ControIs on a lorm
When you add conLrols Lo a orm programmaLically, iL Lakes a biL o Lrial and error Lo
posiLion Lhe new objecLs so LhaL Lhey're aligned properly and look nice. ALer all, you don'L
have Lhe visual SLudio Designer Lo help you-jusL Lhe (x, y) coordinaLes o Lhe lcccticn
and Size properLies, which are clumsy values Lo work wiLh unless you have a knack or
Chapter l4 Managng Wndows forms and ControIs at Run 1me 369
our orm looks similar Lo Lhis.
l6. Double-click Lhe Align Now buLLon Lo open Lhe 3uttcn1_Clicl evenL procedure in Lhe
Code FdiLor.
l7. 1ype Lhe ollowing program code.
Pi ct ur eBox1. Dock = DockSt yl e. Top
Text Box1. Anchor = Anchor St yl es. Bot t omOr _
Anchor St yl es. Lef t Or Anchor St yl es. Ri ght Or _
Anchor St yl es. Top
But t on1. Anchor = Anchor St yl es. Bot t omOr _
Anchor St yl es. Ri ght
When Lhis evenL procedure is execuLed, Lhe Dccl properLy o Lhe Picture3cx1 objecL
is used Lo dock Lhe picLure box Lo Lhe Lop o Lhe orm. 1his orces Lhe Lop edge o Lhe
picLure box objecL Lo Louch and adhere Lo Lhe Lop edge o Lhe orm-much as Lhe
visual SLudio docking eaLure works in Lhe lDF. 1he only surprising behavior here is LhaL
Lhe picLure box objecL is also resized so LhaL iLs sides adhere Lo Lhe leL and righL edges
o Lhe orm.
NexL, Lhe Anchcr properLy or Lhe 1ext3cx1 and 3uttcn1 objecLs is used. 1he Anchcr
i Lhe orm is resized. NoLe LhaL Lhe Anchcr properLy mainLains Lhe objecL's currenL
unless iL's already Lhere. ln Lhis example, l speciy LhaL Lhe 1ext3cx1 objecL should
be anchored Lo all our edges o Lhe orm (boLLom, leL, righL, and Lop). l use Lhe Or
operaLor Lo combine my edge selecLions. l anchor Lhe 3uttcn1 objecL Lo Lhe boLLom
and righL edges o Lhe orm.
l8. Save Lhe projecL, and Lhen speciy Lhe C.\vb0sbs\Chap4 older as Lhe locaLion.
370 Part III Desgnng the User Interface
1p 1he compleLe Anchor and Dock program is locaLed in Lhe C.\vb0sbs\Chap4\Anchor
and Dock older.
l9. Click Lhe SLarL Debugging buLLon Lo run Lhe program.
1he orm opens, jusL as you designed iL.
20. Move Lhe poinLer Lo Lhe lower-righL corner o Lhe orm unLil iL changes inLo a Resize
poinLer, and Lhen enlarge Lhe orm.
NoLice LhaL Lhe size and posiLion o Lhe objecLs on Lhe orm do noL change.
2l. ReLurn Lhe orm Lo iLs original size.
22. Click Lhe Align Now buLLon on Lhe orm.
1he picLure box objecL is now docked aL Lhe Lop edge o Lhe orm. 1he picLure box
is also resized so LhaL iLs sides adhere Lo Lhe leL and righL edges o Lhe orm, as
shown here.
NoLice LhaL Lhe Sun icon in Lhe picLure box is now disLorLed, which is a resulL o Lhe
docking process.
23. Fnlarge Lhe orm again.
As you resize Lhe orm, Lhe picLure box and LexL box objecLs are also resized. 8ecause
Lhe LexL box is anchored on all our sides, Lhe disLance beLween Lhe edges o Lhe
orm and Lhe LexL box remains consLanL. During Lhe resizing acLiviLy, iL also becomes
apparenL LhaL Lhe buLLon objecL is being reposiLioned. AlLhough Lhe disLance beLween
372 Part III Desgnng the User Interface
4. Click Add Lo add Lhe second orm (Form2.vb) Lo SoluLion Fxplorer.
5. Click My SLarLup Form ProperLies on Lhe ProjecL menu.
1he ProjecL Designer opens, as shown here.
1he ProjecL Designer leLs you adjusL seLLings LhaL apply Lo Lhe enLire projecL in one
place. Here you'll use Lhe ApplicaLion Lab and Lhe SLarLup Form lisL box Lo speciy a new
sLarLup orm.
6. On Lhe ApplicaLion Lab, click Lhe SLarLup Form arrow, and Lhen click Form2.
visual 8asic changes Lhe sLarLup orm in your projecL rom Form Lo Form2. When Lhe
program runs, Form2 will be displayed, and Form will appear only i iL's opened using
Lhe Shcw or ShcwDiclc meLhod.
7. Click Lhe Close buLLon Lo close Lhe ProjecL Designer.
8. Click Lhe SLarL Debugging buLLon.
1he program runs in Lhe developmenL environmenL, and Form2 opens.
9. Click Lhe Close buLLon on Lhe orm Lo end Lhe program.
l0. Close Lhe projecL, and discard your changes-iL is noL necessary Lo save Lhis simple
.
375
ChapLer 5
Addng Graphcs
and Anmaton fffects
After compIetng ths chapter, you wII be abIe to:
Use Lhe System.Drcwin namespace Lo add graphics Lo your orms.
CreaLe animaLion eecLs on your orms.
Fxpand or shrink objecLs on a orm aL run Lime.
Change Lhe Lransparency o a orm.
For many developers, adding arLwork and special eecLs Lo an applicaLion is Lhe mosL
exciLing-and addicLive-parL o programming. ForLunaLely, creaLing impressive and useul
graphical eecLs wiLh MicrosoL visual 8asic 200 is boLh saLisying and easy.
ln Lhis chapLer, you'll learn how Lo add a number o visually inLeresLing eaLures Lo
your programs. ou'll learn how Lo creaLe arLwork on a orm using Lhe System.Drcwin
namespace, how Lo creaLe simple animaLion eecLs by using Picture3cx and 1imer
conLrols, and how Lo expand or shrink objecLs aL run Lime by using Lhe Heiht and WiJth
properLies. ou'll also learn how Lo change Lhe Lransparency o Lhe orm and change
a orm's background image and color.
you need Lo creaLe a visually exciLing user inLerace.
WhaL will you be able Lo do on your own 1his is Lhe poinL when your imaginaLion Lakes
over. One o my avoriLe resulLs is rom a reader o a previous version o Lhis book who used
whaL he had learned abouL visual 8asic and graphics Lo build his own elecLrocardiograph
machine, compleLe wiLh analog circuiLry and a Windows orm displaying digiLal daLa rom
Lhe homemade elecLrocardiogram. l Lhis isn'L your idea o un, you mighL decide on a more
modesL goal. Lo enhance your applicaLion's sLarL page so LhaL iL conLains cusLom arLwork
and visual eecLs-perhaps in combinaLion wiLh one or more digiLal phoLographs loaded
inLo picLure box objecLs on a orm.
Fven game programmers can have some serious un using graphics in visual 8asic and
MicrosoL visual SLudio. However, i you're planning on creaLing Lhe nexL version o MicrosoL
Zoo 1ycoon or MicrosoL Halo, you had beLLer plan or much more Lhan visual ouLpuL.
Modern video games conLain huge libraries o objecLs and complex ormulas or rendering
graphical images LhaL go well beyond Lhe scope o Lhis book. 8uL LhaL sLill leaves a loL o
room or experimenLaLion and un!
376 Part III Desgnng the User Interface
Adding Artwork by Using
the System.Drowing Namespace
Adding ready-made arLwork Lo your programs is easy in visual 8asic. 1hroughouL Lhis book,
you've experimenLed wiLh adding biLmaps and icons Lo a orm by using picLure box objecLs.
Now you'll learn how Lo creaLe original arLwork on your orms by using Lhe CDl- uncLions
in Lhe System.Drcwin namespace, an applicaLion programming inLerace (APl) provided
by Lhe MicrosoL .NF1 Framework or creaLing Lwo-dimensional vecLor graphics, imaging,
and Lypography wiLhin Lhe Windows operaLing sysLem. 1he eecLs LhaL you creaLe can add
color, shape, and LexLure Lo your orms.
Usng a form's Coordnate System
coordinaLe sysLem. ln visual 8asic, each orm has iLs own coordinaLe sysLem. 1he coordinaLe
sysLem's sLarLing poinL, or criin, is Lhe upper-leL corner o a orm. 1he deaulL coordinaLe
sysLem is made up o rows and columns o device-independenL picLure elemenLs, or ixels,
which represenL Lhe smallesL poinLs LhaL you can locaLe, or cJJress, on a visual 8asic orm.
ln Lhe visual 8asic coordinaLe sysLem, rows o pixels are aligned Lo Lhe x-axis (horizonLal
axis), and columns o pixels are aligned Lo Lhe y-axis (verLical axis).
in Lhe coordinaLe sysLem by idenLiying Lhe inLersecLion o a row and a column wiLh Lhe
noLaLion (x, y). For example, i you decide Lo place a picLure box objecL on a orm in your
projecL, Lhe (x, y) coordinaLes or Lhe objecL will indicaLe where Lhe upper-leL corner
o Lhe picLure box is locaLed on Lhe orm. Also keep in mind LhaL Lhe (x, y) coordinaLes
o Lhe upper-leL corner o a orm are always (0, 0)-LhaL is Lhe origin LhaL everyLhing is
measured rom.
visual 8asic works in collaboraLion wiLh your compuLer's video display driver soLware Lo
deLermine how pixels are displayed on Lhe orm and how shapes such as lines, recLangles,
curves, and circles are displayed. Occasionally, more Lhan one neighboring pixel is Lurned
on Lo display a parLicular shape, such as a diagonal line LhaL appears on a orm. 1he logic
LhaL handles Lhis Lype o rendering isn'L your responsibiliLy-iL's handled by your display
adapLer and Lhe drawing rouLines in Lhe CDl- graphics library. Occasionally, Lhis will produce
a disLorLed or jagged resulL, buL iL is rarely anyLhing more Lhan a slighL visual gliLch.
1he System.Drcwing.Crcphics CIass
1he System.Drcwin namespace includes numerous classes or creaLing arLwork and special
eecLs in your programs. ln Lhis secLion, you'll learn a liLLle abouL Lhe System.Drcwin.
Crchics class, which provides meLhods and properLies or drawing shapes on your orms.
ou can learn abouL Lhe oLher classes by reerring Lo Lhe visual SLudio Help documenLaLion.
Chapter l5 Addng Graphcs and Anmaton fffects 379
' Use a gr een br ush col or t o cr eat e a f i l l ed r ect angl e
Di mBr ushCol or As New Sol i dBr ush( Col or . Gr een)
Gr aphi csFun. Fi l l Rect angl e( Br ushCol or , 150, 10, 250, 100)
' Cr eat e a bl ue car di nal spl i ne cur ve wi t h f our poi nt s
Di mPoi nt s( ) As Poi nt = {New Poi nt ( 358, 280) , _
New Poi nt ( 300, 320) , New Poi nt ( 275, 155) , New Poi nt ( 350, 180) }
For t ensi on As Si ngl e = 0 To 2. 5 St ep 0. 5
Gr aphi csFun. Dr awCur ve( Pens. Dodger Bl ue, Poi nt s, t ensi on)
Next
1his sample evenL procedure draws our graphic shapes on your orm. a red line, a red
. 1o enable graphics programming, Lhe rouLine declares a variable named
Crchicslun in Lhe code and uses Lhe CrecteCrchics meLhod Lo acLivaLe or insLanLiaLe
Lhe variable. 1he PenCclcr variable o Lype Pen is used Lo seL Lhe drawing color in Lhe
line and ellipse, and Lhe 3rushCclcr variable o Lype ScliJ3rush
color in Lhe recLangle. 1hese examples are obviously jusL Lhe Lip o Lhe graphics library
iceberg-Lhere are many more shapes, colors, and variaLions LhaL you can creaLe by
using Lhe meLhods in Lhe System.Drcwin.Crchics class.
1p 1he compleLe Draw Shapes program is locaLed in Lhe C.\vb0sbs\Chap5\Draw
Shapes older.
9. Click Lhe SLarL Debugging buLLon on Lhe SLandard Loolbar Lo run Lhe program.
visual 8asic loads Lhe orm and execuLes Lhe orm's Pcint evenL. our orm looks
like Lhis.
l0. Minimize Lhe orm, and Lhen resLore iL again.
1he orm's Pcint evenL is execuLed again, and Lhe graphics shapes are rereshed on
Lhe orm.
Chapter l5 Addng Graphcs and Anmaton fffects 38l
1o move a relaLive disLance Lo Lhe righL or leL, you would add or subLracL pixels rom Lhe
currenL lejt properLy seLLing. For example, Lo move an objecL 50 pixels Lo Lhe righL, you add
50 Lo Lhe lejt properLy, as ollows.
Pi ct ur eBox1. Lef t = Pi ct ur eBox1. Lef t + 50
ln a similar way, you can change Lhe verLical locaLion o an objecL on a orm by seLLing Lhe
1c properLy, which Lakes Lhe synLax.
obj ect . Top = ver t i cal
where cbject is Lhe name o Lhe objecL on Lhe orm LhaL you wanL Lo move, and verticcl is
Lhe new verLical, or y-axis, coordinaLe o Lhe Lop edge o Lhe objecL, measured in pixels.
For example, Lhe ollowing program sLaLemenL moves a picLure box objecL Lo a locaLion
50 pixels below Lhe window's LiLle bar.
Pi ct ur eBox1. Top = 150
RelaLive movemenLs down or up are easily made by adding or subLracLing pixels rom Lhe
currenL 1c properLy seLLing. For example, Lo move 80 pixels in a downward direcLion, you
add 80 Lo Lhe currenL 1c properLy, as ollows.
Pi ct ur eBox1. Top = Pi ct ur eBox1. Top + 30
1he Locction Property
1o move an objecL in boLh verLical and horizonLal direcLions, you can use a combinaLion o
Lhe lejt and 1c properLy seLLings. For example, Lo relocaLe Lhe upper-leL corner o a picLure
box objecL Lo Lhe (x, y) coordinaLes (800, 200), you enLer Lhe ollowing program code.
Pi ct ur eBox1. Lef t = 300
Pi ct ur eBox1. Top = 200
However, Lhe designers o visual SLudio don'L recommend using Lwo program sLaLemenLs
Lo relocaLe an objecL i you plan Lo make numerous objecL movemenLs in a program (or
example, i you plan Lo move an objecL hundreds or Lhousands o Limes during an elaboraLe
animaLion eecL). lnsLead, you should use Lhe lcccticn properLy wiLh Lhe synLax.
obj ect . Locat i on = New Poi nt ( hor i zont al , ver t i cal )
where cbject is Lhe name o Lhe objecL, hcrizcntcl is Lhe horizonLal x-axis coordinaLe, verticcl
is Lhe verLical y-axis coordinaLe, and Pcint is a sLrucLure idenLiying Lhe pixel locaLion or
Lhe upper-leL corner o Lhe objecL. For example, Lhe ollowing program sLaLemenL moves
a picLure box objecL Lo an (x, y) coordinaLe o (800, 200).
Pi ct ur eBox1. Locat i on = New Poi nt ( 300, 200)
384 Part III Desgnng the User Interface
l3. Double-click Lhe Move Up buLLon Lo ediL iLs evenL procedure.
1he 3uttcn1_Clicl evenL procedure appears in Lhe Code FdiLor.
l4. 1ype Lhe ollowing program code.
Goi ngUp = Tr ue
Ti mer 1. Enabl ed = Tr ue
1his simple evenL procedure seLs Lhe CcinU variable Lo 1rue and enables Lhe Limer
objecL. 1he acLual program code Lo move Lhe picLure box objecL and sense Lhe correcL
direcLion is sLored in Lhe 1imer1_1icl evenL procedure. 1he CcinU variable has
a jagged underline now because you have noL declared iL yeL.
l5. Near Lhe Lop o Lhe orm's program code (below Lhe sLaLemenL Public Clcss lcrm1),
Lype Lhe ollowing variable declaraLion.
Di mGoi ngUp As Bool ean ' Goi ngUp st or es cur r ent di r ect i on
1his variable declaraLion makes CcinU available Lo all Lhe evenL procedures in Lhe
orm, so Lhe jagged underline in Lhe 3uttcn1_Clicl evenL procedure is removed. l've
used a 3cclecn variable because Lhere are only Lwo possible direcLions or movemenL
in Lhis program-up and down.
l6. Display Lhe orm again, double-click Lhe Move Down buLLon, and Lhen enLer Lhe
ollowing program code in Lhe 3uttcn2_Clicl evenL procedure.
Goi ngUp = Fal se
Ti mer 1. Enabl ed = Tr ue
1his rouLine is very similar Lo Lhe 3uttcn1_Clicl evenL procedure, excepL LhaL iL changes
Lhe direcLion rom up Lo down.
l7. Display Lhe orm again, double-click Lhe 1imer1 objecL, and Lhen enLer Lhe ollowing
program code in Lhe 1imer1_1icl evenL procedure.
I f Goi ngUp = Tr ue Then
' move pi ct ur e box t owar d t he t op
I f Pi ct ur eBox1. Top > 10 Then
Pi ct ur eBox1. Locat i on = New Poi nt _
( Pi ct ur eBox1. Locat i on. X - 10, _
Pi ct ur eBox1. Locat i on. Y - 10)
End I f
El se
' move pi ct ur e box t owar d t he bot t om
I f Pi ct ur eBox1. Top < ( Me. Si ze. Hei ght - 75) Then
Pi ct ur eBox1. Locat i on = New Poi nt _
( Pi ct ur eBox1. Locat i on. X + 10, _
Pi ct ur eBox1. Locat i on. Y + 10)
End I f
End I f
388 Part III Desgnng the User Interface
1p 1he compleLe Zoom ln program is locaLed in Lhe C.\vb0sbs\Chap5\Zoom ln older.
9. Click Lhe SLarL Debugging buLLon Lo run Lhe program.
1he FarLh image appears alone on Lhe orm.
SLars appear in Lhe background because you have loaded Lhe Space.
orm wiLh Lhe 3ccllmce properLy. Any area noL covered by Lhe 3ccllmce properLy
on Lhe orm will be black because you've used Lhe 3cclCclcr properLy Lo simulaLe Lhe
quieL melancholy o ouLer space.
l0. Click Lhe FarLh image several Limes Lo expand iL on Lhe screen.
ALer 0 or clicks, your screen looks similar Lo Lhis.
8ecause Lhe image has a relaLively low resoluLion, iL will evenLually become somewhaL
blurry i you magniy iL much more. ou can address Lhis limiLaLion by saving smaller
images aL a higher resoluLion. 1he wispy clouds on FarLh miLigaLe Lhe blurring problem
in Lhis example, however. (ln prinL, Lhis will noL look LhaL greaL, so be sure Lo Lry iL ouL
on your compuLer and see Lhe image in color!)
ll. When you geL close enough Lo esLablish a sLandard orbiL, click Lhe Close buLLon Lo quiL
Lhe program.
1he program sLops, and Lhe developmenL environmenL reLurns.
One Step lurther. Changing lorm Transparency
impossible in earlier versions o visual 8asic. For example, you can make a orm parLially
LransparenL so LhaL you can see Lhrough iL. LeL's say you're designing a phoLo-display
393
ChapLer 6
Inhertng forms and Creatng
ase CIasses
After compIetng ths chapter, you wII be abIe to:
Use Lhe lnheriLance Picker Lo incorporaLe exisLing orms in your projecLs.
CreaLe your own base classes wiLh cusLom properLies and meLhods.
Derive new classes rom base classes by using Lhe lnherits sLaLemenL.
An imporLanL skill or virLually all proessional soLware developers Loday is Lhe abiliLy
Lo undersLand and uLilize cbject-crienteJ rcrcmmin (OOP) Lechniques. 1he changes
associaLed wiLh OOP have been gaining momenLum in recenL versions o MicrosoL visual
8asic, including eaLures LhaL supporL inheritcnce, a mechanism LhaL allows one class Lo
acquire Lhe inLerace and behavior characLerisLics o anoLher class.
lnheriLance in visual 8asic 200 is aciliLaLed by boLh Lhe visual 8asic language and Lools wiLhin
Lhe lnLegraLed DevelopmenL FnvironmenL (lDF). WhaL Lhis means is LhaL you can build one
orm in Lhe developmenL environmenL and pass on iLs characLerisLics and uncLionaliLy Lo oLher
orms. ln addiLion, you can build your own classes and inheriL properLies, meLhods, and evenLs
rom Lhem.
ln Lhis chapLer, you'll experimenL wiLh boLh Lypes o inheriLance. ou'll learn how Lo inLegraLe
exisLing orms inLo your projecLs by using Lhe lnheriLance Picker dialog box LhaL is parL o
MicrosoL visual SLudio 200, and you'll learn how Lo creaLe your own classes and derive new
ones rom Lhem by using Lhe lnherits sLaLemenL. WiLh Lhese skills, you'll be able Lo uLilize many
o Lhe orms and coding rouLines you've already developed, making visual 8asic programming
. 1hese improvemenLs will help you design compelling user
inLeraces rapidly and will exLend Lhe work LhaL you have done in oLher programming projecLs.
lnheriting a lorm by Using the lnheritance Picker
ln OOP synLax, inheritcnce means having one class receive Lhe objecLs, properLies,
meLhods, and oLher aLLribuLes o anoLher class. As l menLioned in Lhe secLion "Adding
New Forms Lo a Program" in ChapLer 4, "Managing Windows Forms and ConLrols
aL Run 1ime," visual 8asic goes Lhrough Lhis process rouLinely when iL creaLes a new
orm in Lhe developmenL environmenL. lcrm1) relies on Lhe
Chapter l6 Inhertng forms and Creatng ase CIasses 395
Now you'll pracLice inheriLing Lhe orm.
ccmilin, Lhe projecL because you can inheriL only rom orms LhaL are compiled inLo
.exe or . . Fach Lime Lhe base orm is recompiled, changes made Lo Lhe base orm
are passed Lo Lhe derived (inheriLed) orm.
9. Click Lhe 8uild My Form lnheriLance command on Lhe 8uild menu.
visual 8asic compiles your projecL and creaLes an . .
l0. Click Lhe Add New lLem command on Lhe ProjecL menu, and Lhen click Lhe Windows
Forms caLegory on Lhe leL side o Lhe dialog box and Lhe lnheriLed Form LemplaLe in
Lhe middle o Lhe dialog box.
1he Add New lLem dialog box looks as shown in Lhe ollowing screen shoL.
Note visual 8asic 200 Fxpress does noL include Lhe lnheriLed Form LemplaLe. l you are
.
(ln general, Proessional and Lhe oLher ull versions o visual SLudio provide a number
o addiLional LemplaLes LhaL are useul.) AL Lhis poinL, you may wanL Lo simply review
Lhe sample projecL LhaL l have included on Lhe PracLice Files CD and examine Lhe code.
However Lhere is a work-around LhaL you can aLLempL Lo creaLe an inheriLed orm manually.
1o Lry iL, add a Windows Form named Form2.vb Lo your projecL insLead o lnheriLed Form.
AL Lhe Lop o SoluLion Fxplorer, click Lhe Show All Files Loggle buLLon. Fxpand Form2.vb and
Lhen open Form2.Designer.vb. Change "lnheriLs SysLem.Windows.Forms.Form" Lo "lnheriLs
My_Form_lnheriLance.Form." Click Save All, close Form2.Designer.vb, and Lhen click Show
. Since you perormed Lhe sLeps manually, you can
now skip Lo Lhe nexL secLion, "CusLomize Lhe lnheriLed Form."
396 Part III Desgnng the User Interface
As usual, visual SLudio lisLs all Lhe possible LemplaLes you could include in your projecLs,
noL jusL Lhose relaLed Lo inheriLance. 1he lnheriLed Form LemplaLe gives you access Lo
Lhe lnheriLance Picker dialog box.
ou can also use Lhe Name LexL box aL Lhe boLLom o Lhe dialog box Lo assign a name
Lo your inheriLed orm, alLhough iL is noL necessary or Lhis example. 1his name will
.
ll. Click Add Lo accepL Lhe deaulL seLLings or Lhe new, inheriLed orm.
visual SLudio displays Lhe lnheriLance Picker dialog box, as shown here.
1his dialog box lisLs all Lhe inheriLable orms in Lhe currenL projecL. l you wanL Lo
browse or anoLher compiled orm, click Lhe 8rowse buLLon and locaLe Lhe .
your sysLem.
Note l you wanL Lo inheriL a orm LhaL isn'L a componenL o Lhe currenL projecL, Lhe orm
musL be compiled as a . .
l2. Click Form in Lhe lnheriLance Picker dialog box, and Lhen click OK.
visual SLudio creaLes Lhe Form2.vb enLry in SoluLion Fxplorer and displays Lhe inheriLed
orm in Lhe Designer. NoLice in Lhe screen shoL aL Lhe Lop o Lhe ollowing page LhaL
Lhe orm looks idenLical Lo Lhe Form window you creaLed earlier excepL LhaL Lhe Lwo
buLLons conLain Liny icons, which indicaLe LhaL Lhe objecLs come rom an inheriLed
source.
icons aren'L LhaL obvious), buL you can also use SoluLion Fxplorer and Lhe lDF Labs Lo
disLinguish beLween Lhe orms.
398 Part III Desgnng the User Interface
6. Fnlarge Lhe orm.
. And in addiLion Lo modiying Lhe size, you can change Lhe locaLion
and oLher display or operaLional characLerisLics o Lhe orm. NoLice LhaL i you use Lhe
ProperLies window Lo cusLomize a orm, Lhe ObjecL lisL box in Lhe ProperLies window
displays Lhe orm rom which Lhe currenL orm is derived. Here's whaL Lhe ProperLies
window looks like in your projecL when Form2 is selecLed.
Now seL Lhe sLarLup objecL in your projecL Lo Form2.
7. Click Lhe My Form lnheriLance ProperLies command on Lhe ProjecL menu.
1he ProjecL Designer, inLroduced in ChapLer 4, appears.
8. On Lhe ApplicaLion Lab, click Lhe SLarLup Form lisL box, click Form2, and Lhen close Lhe
ProjecL Designer by clicking Lhe Close buLLon on Lhe Lab.
1here is no Save buLLon in Lhe ProjecL Designer because visual SLudio saves your
changes as you make Lhem in Lhe dialog box. Now run Lhe new projecL.
1p 1he compleLe Form lnheriLance program is locaLed in Lhe C.\vb0sbs\Chap6\Form
lnheriLance older.
9. Click Lhe SLarL Debugging buLLon.
1he inheriLed orm opens, as shown here. (My version is shown slighLly enlarged aLer
ollowing sLep 6 earlier in Lhis exercise.)
Chapter l6 Inhertng forms and Creatng ase CIasses 399
l0. Click OK.
1he inheriLed orm runs Lhe evenL procedure LhaL iL inheriLed rom Form, and Lhe
evenL procedure displays Lhe ollowing message.
ll. Click OK, and Lhen click Lhe Click Me! buLLon.
Form2 displays Lhe inheriLed orm message.
WhaL Lhis demonsLraLes is LhaL Form2 (Lhe inheriLed orm) has iLs own characLerisLics
(a new Click Me! buLLon and an enlarged size). Form2 also uses Lwo buLLons (OK
and Cancel) LhaL were inheriLed rom Form and conLain Lhe code rom Form, as well
as Lhe exacL visual represenLaLion o Lhe buLLons. 1his means LhaL you can redeploy
Lhe user inLerace and code eaLures LhaL you have previously creaLed wiLhouL
cumbersome cuLLing and pasLing. ln oLher words, you've encounLered one o Lhe main
code, and projecLs. ou've also learned Lo use Lhe visual SLudio lnheriLance Picker
dialog box, which oers a handy way Lo selecL objecLs you wanL Lo reuse.
l2. Click OK Lo close Lhe message box, and Lhen click Close on Lhe orm Lo end Lhe
program.
1he program sLops, and Lhe lDF reLurns.
Creating Your Own Base CIasses
1he lnheriLance Picker managed Lhe inheriLance process in Lhe previous exercise by creaLing
a new class in your projecL named lcrm2. 1o build Lhe lcrm2 class, Lhe lnheriLance Picker
esLablished a link beLween Lhe lcrm1 class in Lhe My Form lnheriLance projecL and Lhe new
orm. Here's whaL Lhe new lcrm2 class looks like in Lhe Code FdiLor.
400 Part III Desgnng the User Interface
1he 3uttcnJ_Clicl evenL procedure LhaL you added is also a member o Lhe new class.
8uL recall or a momenL LhaL Lhe lcrm1 class iLsel relied on Lhe System.WinJcws.lcrms.lcrm
class or iLs undamenLal behavior and characLerisLics. So Lhe lasL exercise demonsLraLes
LhaL one derived class (lcrm2) can inheriL iLs uncLionaliLy rom anoLher derived class
(lcrm1), which in Lurn inheriLed iLs core uncLionaliLy rom an original base class (lcrm),
which is a member o Lhe System.WinJcws.lcrms namespace in Lhe MicrosoL .NF1
Framework.
ln addiLion Lo Lhe lnheriLance Picker, visual SLudio oers Lhe lnherits sLaLemenL, which
causes Lhe currenL class Lo inheriL Lhe properLies, procedures, and variables o anoLher
class. 1o use Lhe lnherits sLaLemenL Lo inheriL a orm, you musL place Lhe lnherits sLaLemenL
. AlLhough you mighL choose Lo use
Lhe lnheriLance Picker or Lhis sorL o work wiLh orms, iL is useul Lo know abouL lnherits
because iL can be used or classes and inLeraces oLher Lhan orms, and you will probably
run inLo iL now and Lhen in your colleagues' program code. ou'll see an example o Lhe
lnherits sLaLemenL near Lhe end o Lhis chapLer.
Recognizing LhaL classes are such a undamenLal building block in visual 8asic programs,
you mighL very well ask how new classes are creaLed and how Lhese new classes mighL
be inheriLed down Lhe road by subsequenLly derived classes. 1o ponder Lhese possibiliLies,
l'll devoLe Lhe remainder o Lhis chapLer Lo discussing Lhe synLax or creaLing classes in
visual
by sLill more classes. Along Lhe way, you'll learn how very useul creaLing your own classes
can be.
Nerd AIert
1here's a poLenLial danger or Lerminology overload when discussing class creaLion
and inheriLance. A number o very smarL compuLer scienLisLs have been Lhinking abouL
in use or Lhe concepLs LhaL l plan Lo cover.
LhaL creaLing classes and inheriLing Lhem is quiLe simple in visual 8asic 200 and LhaL
you can accomplish a loL o useul work by adding jusL a ew lines o program code Lo
your projecLs. UndersLanding OOP Lerminology will also help you make sense o some
o Lhe advanced eaLures o visual 8asic 200, such as covariance and conLravariance,
Language lnLegraLed uery (LlN), anonymous Lypes, exLension meLhods, and
lambda expressions, which aciliLaLe Lhe use o classes, objecLs, and meLhods, and are
someLimes emphasized in markeLing announcemenLs and new eaLure lisLs.
402 Part III Desgnng the User Interface
our orm looks someLhing like Lhis.
a business applicaLion. 1he orm isn'L connecLed Lo a daLabase, however, so only
one record can be sLored aL a Lime. ou'll learn Lo make daLabase connecLions in
ChapLer 8, "CeLLing SLarLed wiLh ADO.NF1."
Now you'll add a class Lo Lhe projecL Lo sLore Lhe inormaLion in Lhe record.
7. Click Lhe Add Class command on Lhe ProjecL menu.
visual SLudio displays Lhe Add New lLem dialog box, wiLh Lhe Class LemplaLe selecLed,
as shown here.
406 Part III Desgnng the User Interface
or a Sub procedure Lo your class. AlLhough many meLhods don'L require argumenLs
Lo accomplish Lheir work, Lhe Ae 3irthJcy argumenL
o Lype Dcte Lo compleLe iLs calculaLion. 1he meLhod uses Lhe Subtrcct meLhod Lo
subLracL Lhe new employee's birLh daLe rom Lhe currenL sysLem Lime, and iL reLurns
Lhe value expressed in days divided by 865.25-Lhe approximaLe lengLh in days o
a single year. 1he lnt uncLion reLurns Lhe inLeger porLion o a number, and Lhis value
is reLurned Lo Lhe calling procedure via Lhe Return sLaLemenL-jusL like a Lypical
uncLion.
Modules and Procedures.")
Perscn class now looks like
Lhe ollowing.
Now you'll reLurn Lo Form and use Lhe new class in an evenL procedure.
1p AlLhough you didn'L do iL or Lhis example, iL's usually wise Lo add some Lype-checking
logic Lo class modules in acLual projecLs so LhaL properLies or meLhods LhaL are improperly
used don'L Lrigger run-Lime errors LhaL halL Lhe program.
408 Part III Desgnng the User Interface
our orm looks similar Lo Lhis.
8. Click Lhe Display Record buLLon.
Lhe Ae meLhod Lo calculaLe Lhe new employee's currenL age. A message box displays Lhe
resulL, as shown here.
9. Click OK Lo close Lhe message box, and Lhen experimenL wiLh a ew dierenL daLe
.
l0.
Lhe orm.
1he developmenL environmenL reLurns.
One Step lurther. lnheriting a Base CIass
As promised aL Lhe beginning o Lhis chapLer, l have one more Lrick Lo show you regarding
. JusL as orms can inheriL orm classes, Lhey can also
module.
1he mechanism or inheriLing a base (parenL) class is Lo use Lhe lnherits sLaLemenL Lo
. ou can Lhen add addiLional properLies
Chapter l6 Inhertng forms and Creatng ase CIasses 4ll
9. Click Display Record.
displays Lhe ollowing inpuL box, which prompLs Lhe new Leacher or Lhe grade he or
she Leaches.
l0. 1ype 3, and Lhen click OK Lo close Lhe inpuL box.
1he applicaLion sLores Lhe number 8 in Lhe new CrcJe properLy and uses Lhe
lirstNcme, lcstNcme, and CrcJe properLies Lo display Lhe new employee inormaLion
. ou see Lhis message.
ll. FxperimenL wiLh a ew more values i you like, and Lhen click Lhe Close buLLon on Lhe orm.
1he program sLops, and Lhe developmenL environmenL reLurns.
wiLh classes and inheriLance in Lhis chapLer. Nice job!
lurther xperiments with OOP
l you've enjoyed Lhis oray inLo objecL-orienLed coding Lechniques, more un awaiLs
you in visual 8asic 200, a Lruly OOP language. ln parLicular, you mighL wanL Lo add
and anonymous Lypes, and experimenL wiLh a polymorphic eaLure called methcJ
cverlccJin. 1hese and oLher OOP eaLures can be explored by using Lhe visual SLudio
Help documenLaLion or by perusing an advanced book on visual 8asic programming.
(See Lhe Appendix, "Where Lo Co or More lnormaLion," or a reading lisL.) ou'll also
well as you move more deeply inLo Lhe .NF1 Framework and advanced Lopics like
daLabase programming. For Lhe relaLionship beLween OOP and daLabases in visual
8asic, see ParL lv, "DaLabase and Web Programming."
4l5
ChapLer 7
Workng wth Prnters
After compIetng ths chapter, you wII be abIe to:
PrinL graphics rom a visual 8asic program.
PrinL LexL rom a visual 8asic program.
PrinL mulLipage documenLs.
CreaLe PrinL, Page SeLup, and PrinL Preview dialog boxes in your programs.
ln Lhe ollowing secLions, you'll compleLe your survey o user inLerace design and
componenLs by learning how Lo add prinLer supporL Lo your Windows applicaLions. MicrosoL
visual 8asic 200 supporLs prinLing wiLh Lhe PrintDccument class. 1he PrintDccument class
and iLs many meLhods, properLies, and supporLing classes handle sending LexL and graphics
Lo prinLers.
ln Lhis chapLer, you'll learn how Lo prinL graphics and LexL rom visual 8asic programs,
manage mulLipage prinLing Lasks, and add prinLing dialog boxes Lo your user inLerace. ln my
opinion, Lhis chapLer is one o Lhe mosL useul in Lhe book, wiLh loLs o pracLical code LhaL
you can immediaLely incorporaLe inLo real-world programming projecLs. PrinLing supporL
doesn'L come auLomaLically in visual 8asic 200, buL Lhe rouLines in Lhis chapLer will help
you prinL longer LexL documenLs and display helpul dialog boxes such as Page SeLup, PrinL,
and PrinL Preview rom wiLhin your programs. l'll sLarL Lhe chapLer wiLh Lwo very simple
prinLing rouLines Lo show you Lhe basics, and Lhen l'll geL considerably more sophisLicaLed.
Using the PrintDocument CIass
MosL Windows applicaLions allow users Lo prinL documenLs aLer Lhey creaLe Lhem, and by
now you mighL be wondering jusL how prinLing works in visual 8asic programs. 1his is one
Lechnical
sophisLicaLion comes aL a liLLle cosL. Producing prinLed ouLpuL rom visual 8asic programs
isn'L a Lrivial process, and Lhe Lechnique you use depends on Lhe Lype and amounL o
prinLed ouLpuL you wanL Lo generaLe. ln all cases, however, Lhe undamenLal mechanism
LhaL regulaLes prinLing in visual 8asic 200 is Lhe PrintDccument class, which you can creaLe
in a projecL in Lwo ways.
8y adding Lhe PrintDccument conLrol Lo a orm
Chapter l7 Workng wth Prnters 4l7
our orm looks similar Lo Lhis.
.
7. Double-click Lhe PrinL Craphics buLLon.
1he 3uttcn1_Clicl evenL procedure appears in Lhe Code FdiLor.
8. Move Lhe inserLion poinL Lo Lhe Lop o Lhe orm's code, and Lhen Lype Lhe ollowing
program sLaLemenL.
I mpor t s Syst em. Dr awi ng. Pr i nt i ng
1his lmcrts sLaLemenL declares Lhe System.Drcwin.Printin namespace, which makes
iL easier Lo reerence Lhe prinLing classes.
9. Now move Lhe inserLion poinL down Lo Lhe 3uttcn1_Clicl evenL procedure, and enLer
Lhe ollowing program code.
' Pr i nt usi ng an er r or handl er t o cat ch pr obl ems
Tr y
AddHandl er Pr i nt Document 1. Pr i nt Page, Addr essOf Me. Pr i nt Gr aphi c
Pr i nt Document 1. Pr i nt ( ) ' pr i nt gr aphi c
Cat ch ex As Except i on ' cat ch pr i nt i ng except i on
MessageBox. Show( "Sor r y- - t her e i s a pr obl empr i nt i ng" , ex. ToSt r i ng( ) )
End Tr y
Note ALer you enLer Lhis code, you'll see a jagged line under Me.PrintCrchic indicaLing
an error. Don'L worry, you'll be adding Lhe PrintCrchic procedure in Lhe nexL sLep.
1his code uses Lhe AJJHcnJler PrintCrchic evenL
procedure (also called an evenL handler) should be called when Lhe PrintPce evenL
o Lhe PrintDccument1 . An event rcceJure is a mechanism LhaL handles
4l8 Part III Desgnng the User Interface
evenLs LhaL represenL crucial acLions in Lhe lie cycle o an objecL. ou have been
working wiLh evenL procedures several Limes already. For example, you jusL creaLed Lhe
Clicl evenL procedure or Lhe 3uttcn1 objecL. 1he AJJHcnJler sLaLemenL is a way Lo
manually "wire up" an evenL procedure.
currenL
prinLer seLLings, and oLher aLLribuLes o Lhe PrintDccument class. 1echnically, Lhe
AJJressOj operaLor is used Lo idenLiy Lhe PrintCrchic evenL procedure by deLermining
iLs inLernal address and sLoring iL. 1he AJJressOj operaLor impliciLly creaLes an objecL
known as a Jelecte LhaL orwards calls Lo Lhe appropriaLe evenL procedure when an
evenL occurs.
1he Lhird line o Lhe code you jusL enLered uses Lhe Print meLhod o Lhe
PrintDccument1 objecL Lo send a prinL requesL Lo Lhe PrintCrchic evenL procedure.
1his prinL requesL is locaLed inside a 1ry code block Lo caLch any prinLing problems LhaL
mighL occur during Lhe prinLing acLiviLy. l inLroduced Lhe 1ry . . . Cctch error handler in
ChapLer 9, "1rapping Frrors by Using SLrucLured Frror Handling." Here Lhe ex variable is
being declared o Lype lxceticn Lo geL a deLailed message abouL any errors LhaL occur.
l0. Scroll above Lhe 3uttcn1_Clicl evenL procedure in Lhe Code FdiLor Lo Lhe general
declaraLion space below Lhe Public Clcss lcrm1 sLaLemenL. 1hen Lype Lhe ollowing
PrintCrchic evenL procedure.
' Sub f or pr i nt i ng gr aphi c
Pr i vat e Sub Pr i nt Gr aphi c( ByVal sender As Obj ect , _
ByVal ev As Pr i nt PageEvent Ar gs)
' Cr eat e t he gr aphi c usi ng Dr awI mage
ev. Gr aphi cs. Dr awI mage( I mage. Fr omFi l e( Text Box1. Text ) , _
ev. Gr aphi cs. Vi si bl eCl i pBounds)
' Speci f y t hat t hi s i s t he l ast page t o pr i nt
ev. HasMor ePages = Fal se
End Sub
1his rouLine handles Lhe prinLing evenL generaLed by Lhe PrintDccument1.Print meLhod.
l've declared Lhe Sub procedure wiLhin Lhe orm's code, buL you can also declare Lhe
Sub as a general-purpose procedure in a module. NoLe Lhe ev variable in Lhe argumenL
lisL or Lhe PrintCrchic procedure. 1his variable is Lhe crucial carrier o inormaLion
abouL Lhe currenL prinL page, and iL's declared o Lype PrintPcelventArs, a class in Lhe
System.Drcwin.Printin namespace.
1o acLually prinL Lhe graphic, Lhe procedure uses Lhe Crchics.Drcwlmce meLhod
sLored in Lhe 1ext properLy o Lhe 1ext3cx1 objecL. (8y deaulL, l seL Lhis properLy Lo
C.\vb0sbs\Chap5\Sun.ico-Lhe same Sun icon used in ChapLer 5, "Adding Craphics
and AnimaLion FecLs"-buL you can change Lhis value aL run Lime and prinL any
.) Finally, l seL Lhe ev.HcsMcrePces properLy Lo False so LhaL
visual 8asic undersLands LhaL Lhe prinL job doesn'L have mulLiple pages.
ll. Click Lhe Save All buLLon on Lhe SLandard Loolbar Lo save your changes, and Lhen
speciy Lhe C.\vb0sbs\Chap7 older as Lhe locaLion.
426 Part III Desgnng the User Interface
9. Scroll Lo Lhe Lop o Lhe orm, and Lhen enLer Lhe ollowing code.
I mpor t s Syst em. I O ' f or Fi l eSt r eamcl ass
I mpor t s Syst em. Dr awi ng. Pr i nt i ng
1hese sLaLemenLs make iL easier Lo reerence Lhe lileStrecm class and Lhe classes or
prinLing.
l0. Move Lhe cursor below Lhe Public Clcss lcrm1 sLaLemenL, and Lhen enLer Lhe ollowing
variable declaraLions.
Pr i vat e Pr i nt PageSet t i ngs As New PageSet t i ngs
Pr i vat e St r i ngToPr i nt As St r i ng
Pr i vat e Pr i nt Font As New Font ( "Ar i al " , 10)
.
ll. Scroll Lo Lhe btnOen_Clicl evenL procedure, and Lhen Lype Lhe ollowing program
code.
Di mFi l ePat h As St r i ng
' Di spl ay Open di al og box and sel ect t ext f i l e
OpenFi l eDi al og1. Fi l t er = "Text f i l es ( *. t xt ) | *. t xt "
OpenFi l eDi al og1. ShowDi al og( )
' I f Cancel but t on not sel ect ed, l oad Fi l ePat h var i abl e
I f OpenFi l eDi al og1. Fi l eName <> " " Then
Fi l ePat h = OpenFi l eDi al og1. Fi l eName
Tr y
' Read t ext f i l e and l oad i nt o Ri chText Box1
Di mMyFi l eSt r eamAs New Fi l eSt r eam( Fi l ePat h, Fi l eMode. Open)
Ri chText Box1. LoadFi l e( MyFi l eSt r eam, _
Ri chText BoxSt r eamType. Pl ai nText )
MyFi l eSt r eam. Cl ose( )
' I ni t i al i ze st r i ng t o pr i nt
St r i ngToPr i nt = Ri chText Box1. Text
' Enabl e Pr i nt but t on
bt nPr i nt . Enabl ed = Tr ue
Cat ch ex As Except i on
' di spl ay er r or messages i f t hey appear
MessageBox. Show( ex. Message)
End Tr y
End I f
When Lhe user clicks Lhe Open buLLon, Lhis evenL procedure displays an Open dialog
.
is assigned Lo a public sLring variable named lilePcth, which is declared aL Lhe Lop o
Lhe evenL procedure. 1he procedure Lhen uses a 1ry . . . Cctch error handler Lo load Lhe
Rich1ext3cx1 objecL. 1o aciliLaLe Lhe loading process, l've used Lhe
lileStrecm class and Lhe Oen
MylileStrecm variable. Finally, Lhe evenL procedure enables Lhe PrinL
buLLon (btnPrint .
and enables Lhe prinL buLLon on Lhe orm buL doesn'L do any prinLing iLsel.
by using logic LhaL moniLors Lhe dimensions o Lhe currenL LexL page.
Chapter l7 Workng wth Prnters 429
3. . .
ln Windows 7, your Open dialog box looks like Lhis.
4. .
enables Lhe PrinL buLLon.
LesL Lhe wide margin and mulLipage prinLing opLions. our orm looks like Lhis.
430 Part III Desgnng the User Interface
5. veriy LhaL your prinLer is on, and Lhen click Lhe PrinL buLLon.
visual 8asic displays Lhe PrinL dialog box, cusLomized wiLh Lhe name and seLLings or
your prinLer, as shown in Lhe ollowing screen shoL.
Many o Lhe opLions in Lhe PrinL dialog box are acLive, and you can experimenL wiLh
Lhem as you would a regular Windows applicaLion.
6. Click PrinL Lo prinL Lhe documenL.
our program submiLs Lhe our-page prinL job Lo Lhe Windows prinL queue. ALer a
momenL (and i your prinLer is ready), Lhe prinLer begins prinLing Lhe documenL. As in
previous exercises, a dialog box auLomaLically opens Lo show you Lhe prinLing sLaLus
and gives you an indicaLion o how many pages your prinLed documenL will be.
7. Click Lhe Close buLLon on Lhe orm Lo sLop Lhe program.
ou've jusL creaLed a seL o very versaLile prinLing rouLines LhaL can be added Lo any visual
8asic applicaLion LhaL needs Lo prinL mulLiple pages o LexL!
One Step lurther. Adding Print Preview
and Page Setup DiaIog Boxes
1he PrinL File applicaLion is ready Lo handle several prinLing Lasks, buL iLs inLerace isn'L
as visually compelling as LhaL o a commercial Windows applicaLion. ou can make your
supplemenL Lhe PrinL dialog box LhaL you experimenLed wiLh in Lhe previous exercise.
432 Part III Desgnng the User Interface
our orm looks like Lhis.
6. Double-click Lhe Page SeLup buLLon (btnSetu) Lo display Lhe btnSetu_Clicl evenL
procedure in Lhe Code FdiLor.
7. 1ype Lhe ollowing program code.
Tr y
' Load page set t i ngs and di spl ay page set up di al og box
PageSet upDi al og1. PageSet t i ngs = Pr i nt PageSet t i ngs
PageSet upDi al og1. ShowDi al og( )
Cat ch ex As Except i on
' Di spl ay er r or message
MessageBox. Show( ex. Message)
End Tr y
1he code or creaLing a Page SeLup dialog box in Lhis program is quiLe simple because
Lhe PrintPceSettins . 1his
Lhe PceSettins properLy o Lhe PceSetuDiclc1 objecL, Lhe ShcwDiclc meLhod
auLomaLically loads a dialog box LhaL allows Lhe user Lo modiy whaL Lhe program has
selecLed as Lhe deaulL page orienLaLion, margins, and so on. 1he 1ry . . . Cctch error
handler simply handles any errors LhaL mighL occur when Lhe ShcwDiclc meLhod is used.
8. Display Lhe orm again, and Lhen double-click Lhe PrinL Preview buLLon (btnPreview)
Lo display Lhe btnPreview_Clicl evenL procedure.
434 Part III Desgnng the User Interface
l. Click Lhe SLarL Debugging buLLon on Lhe Loolbar.
.
2. .
older.
1he remaining Lhree buLLon objecLs are now enabled, as shown here.
3. Click Lhe Page SeLup buLLon.
our program displays Lhe Page SeLup dialog box, as shown here.
Chapter l7 Workng wth Prnters 435
Page SeLup provides numerous useul opLions, including Lhe abiliLy Lo change Lhe
paper size and source, Lhe orienLaLion o Lhe prinLing (PorLraiL or Landscape), and Lhe
page margins (LeL, RighL, 1op, and 8oLLom).
4. Change Lhe LeL margin Lo 2, and Lhen click OK.
1he leL margin will now be 2 inches.
5. Click Lhe PrinL Preview buLLon.
our program displays Lhe PrinL Preview dialog box, as shown in Lhe ollowing
screen shoL.
l you've used Lhe PrinL Preview command in MicrosoL Word or MicrosoL Fxcel,
you will recognize several o Lhe buLLons and preview eaLures in Lhis PrinL Preview
dialog box. For example, Lhe helpul Loolbar conLains (rom leL Lo righL) Lhe PrinL
and Zoom buLLons, Lhe One Page, 1wo Pages, 1hree Pages, Four Pages, and Six
Pages buLLons (Lo adjusL how many pages are visible aL one Lime), Lhe Close buLLon,
and Lhe Page SelecL conLrol. No program code is required Lo make Lhese helpul
eaLures operaLe.
6. Click Lhe Four Pages buLLon Lo display your documenL our pages aL a Lime.
7. Click Lhe Maximize buLLon on Lhe PrinL Preview LiLle bar Lo make Lhe window ull size.
436 Part III Desgnng the User Interface
8. Click Lhe Zoom arrow, and Lhen click 50%.
our screen looks like Lhis.
9. Click Lhe Zoom arrow and reLurn Lhe view Lo AuLo.
l0. Click Lhe 1hree Pages buLLon, and Lhen click Lhe Up arrow in Lhe Page SelecL box Lo
view pages 2 Lhrough 4.
As you can see, Lhis PrinL Preview window is quiLe impressive-and you incorporaLed iL
inLo your program wiLh jusL a ew lines o code!
ll. l you wanL Lo LesL prinLing Lhe enLire documenL again, click Lhe PrinL buLLon.
l2.
dialog box, and Lhen click Lhe Close buLLon Lo close Lhe program.
ou're done working wiLh prinLers or now.
439
ParL lv
Database and Web
Programmng
In ths part:
Chapter l8: Gettng Started wth ADO.Nf1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44l
Chapter l9: Data Presentaton Usng the DctcCridView ControI . . . . . . . . . . . . 467
Chapter 20: Creatng Web Stes and Web Pages by Usng VsuaI
Web DeveIoper and ASP.Nf1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49l
ln ParL lv, you'll learn how Lo work wiLh inormaLion sLored in daLabases and Web siLes. FirsL,
you'll learn abouL MicrosoL ADO.NF1, an imporLanL paradigm or working wiLh daLabase
inormaLion, and you'll learn how Lo display, modiy, and search or daLabase conLenL
by using a combinaLion o program code and Windows Forms conLrols. MicrosoL visual
varieLy o daLa sources. 1hese cusLom inLeraces have LradiLionally been called Jctcbcse
jrcnt enJs, meaning LhaL Lhrough your MicrosoL visual 8asic applicaLion, Lhe user is given
a more useul window inLo daLabase inormaLion Lhan simply manipulaLing raw daLabase
records. However, a more appropriaLe descripLion in visual SLudio 200 is LhaL you can build
Jctccentric applicaLions, meaning LhaL Lhrough your applicaLion, Lhe user is inviLed Lo explore
Lhe ull poLenLial o any number o rich daLa source connecLions, wheLher Lo local or remoLe
locaLions, and LhaL Lhe applicaLion places Lhis daLa aL Lhe cenLer o Lhe user's compuLing
experience.
44l
ChapLer 8
Gettng Started wth ADO.Nf1
After compIetng ths chapter, you wII be abIe to:
and build a daLaseL.
Use Lhe DaLaseL Designer and Lhe DaLa Sources window Lo examine daLaseL members
and creaLe bound objecLs on orms.
CreaLe daLacenLric applicaLions by using daLaseL and daLa navigaLor objecLs.
Use bound 1ext3cx and McsleJ1ext3cx conLrols Lo display daLabase inormaLion on
a Windows orm.
uery 8uilder Lool.
.NF1 and wiLh daLacenLric applicaLions.
and records rom a daLabase Lable, and you'll use Lhe DaLaseL Designer and DaLa Sources
window Lo examine daLaseL members and creaLe bound objecLs on your orms. ou'll also
learn how Lo use 1ext3cx and McsleJ1ext3cx conLrols Lo presenL daLabase inormaLion Lo your
daLaseLs (and Lhereore whaL your user sees and uses) in inLeresLing ways.
Database Programming with ADO.NT
A Jctcbcse . ou can creaLe powerul
daLabases by using any o a varieLy o daLabase producLs, including Access, MicrosoL SL
Server, and Oracle. ou can also sLore and LransmiL daLabase inormaLion by using FxLensible
lnLerneL and in oLher seLLings.
CreaLing and mainLaining daLabases has become an essenLial Lask or all major corporaLions,
. Rich daLa resources-
or example, cusLomer addresses, manuacLuring invenLories, accounL balances, employee
records, donor lisLs, and order hisLories-have become Lhe lieblood o Lhe business world.
442 Part IV Database and Web Programmng
ou can use MicrosoL visual SLudio 200 Lo creaLe new daLabases, buL visual SLudio 200
is primarily designed or displaying, analyzing, and manipulaLing Lhe inormaLion in exisLing
daLabases. ADO. .NF1 2002, is sLill Lhe
sLandard daLa model or daLabase programming in visual SLudio 200. ADO.NF1 has been
improved over Lhe years Lo work wiLh a large number o daLa access scenarios, and iL has
been careully opLimized or lnLerneL use. For example, iL uses Lhe same basic meLhod or
accessing local, clienL-server, and lnLerneL-based daLa sources, and Lhe inLernal daLa ormaL
o ADO.NF1 is XML.
ForLunaLely, mosL o Lhe daLabase applicaLions LhaL programmers creaLed using MicrosoL
visual 8asic 2008 and ADO.NF1 sLill uncLion very well, and Lhe basic Lechniques or accessing
a daLabase are mosLly Lhe same in visual 8asic 200. However, Lhere are Lwo new daLabase
Lechnologies in visual SLudio 200 LhaL will be o considerable use Lo experienced daLabase
programmers. 1hese Lechnologies are Language-lnLegraLed uery (LlN) and Lhe ADO.NF1
FnLiLy Framework.
LlN is included wiLh visual SLudio 200 and oers Lhe capabiliLy Lo wriLe objecL-orienLed
daLabase queries direcLly wiLhin visual 8asic code. 1he ADO.NF1 FnLiLy Framework inLroduces
a new objecL model, powerul new eaLures, and Lools LhaL will make daLabase applicaLions
even reer rom hard-coded dependencies on a parLicular daLa engine or logical model.
As daLabase Lechnology and Lhe lnLerneL conLinue Lo advance, ADO.NF1 will conLinue Lo
.
Database 1ermnoIogy
An underlying Lheme in Lhe preceding secLion is LhaL daLabase programmers are oLen aced
wiLh new Lechnologies Lo decode and masLer, a reorienLaLion oLen iniLiaLed by Lhe Lerms
new crcJim or new Jctcbcse mcJel. AlLhough conLinually learning new Lechniques can be
a source o rusLraLion, Lhe rapid pace o change can be explained parLially by Lhe relaLive
newness o disLribuLed and mulLiple-Lier daLabase applicaLion programming in Windows,
as well as Lechnical innovaLions, securiLy needs, and Web programming challenges LhaL are
beyond Lhe conLrol o Lhe visual SLudio developmenL Leam. ln Lhis chapLer, however, we'll
be sLarLing aL Lhe beinnin, and wiLh daLabase programming more Lhan almosL any oLher
subjecL, you really need Lo be exposed Lo Lopics ste by ste. LeL's sLarL by undersLanding
some basic daLabase Lerminology.
A (also called a cclumn) is a caLegory o inormaLion sLored in a daLabase. 1ypical
members, e-mail names, business phone numbers, and deparLmenL names. All Lhe
inormaLion abouL a parLicular aculLy member is called a reccrJ (less commonly called
a rcw). When a daLabase is creaLed, inormaLion is enLered in a tcble .
Chapter l8 Gettng Started wth ADO.Nf1 443
ollowing aculLy daLabase (FaculLy200) in Access 2007.
A relcticncl Jctcbcse can consisL o mulLiple linked Lables. ln general, mosL o Lhe daLabases
LhaL you connecL Lo rom visual SLudio will probably be relaLional daLabases LhaL conLain
mulLiple Lables o daLa organized around a parLicular Lheme.
ln ADO.NF1, various objecLs are used Lo reLrieve and modiy inormaLion in a daLabase.
FirsL, a ccnnecticn
and creaLes someLhing or oLher conLrols and componenLs Lo bind Lo. NexL, Lhe DaLa
Jctcset, which is a represenLaLion o one or more
daLabase Lables you plan Lo work wiLh in your program. (ou don'L manipulaLe Lhe acLual
daLa, buL raLher a copy o iL. XMl
Lo your projecL and associaLes a tcble cJcter and Jctc ncvictcr wiLh Lhe
daLaseL Lo handle reLrieving daLa rom Lhe daLabase, posLing changes, and moving rom one
record Lo Lhe nexL in Lhe daLaseL. ou can Lhen bind inormaLion in Lhe daLaseL Lo conLrols
on a orm by using Lhe DaLa Sources window or Dctc3inJins properLy seLLings.
Chapter l8 Gettng Started wth ADO.Nf1 445
3. On Lhe DaLa menu, click Lhe Add New DaLa Source command.
as shown in Lhe ollowing screen shoL.
1he DaLa Source ConnecLion Wizard is a eaLure wiLhin Lhe visual SLudio 200 lDF LhaL
auLomaLically prepares your visual 8asic program Lo receive daLabase inormaLion. 1he
wizard prompLs you or Lhe Lype o daLabase LhaL you will be connecLing Lo (a local or
remoLe daLabase, Web service, cusLom daLa objecL LhaL you have creaLed, or MicrosoL
SharePoinL siLe), esLablishes a connecLion Lo Lhe daLa, and Lhen creaLes a daLaseL or
. 1he resulL is
o each daLabase objecL LhaL you can use in your program.
4.
Wizard, and Lhen click NexL.
1he wizard displays a screen prompLing you Lo choose a daLabase model or your
applicaLion and Lhe connecLion LhaL your program will make Lo Lhe daLabase
inormaLion. 1his is a new screen in visual SLudio 200, your opLions are now Lo choose
a daLaseL Lo make Lhe connecLion or an enLiLy daLa model. We will be using Lhe daLaseL
opLion here, buL Lhe enLiLy daLa model can also be useul because iL allows developers
446 Part IV Database and Web Programmng
concerning Lhemselves wiLh Lhe ormaL o underlying daLabase Lables and columns.
1he enLiLy daLa model opLion is made possible by Lhe ADO.NF1 FnLiLy Framework,
which is a subseL o Lhe ADO.NF1 daLabase Lechnology.
5. Click DaLaseL, and Lhen click NexL Lo selecL Lhe daLaseL model.
1he wizard now displays a screen LhaL helps you esLablish a connecLion Lo your
daLabase by building a sLaLemenL called a ccnnecticn strin. A connecLion sLring
conLains Lhe inormaLion LhaL visual SLudio needs Lo open and exLracL inormaLion
.
sensiLive daLa such as a user name and password. For Lhis reason, Lhe connecLion sLring
is LreaLed careully wiLhin Lhe DaLa Source ConnecLion Wizard, and you should Lake
Lo place.
6. Click Lhe New ConnecLion buLLon.
dialog box opens, prompLing you Lo selecL Lhe daLabase ormaL LhaL you plan Lo use.
l you see Lhe Add ConnecLion dialog box insLead o Lhe Choose DaLa Source dialog
avor a parLicular daLabase ormaL. No problem, simply click Lhe Change buLLon in Lhe
see, excepL LhaL Lhe LiLle bar reads Change DaLa Source. ln Lhis example, however, l'll
assume LhaL you haven'L selecLed a daLa source ormaL, in LhaL case, your screen looks
like Lhe ollowing screen shoL.
1he Change/Choose DaLa Source dialog box is Lhe place where you selecL your
preerred daLabase ormaL, which visual SLudio uses as Lhe deaulL ormaL. ln Lhis
chapLer, you'll selecL Lhe Access ormaL, buL noLe LhaL you can change Lhe daLabase
ormaL Lo one o Lhe oLher choices aL any Lime. ou can also esLablish more Lhan one
daLabase connecLion-each Lo a dierenL Lype o daLabase-wiLhin a single projecL.
Chapter l8 Gettng Started wth ADO.Nf1 447
7. Click MicrosoL Access DaLabase File, and Lhen click ConLinue (or OK).
1he Add ConnecLion dialog box opens, as shown in Lhe ollowing screen shoL.
Now you'll speciy Lhe locaLion and connecLion seLLings or your daLabase, so LhaL
visual SLudio can build a valid connecLion sLring.
8. Click 8rowse.
1he SelecL MicrosoL Access DaLabase File dialog box opens, which uncLions like
an Open dialog box.
9. 8rowse Lo Lhe C.\vb0sbs\Chap8 older, click Lhe FaculLy200.accdb daLabase,
and Lhen click Open.
ou have selecLed Lhe Access daLabase in 2007 ormaL LhaL l builL Lo demonsLraLe
. 1he Add
ConnecLion dialog box opens again wiLh Lhe paLh name recorded. l don'L resLricL access
.accdb. However, i your daLabase requires a user name, a password, or boLh or use,
you can speciy iL now in Lhe User Name and Password boxes. 1hese values are Lhen
included in Lhe connecLion sLring.
l0. Click Lhe 1esL ConnecLion buLLon.
LhaL Lhe wizard has builL or you. l Lhe daLabase is in a recognized ormaL and Lhe
user name and password enLries (i any) are correcL, you see Lhe message shown in Lhe
illusLraLion on Lhe nexL page.
448 Part IV Database and Web Programmng
Note l you geL a message LhaL says "Unrecognized daLabase ormaL", you mighL noL have
Access 2007 or laLer insLalled. l you don'L have Access 2007 or laLer insLalled, you will need
rom MicrosoL.com. (See SLep above.)
ll. Click OK Lo close Lhe message box, and Lhen click OK Lo close Lhe Add ConnecLion
dialog box.
.
l2. Click Lhe plus sign (-) nexL Lo Lhe ConnecLion SLring iLem in Lhe dialog box Lo display
your compleLed connecLion sLring.
our wizard page looks similar Lo Lhe ollowing.
rcviJer (also called a mcnceJ rcviJer)
named MicrosoL.ACF.OLFD8.2.0, which is an underlying daLabase componenL
LhaL undersLands how Lo connecL Lo a daLabase and exLracL daLa rom iL. 1he Lwo
mosL popular providers oered by visual SLudio are MicrosoL OLF D8 and SL Server, buL
Lhird-parLy providers are available or many o Lhe oLher popular daLabase ormaLs.
Chapter l8 Gettng Started wth ADO.Nf1 449
l3. Click Lhe NexL buLLon.
1he wizard displays an alerL message indicaLing LhaL a new local daLabase (or local
daLabase should be copied Lo your projecL olders. (1his message appears only Lhe
. l you are repeaLing Lhis
exercise, you probably won'L see Lhe message.) ln a commercial applicaLion LhaL uses
a daLabase, you mighL wanL Lo conLrol how Lhis works a liLLle more careully. (1o learn
more abouL your opLions, you would click Lhe Help buLLon or press F.)
l4. Click No Lo avoid making an exLra copy o Lhe daLabase aL Lhis Lime.
ou are noL commercially disLribuLing Lhis projecL, iL is only a sample program, and an
exLra copy is noL needed.
connecLion sLring is Lhe deaulL selecLion, and in Lhis example, Lhe recommended sLring
name is FaculLy200ConnecLionSLring. ou usually wanL Lo save Lhis sLring wiLhin your
Fxplorer), as opposed Lo Lracking down Lhe connecLion sLring wiLhin your program
code and recompiling Lhe applicaLion.
l5. Click NexL Lo save Lhe deaulL connecLion sLring.
ou are now prompLed Lo selecL Lhe subseL o daLabase objecLs LhaL you wanL Lo use
or Lhis parLicular projecL, as shown in Lhe ollowing dialog box.
450 Part IV Database and Web Programmng
Note visual SLudio allows you Lo use jusL parL o a daLabase or Lo combine dierenL
daLabases-a useul eaLure when you're working Lo build daLacenLric applicaLions.
1he iLems you selecL in Lhis dialog box are reerred Lo wiLhin Lhe projecL as Jctcbcse
cbjects.
procedures, uncLions, and oLher iLems unique Lo your daLabase. 1he collecLive Lerm or all
Lhe daLabase objecLs LhaL you selecL is a Jctcset. ln Lhis projecL, Lhe daLaseL is assigned Lhe
deaulL name lcculty2919DctcSet, which you can adjusL in Lhe DaLaSeL Name box.
1p NoLe LhaL Lhe daLaseL you creaLe now only reresents Lhe daLa in your daLabase-i
you add, deleLe, or modiy daLabase records in Lhe daLaseL, you don'L acLually modiy Lhe
underlying daLabase Lables unLil you issue a command LhaL wriLes your changes back Lo
Lhe original daLabase. DaLabase programmers call Lhis kind o arrangemenL a JisccnnecteJ
Jctc scurce, meaning LhaL Lhere is a layer o absLracLion beLween Lhe acLual daLabase and
your daLaseL.
l6. Click Lhe arrow nexL Lo Lhe 1ables node Lo expand Lhe lisL o Lhe Lables included in Lhe
FaculLy200.accdb daLabase.
ln Lhis case, Lhere is only one Lable lisLed, named lcculty, which we'll use in our sample
program.
l7. Click Lhe arrow nexL Lo Lhe FaculLy node, and Lhen selecL Lhe check boxes or Lhe lcst
Ncme and 3usiness Phcne .
lcculty2919DctcSet daLaseL. 1he wizard page looks
like Lhe ollowing screen shoL.
Chapter l8 Gettng Started wth ADO.Nf1 45l
l8. .
and . (Depending on how
or window now.)
l9. Click Lhe Save All buLLon on Lhe SLandard Loolbar Lo save your changes. Speciy Lhe
C.\vb0sbs\Chap8 older as Lhe locaLion.
20.
componenLs conLained in Lhe ADO FaculLy Form projecL.
our screen looks like Lhis.
named FaculLy200DaLaSeL.xsd.
.
1he tyeJ Jctcset Lo your
projecL.
daLaseLs don'L.) 1yped daLaseLs are advanLageous because Lhey enable Lhe MicrosoL
.
2l. Click Lhe FaculLy200DaLaSeL.
view Designer buLLon.
relaLed Lo your new daLaseL in a visual Lool called Lhe Dctcset Desiner. 1he DaLaseL
Designer conLains Lools or creaLing componenLs LhaL communicaLe beLween your
daLabase and your applicaLion-whaL daLabase programmers call Jctc cccess lcyer
ccmcnents. ou can creaLe and modiy Lable adapLers, Lable adapLer queries, daLa
Lables, daLa columns, and daLa relaLionships wiLh Lhe DaLaseL Designer. ou can also
use Lhe DaLaseL Designer Lo review and seL imporLanL properLies relaLed Lo objecLs
452 Part IV Database and Web Programmng
.
22. Click Lhe lcst Ncme .
23. Click Lhe Mcxlenth properLy. our screen looks similar Lo Lhe ollowing screen shoL.
Here Lhe DaLaseL Designer is shown wiLh an acLive daLaseL named lcculty2919DctcSet,
and Lhe ProperLies window shows LhaL Lhe Mcxlenth properLy is seL Lo allow or
a maximum o 50 characLers in Lhe lcst Ncme . AlLhough Lhis lengLh seems
daLabase seLLings are inadequaLe or your applicaLion.
SeLLing Lhe DaLaseL Designer aside or a momenL, leL's conLinue building Lhe sample daLabase
applicaLion in Lhe DaLa Sources window.
1he Data Sources Wndow
1he DaLa Sources window is a useul and Limesaving eaLure o Lhe visual SLudio 200 lDF.
or use wiLhin your projecL, and Lo help you bind Lhese daLaseLs Lo conLrols on Lhe orm.
Remember LhaL a daLaseL is jusL a Lemporary represenLaLion o daLabase inormaLion in your
Chapter l8 Gettng Started wth ADO.Nf1 453
. 1he daLaseL is displayed in a hierarchical (Lree) view in Lhe DaLa
Sources window, wiLh a rooL node or each o Lhe objecLs LhaL you selecLed in Lhe wizard.
Fach Lime you run Lhe wizard Lo creaLe a new daLaseL, a new daLaseL Lree is added Lo Lhe
DaLa Sources window, giving you poLenLial access Lo a wide range o daLa sources and views
wiLhin a single program.
lcculty Lable o Lhe
FaculLy200 daLabase, you have someLhing inLeresLing Lo display in Lhe DaLa Sources window
now. 1o prepare or Lhe ollowing exercises and display Lhe DaLa Sources window, display Lhe
orm again (click Lhe Form.vb [Design] Lab), and Lhen click Lhe Show DaLa Sources command
on Lhe DaLa menu. (ou can also click Lhe DaLa Sources Lab i iL is visible.) When Lhe DaLa
Sources window is open, expand Lhe lcculty
selecLed. our DaLa Sources window looks like Lhis.
Across Lhe Lop o Lhe window are our helpul Lools LhaL allow you Lo work wiLh daLaseLs.
From leL Lo righL, Lhese Loolbar buLLons allow you Lo add a new daLaseL Lo your projecL, ediL
daLaseL.
1he easiesL way Lo display Lhe inormaLion in a daLaseL on a orm (and Lhereore or your
users) is Lo drag objecLs rom Lhe DaLa Sources window Lo Lhe Windows Forms Designer.
(1his is Lhe Designer you used in earlier chapLers, buL l am calling iL Lhe WinJcws lcrms
Desiner here Lo disLinguish iL rom Lhe DaLaseL Designer.)
ChapLer 9, "DaLa PresenLaLion Using Lhe DctcCriJview ConLrol," describes how you can
display enLire Lables o daLa on a orm. ln Lhe remainder o Lhis chapLer, however, you'll
. Cive iL a Lry now.
Chapter l8 Gettng Started wth ADO.Nf1 455
a proessional-looking navigaLion bar aL Lhe Lop o Lhe orm. 1he orm looks someLhing
like Lhis (your DaLa Sources window mighL be in a dierenL locaLion).
visual SLudio has acLually creaLed Lwo objecLs or Lhis lcst Ncme
. 8elow Lhe orm in Lhe
componenL Lray, visual SLudio has also creaLed several objecLs Lo manage inLernal
aspecLs o Lhe daLa access process. 1hese objecLs include.
lcculty2919DctcSet, Lhe daLaseL LhaL you creaLed wiLh Lhe DaLa Source
lcculty3inJinScurce, an inLermediary componenL LhaL acLs as a conduiL
beLween Lhe lcculty Lable and bound objecLs on Lhe orm
lcculty1cbleAJcter and 1cbleAJcterMcncer, inLermediary componenLs LhaL
move daLa beLween lcculty2919DctcSet and Lables in Lhe underlying FaculLy200
daLabase
lcculty3inJinNcvictcr, which provides navigaLion services and properLies
relaLed Lo Lhe navigaLion Loolbar and Lhe lcculty Lable
Now you'll run Lhe program Lo see how all Lhese objecLs work.
456 Part IV Database and Web Programmng
5. Click Lhe SLarL Debugging buLLon on Lhe SLandard Loolbar.
1he ADO FaculLy Form program runs in Lhe lDF. 1he LexL box objecL is loaded wiLh Lhe
lcst Ncme record in Lhe daLabase (Abercrombie), and a navigaLion Loolbar wiLh
several buLLons and conLrols appears aL Lhe Lop o Lhe orm, as shown in Lhe ollowing
screen shoL.
1he navigaLion Loolbar is a helpul eaLure in Lhe visual SLudio 200 daLabase programming
Lools. From leL Lo righL, iL conLains Move FirsL and Move Previous buLLons, a currenL
posiLion indicaLor, and Move NexL, Move LasL, Add New, DeleLe, and Save DaLa buLLons.
ou can change or deleLe Lhese Loolbar buLLons by seLLing Lhe lLems properLy or Lhe
binding navigaLor objecL in Lhe ProperLies window, which displays a visual Lool called Lhe
ltems Ccllecticn lJitcr. ou can also enable or disable individual Loolbar buLLons.
6. Click Lhe Move NexL buLLon Lo scroll Lo Lhe second aculLy name in Lhe daLaseL.
1he Pais record appears.
7. ConLinue scrolling Lhrough Lhe daLaseL one record aL a Lime. As you scroll Lhrough Lhe
lisL o names, noLice LhaL Lhe posiLion indicaLor keeps Lrack o where you are in Lhe lisL
o records.
8.
daLaseL, respecLively.
9. DeleLe Lhe lasL record rom Lhe daLaseL (Skinner) by clicking Lhe DeleLe buLLon when
Lhe record is visible.
Chapter l8 Gettng Started wth ADO.Nf1 457
1he record is deleLed rom Lhe daLaseL, and Lhe posiLion indicaLor shows LhaL Lhere
are now 9 records remaining. (Lan has become Lhe lasL and currenL record.) our orm
looks like Lhis.
As l menLioned earlier, Lhe daLaseL represenLs only Lhe subseL o Lables rom
Lhe FaculLy200 daLabase LhaL have been used in Lhis projecL-Lhe daLaseL is
a disconnecLed image o Lhe daLabase, noL Lhe daLabase iLsel. Accordingly, Lhe record
LhaL you deleLed has been deleLed only rom Lhe daLaseL LhaL is loaded in memory
while Lhe program is running. However, Lo veriy LhaL Lhe program is acLually working
wiLh disconnecLed daLa and is noL modiying Lhe original daLabase, you'll sLop
and resLarL Lhe program now.
l0. Click Lhe Close buLLon on Lhe orm Lo end Lhe program.
1he program LerminaLes, and Lhe lDF reLurns.
ll. Click SLarL Debugging Lo run Lhe program again.
When Lhe program resLarLs and Lhe orm loads, Lhe navigaLion Loolbar shows LhaL Lhe
daLaseL conLains 20 records, as iL did originally. ln oLher words, iL works as expecLed.
l2. Click Lhe Move LasL buLLon Lo view Lhe lasL record in Lhe daLaseL.
1he record or Skinner appears again.
memory and has reappeared because Lhe underlying daLabase sLill conLains Lhe name.
l3. Click Lhe Close buLLon again Lo close Lhe program.
CongraLulaLions! WiLhouL wriLing any program code, you have builL a uncLioning daLabase
. SeLLing up a daLaseL has Laken
many sLeps, buL Lhe daLaseL is now ready Lo be used in many useul ways in Lhe program.
screen cluLLer and ocus our aLLenLion, you will probably wanL Lo selecL a much wider range
Chapter l8 Gettng Started wth ADO.Nf1 459
counLry Lo counLry, buL or me iL looks like a NorLh American Lelephone number wiLh
area code.)
5. Add a label objecL in ronL o Lhe new masked LexL box objecL, and seL iLs 1ext properLy
Lo "Phone." (including Lhe colon).
need Lo add Lhis one manually.
6. AdjusL Lhe spacing beLween Lhe Lwo labels and LexL boxes so LhaL Lhey are aligned
consisLenLly.
Now you'll bind Lhe 3usiness Phcne lcculty2919DctcSet Lo Lhe new masked LexL
box objecL. 1he process is easy-you simply drag Lhe 3usiness Phcne
DaLa Sources window onLo Lhe objecL LhaL you wanL Lo bind Lo Lhe daLa-in Lhis case,
Lhe McsleJ1ext3cx1 objecL.
7. Display Lhe DaLa Sources window i iL is noL visible, and Lhen drag Lhe 3usiness Phcne
McsleJ1ext3cx1 objecL.
When you drag a daLaseL objecL onLo an objecL LhaL already exisLs on Lhe orm
(whaL we mighL call Lhe tcret cbject), a new bound objecL is noL creaLed. lnsLead,
Lhe Dctc3inJins properLies or Lhe LargeL objecL are seL Lo maLch Lhe dragged
daLaseL objecL in Lhe DaLa Sources window.
ALer Lhis drag-and-drop operaLion, Lhe masked LexL box objecL is bound Lo Lhe
3usiness Phcne 1ext properLy conLains a small
daLabase icon in Lhe ProperLies window (a sign LhaL Lhe objecL is bound Lo a daLaseL).
8. veriy LhaL Lhe McsleJ1ext3cx1 objecL is selecLed on Lhe orm, and Lhen press F4 Lo
highlighL Lhe ProperLies window.
9. Scroll Lo Lhe Dctc3inJins caLegory wiLhin Lhe ProperLies window, and Lhen click Lhe
arrow Lo expand iL.
460 Part IV Database and Web Programmng
visual SLudio displays Lhe properLies Lypically associaLed wiLh daLa access or a masked
LexL box objecL. our ProperLies window looks similar Lo Lhe ollowing.
1he noLeworLhy bound properLy here is Lhe 1ext properLy, which has been seL Lo
FaculLy8indingSource - 8usiness Phone as a resulL o Lhe drag-and-drop operaLion.
(NoLe LhaL Lhe Liny daLabase icon does noL appear here, iL appears only in Lhe 1ext
properLy aL Lhe boLLom o Lhe alphabeLical lisL o properLies.) ln addiLion, i you click
Lhe arrow in Lhe 1ext properLy now, you'll see a represenLaLion o Lhe masked LexL box
objecL. (1his useul visual display allows you Lo quickly change Lhe daLa source LhaL Lhe
conLrol is bound Lo, buL don'L adjusL LhaL seLLing now.)
l0. Click Lhe orm Lo close any open ProperLies window panels.
ll. Click Lhe SLarL Debugging buLLon Lo run Lhe program.
visual SLudio runs Lhe program in Lhe lDF.
are loaded inLo Lhe LexL box and masked LexL box objecLs, as shown in Lhe ollowing
screen shoL.
Chapter l8 Gettng Started wth ADO.Nf1 46l
lmporLanLly, Lhe masked LexL box objecL correcLly ormaLs Lhe phone number
inormaLion so LhaL iL is in Lhe expecLed ormaL or NorLh American phone numbers.
l2. Click Lhe Move NexL buLLon a ew Limes.
LogeLher, and Lhe displayed aculLy names maLch Lhe corresponding business phone
numbers recorded in Lhe FaculLy200 daLabase. 1his synchronizaLion is handled by
Lhe lcculty3inJinNcvictcr objecL, which keeps Lrack o Lhe currenL record or each
bound objecL on Lhe orm.
l3. Click Lhe Close buLLon Lo sLop Lhe program, and Lhen click Lhe Save All buLLon Lo save
your changes.
browse Lhrough a daLaseL, and ormaL daLabase inormaLion wiLh a mask. 8eore you leave
Lhis chapLer and move on Lo Lhe useul DctcCriJview conLrol discussed in ChapLer 9, Lake
a momenL Lo see how you can urLher cusLomize your daLaseL by using a ew SL sLaLemenLs.
One Step lurther. SQL Statements, LlNQ,
and liItering Data
lcculty2919DctcSet.
and
SLudio uery 8uilder. 1his secLion inLroduces Lhese Lools.
SL sLaLemenLs is noLhing new. 8uL Lhe resL o us need Lo learn LhaL Sl stctements
are commands LhaL exLracL, or , inormaLion rom one or more sLrucLured Lables
in a daLabase.
conronLed wiLh a bewildering amounL o daLa on Lhe lnLerneL (and use clever search
keywords in Lheir browsers Lo locaLe jusL Lhe inormaLion Lhey need), daLabase
programmers are rouLinely conronLed wiLh Lables conLaining Lens o Lhousands o records
. 1he SL SFLFC1
sLaLemenL is one LradiLional mechanism or organizing daLabase inormaLion. 8y chaining
LogeLher a group o Lhese sLaLemenLs, programmers can creaLe complex search direcLives,
or queries, LhaL exLracL jusL Lhe daLa LhaL is needed rom a daLabase.
Realizing Lhe indusLry-wide accepLance o SL sLaLemenLs, previous versions o Lhe visual
SLudio and visual 8asic lDFs have included mechanisms or using SL sLaLemenLs. ln addiLion,
visual SLudio 2008 and 200 oer a powerul Lechnology called lcnuce-lntercteJ uery
(llN), which allows experienced programmers Lo wriLe SL-sLyled daLabase queries direcLly
Chapter l8 Gettng Started wth ADO.Nf1 463
1able box, near Lhe Lop o Lhe dialog box. ou'll recognize Lhe objecL hierarchy ormaL
used by Lhe Lable name, which is read as "Lhe lcculty Lable wiLhin Lhe lcculty2919DctcSet
daLaseL." l you had oLher Lables Lo choose among, Lhey would be in Lhe lisL box displayed
when you click Lhe SelecL DaLa Source 1able arrow.
3. 1ype SortLastNames in Lhe New uery Name box.
1his LexL box assigns a name Lo your query, and orms Lhe basis o Loolbar buLLons
added Lo Lhe orm. (For easy access, Lhe deaulL arrangemenL is LhaL new queries are
assigned Lo Loolbar buLLons wiLhin Lhe applicaLion you are building.)
4. Click Lhe uery 8uilder buLLon in Lhe dialog box Lo open Lhe uery 8uilder Lool.
1he uery 8uilder allows you Lo creaLe SL sLaLemenLs by Lyping Lhem direcLly inLo
a large SL sLaLemenL LexL box or by clicking lisL boxes and oLher visual Lools.
5. ln Lhe lcst Ncme row represenLing Lhe lcst Ncme
under SorL 1ype, and Lhen click Lhe arrow Lo display Lhe SorL 1ype lisL box.
our screen looks like Lhis.
6. ln Lhe SorL 1ype lisL box, click Ascending.
ou'll sorL records in Lhe lcst Ncme .
464 Part IV Database and Web Programmng
7. Click Lhe SL sLaLemenL LexL box below Lhe grid pane Lo updaLe Lhe uery 8uilder
window.
A new clause (ORDFR 8 [LasL Name]) is added Lo Lhe SL sLaLemenL box, and your
screen looks like Lhis.
1his is Lhe sLrengLh o Lhe uery 8uilder Lool-iL auLomaLically builds Lhe SL
sLaLemenLs or you in Lhe SL sLaLemenL box.
8. Click OK Lo compleLe your query.
visual SLudio closes Lhe uery 8uilder and displays your new query in Lhe Search
CriLeria 8uilder dialog box. 1he name o Lhe query (ScrtlcstNcmes) is lisLed, as well as
Lhe SL sLaLemenLs LhaL make up Lhe sorL.
9.
lcst_Ncme1ext3cx objecL Lo lisL names in ascending alphabeLical order.
1he process has also creaLed a ScrtlcstNcmes1cclStri objecL in Lhe componenL Lray
below Lhe orm. 1he Designer and componenL Lray now look like Lhe screen shoL shown
on Lhe ollowing page.
Chapter l8 Gettng Started wth ADO.Nf1 465
l0. Click Lhe SLarL Debugging buLLon Lo run Lhe program.
.
ll. Click Lhe SorLLasLNames buLLon on Lhe new Loolbar.
our new SL sLaLemenL sorLs Lhe lcst Ncme records in Lhe daLaseL and displays Lhe
records in Lheir new order.
and Lhird names are ALlas and 8ankov, respecLively.
l2. Click Lhe Move LasL buLLon on Lhe Loolbar.
Now Zimprich appears, as shown in Lhe ollowing screen shoL.
467
ChapLer 9
Data Presentaton Usng
the DctcCridView ControI
After compIetng ths chapter, you wII be abIe to:
CreaLe a daLa grid view objecL on a Windows orm, and use iL Lo display a daLabase
Lable.
SorL daLabase Lables by column.
Change Lhe ormaL and color o cells in a daLa grid view objecL.
Add and remove columns and column headings.
Display mulLiple daLa grid view objecLs on a orm.
PermiL changes in daLa grid view cells, and wriLe updaLes Lo Lhe underlying daLabase.
ln ChapLer 8, "CeLLing SLarLed wiLh ADO.NF1," you learned how Lo use MicrosoL ADO.NF1
daLabase programming Lechniques Lo esLablish a connecLion Lo a MicrosoL Access daLabase
and display columns rom Lhe daLabase in a Windows orm. ou also learned how Lo add
a navigaLion bar Lo a orm and how Lo organize daLabase inormaLion using SLrucLured
uery Language (SL) sLaLemenLs and Lhe uery 8uilder Lool.
ln Lhis chapLer, you'll conLinue working wiLh Lhe daLabase programming eaLures o MicrosoL
visual SLudio 200 and Lhe useul classes, objecLs, and design Lools in ADO.NF1. ln parLicular,
you'll learn how Lo use Lhe DctcCriJview conLrol, which allows you Lo presenL an enLire Lable
o daLabase inormaLion Lo Lhe user.
Using Doto6riJview to DispIay Database kecords
1he DctcCriJview conLrol presenLs inormaLion by esLablishing a grid o rows and columns
on a orm Lo display daLa as you mighL see iL in a program such as MicrosoL Fxcel or Access.
A DctcCriJview conLrol can be used Lo display any Lype o Labular daLa. LexL, numbers, daLes,
or Lhe conLenLs o an array. ln programming Lerms, DctcCriJview is also quiLe convenienL
because Lhe underlying daLa adapLer and daLaseL objecLs associaLed wiLh DctcCriJview
handle all Lhe daLa access uncLionaliLy auLomaLically.
Chapter l9 Data Presentaton Usng the DctcCridView ControI 469
l you don'L see Lhe FaculLy200 daLabase connecLion, click Lhe New ConnecLion
buLLon, and Lhen browse Lo Lhe FaculLy200.
Chap8 older. (DeLailed sLeps or esLablishing Lhis connecLion are given in ChapLer 8,
i you'd like addiLional inormaLion.)
5. WiLh Lhe FaculLy200.accdb connecLion selecLed, click NexL.
1he wizard asks wheLher you wanL Lo save your connecLion sLring.
6. .
ou are now prompLed Lo selecL Lhe daLabase objecLs LhaL you wanL Lo use or Lhis
parLicular projecL.
Lo pick and choose daLabase Lables and columns aL Lhis poinL-you can selecL all Lhe
objecLs in Lhe daLabase or jusL a subseL.
7. Fxpand Lhe 1ables node and Lhe lcculty
daLabase LhaL conLain aculLy employee inormaLion.
8. SelecL Lhe lD, lcst Ncme, lirst Ncme, l-mcil AJJress, lcculty lD, Decrtment, lcculty
1ye, and 3usiness Phcne .
AlLhough Lhis Access daLabase has been designed Lo conLain all sorLs o inormaLion
you're compleLing.
470 Part IV Database and Web Programmng
1p lL is imporLanL LhaL you include Lhe lD rimcry ley o Lhe Access
daLabase LhaL you are using. 1he primary key does noL need Lo be displayed on your
orm, buL iL needs Lo be included in Lhe daLaseL so LhaL inormaLion rom Lhe Lable can be
wriLLen back Lo Lhe original daLabase i you choose Lo give Lhe user Lhis opLion. (l discuss
save operaLions aL Lhe end o Lhis chapLer.) l you don'L include Lhe primary key, you may
receive an error message when you Lry Lo wriLe daLa back Lo Lhe original daLabase.
our wizard page looks as shown in Lhe ollowing screen shoL.
9. .
visual SLudio creaLes a daLaseL named lcculty2919DctcSet Lo represenL Lhe eighL
daLabase objecLs LhaL you selecLed. visual SLudio also adds an FxLensible Markup
.xsd Lo your projecL and Lhe
SoluLion Fxplorer window. ou have now esLablished a connecLion Lo Lhe FaculLy200
.accdb daLabase LhaL you can use or Lhe remainder o Lhis chapLer.
l0. Click Lhe Save All buLLon on Lhe SLandard Loolbar Lo save Lhe projecL. Speciy Lhe
C.\vb0sbs\Chap9 older as Lhe locaLion.
ll. Click Lhe DaLa Source Lab Lo open Lhe DaLa Sources window, and Lhen expand Lhe
FaculLy node. (l Lhe DaLa Sources Lab is noL visible, click Lhe Show DaLa Sources
command on Lhe DaLa menu.)
472 Part IV Database and Web Programmng
8ecause you have selecLed an enLire Lable, you do noL see individual bound conLrols in
Lhis lisL box. lnsLead you see Lhe ollowing opLions.
DaLaCridview, Lhe deaulL selecLion, which displays a grid o columns and rows
lcculty Lable.
. AlLhough
l won'L demonsLraLe DeLails now, iL is a useul opLion i you wanL Lo presenL
Labular daLa in a slighLly more approachable ormaL.
None, which removes any associaLion beLween Lhe Lable and a user inLerace
elemenL or conLrol. (l you selecL None or a Lable, you will noL be able Lo drag
Lhe Lable rom Lhe DaLa Sources window Lo Lhe orm, and a Null icon will appear
nexL Lo Lhe Lable name.)
CusLomize, which leLs you selecL a dierenL conLrol LhaL mighL be suiLable or
list3cx conLrol).
3. Click Lhe DctcCriJview opLion, and Lhen drag Lhe lcculty Lable Lo Lhe leL side o
your orm.
visual SLudio creaLes a navigaLion bar aL Lhe Lop o Lhe orm, adds daLaseL, binding
source, Lable adapLer, Lable adapLer manager, and binding navigaLor componenLs Lo
Lhe componenL Lray, and creaLes a daLa grid view objecL named lccultyDctcCriJview
on Lhe orm. our screen looks similar Lo Lhe ollowing screen shoL.
Chapter l9 Data Presentaton Usng the DctcCridView ControI 473
As you can see, Lhe daLa grid view objecL does noL conLain any inormaLion aL Lhis
poinL, and iL is probably noL Lhe righL size eiLher. (My daLa grid view objecL is noL wide
enough Lo display all eighL columns, or example.) However, you can clearly see LhaL
visual SLudio has organized Lhe lcculty
appear as columns and iLs rows represenL individual records. A blank row is reserved or
.
4. Move and resize Lhe daLa grid view objecL so LhaL you can see as many columns as
possible and Lhere is ample room or aL leasL 0 rows o daLa.
Depending on how your screen resoluLion is seL, you may need Lo hide some o Lhe
programming Lools in Lhe lDF Lo accomplish Lhis, or use Lhe visual SLudio lDF scroll bars
LhaL appear when you work wiLh large applicaLion windows.
5. Use Lhe ProperLies window Lo seL Lhe orm's 1ext properLy Lo "1he FaculLy 1able."
our orm looks similar Lo Lhe ollowing.
Chapter l9 Data Presentaton Usng the DctcCridView ControI 475
3. Click Lhe Preview buLLon.
visual SLudio loads Lhe lcculty Lable rom lcculty2919DctcSet, as shown in Lhe
ollowing screen shoL.
ou should be amiliar wiLh some o Lhis daLa already rom ChapLer 8, buL you now
may be able Lo see eighL columns LhaL you have selecLed, all in one place. Seeing all Lhe
columns aL once is inLeresLing, buL iL also could amounL Lo inormaLion overload-iL is
up Lo you Lo decide how much daLabase inormaLion your users should see, and how iL
should be ormaLLed. ln acL, you mighL noL even be able Lo see all eighL columns righL
now, as is Lhe case in Lhe screen shoL. ln visual SLudio, iL is easy Lo Lailor Lhe daLa grid
view's ouLpuL so LhaL Lhe proper inormaLion is visible.
4. Click Lhe Close buLLon Lo close Lhe Preview DaLa dialog box.
Now you'll remove Lhe lD and lcculty lD columns rom Lhe daLa grid view Lo show only Lhe
inormaLion LhaL a Lypical "direcLory lookup" eaLure would display on Lhe screen. Recall LhaL
you only included Lhe lD
when daLa is wriLLen back Lo Lhe original daLabase.
478 Part IV Database and Web Programmng
1he program sLaLemenL in Lhe lcrm1_lccJ evenL procedure LhaL populaLed Lhe daLa
grid view wiLh inormaLion rom Lhe lcculty Lable looks like Lhis.
Me. Facul t yTabl eAdapt er . Fi l l ( Me. Facul t y2010Dat aSet . Facul t y)
1his line was added Lo your program by visual SLudio when you dragged Lhe lcculty
Lable Lo Lhe orm rom Lhe DaLa Sources window.
Fach row in Lhe daLa grid view represenLs a record o daLa rom Lhe lcculty Lable in Lhe
daLabase. Scroll bars are provided so LhaL you can view any records or columns LhaL
aren'L immediaLely visible. 1his is a handy ease-o-use eaLure LhaL comes auLomaLically
wiLh Lhe DctcCriJview conLrol.
2. Scroll down Lhe lisL o records Lo view all 20 rows, which represenL aculLy employee
daLa or a universiLy.
3. Reduce Lhe size o Lhe FirsL Name column by placing Lhe poinLer beLween Lhe FirsL
Name and F-mail Address column headings and dragging Lhe column border Lo Lhe leL.
When you place Lhe poinLer beLween Lhe column headings, iL changes Lo a resizing
handle. ou can resize columns aL run Lime because Lhe daLa grid view objecL's
AllcwUser1cResizeCclumns properLy is by deaulL seL Lo 1rue. l you wanL Lo prevenL
resizing, you can seL Lhis properLy Lo False.
4. Widen Lhe F-mail Address column Lo see more o Lhe e-mail name or each aculLy
member.
DctcCriJview conLrol's sorLing eaLure.
5. Click Lhe LasL Name column heading.
1he daLa grid view is sorLed alphabeLically by Lhe lasL names o Lhe aculLy members.
our orm looks someLhing like Lhe ollowing screen shoL.
480 Part IV Database and Web Programmng
5. Click OK Lo close Lhe FdiL Columns dialog box.
Now, you'll seL properLies LhaL conLrol Lhe appearance o all Lhe columns in Lhe Lable.
Note . 1o modiy
properLies LhaL apply Lo all Lhe columns in a Lable, you adjusL properLy seLLings or Lhe
daLa grid view objecL in Lhe ProperLies window.
6. ln Lhe ProperLies window, seL Lhe CclumnHecJersvisible properLy Lo False.
AlLhough Lhe column names are somewhaL useul in Lhis parLicular daLabase,
someLimes column names don'L clearly idenLiy Lheir conLenLs or Lhey conLain
abbreviaLions or words LhaL you wanL Lo hide rom your users. SeLLing Lhis properLy
removes Lhe column names rom Lhe Lable.
7. Click Lhe AlternctinRcwsDejcultCellStyle properLy, and Lhen click Lhe ellipsis buLLon.
1he AlternctinRcwsDejcultCellStyle properLy conLrols Lhe color LhaL appears in Lhe
background o daLa grid view cells in alLernaLing rows. Changing Lhis seLLing produces
an alLernaLing eecL (whiLe and Lhe color you selecL) rom row Lo row in Lhe daLa grid
view. ln my opinion, Lhis eecL makes iL easy Lo read records in longer Lables.
visual SLudio displays Lhe CellSLyle 8uilder dialog box, a Lool used Lo seL Lhe properLies
o column cells in daLa grid view Lables.
8. Click Lhe 3cclCclcr properLy, click iLs arrow in Lhe second column, click Lhe CusLom Lab,
and Lhen click Lhe lighL yellow color.
our dialog box looks like Lhis. 1he yellow shading is noL visible in Lhis book, buL you'll
see iL in parLs o Lhe dialog box.
Chapter l9 Data Presentaton Usng the DctcCridView ControI 48l
9. Click OK Lo close Lhe dialog box.
When you run Lhe program, Lhe rows in Lhe daLa grid view will be displayed in
alLernaLing colors o whiLe and yellow.
Note 1he color LhaL appears around Lhe edges o Lhe cell is conLrolled by Lhe
3cclrcunJCclcr properLy. 1o change Lhe color o all Lhe cells in a daLa grid view, you can
adjusL Lhe DejcultCellStyle properLy. 1o change Lhe background color used or Lhe header
cells (i you display Lhem), you can modiy Lhe CclumnHecJersDejcultCellStyle properLy.
l0. Click Lhe CriJCclcr properLy, click Lhe arrow in Lhe second column, click Lhe CusLom
Lab, and Lhen click Navy (a dark blue color).
1his properLy seLLing conLrols Lhe color o Lhe gridlines. l you change Lhe background
color o Lhe cells, you mighL also wanL Lo modiy Lhe gridline color.
Now, you'll run Lhe program Lo see Lhe eecL o your ormaLLing changes.
ll. Click Lhe SLarL Debugging buLLon.
ALer a ew momenLs, Lhe daLa grid view appears wiLh inormaLion rom Lhe lcculty
Lable. our screen looks similar Lo Lhe ollowing screen shoL.
NoLice LhaL Lhe column headers have been removed, Lhe second column is a
liLLle narrower, and Lhe Lhird column is a liLLle wider. NoLice also Lhe alLernaLing
whiLe-and-yellow row paLLern and Lhe blue gridlines (Lhey are noL Loo discernible in
Lhe prinLed book, alas, buL you can see Lhem on Lhe screen).
l2. Click Lhe Close buLLon on Lhe orm Lo sLop Lhe program.
Chapter l9 Data Presentaton Usng the DctcCridView ControI 483
1his Lime, you'll show some dierenL inormaLion rom Lhe lcculty Lable. When you're
lcst Ncme, lirst Ncme, and lcculty lD columns are leL, as shown in
Lhe ollowing screen shoL.
6. Click OK Lo close Lhe FdiL Columns dialog box.
7. Move and resize Lhe second daLa grid view objecL on Lhe orm so LhaL all Lhree rows are
displayed and Lhe daLa grid views are nexL Lo each oLher.
our orm looks someLhing like Lhe ollowing screen shoL. (8ecause l am running visual
SLudio aL a screen resoluLion o 800 x 600, l needed Lo hide many o Lhe visual SLudio
Lool windows Lo show Lhe orm.)
484 Part IV Database and Web Programmng
l you wanL Lo run your program now and have Lhe Lwo daLa grid view conLrols linked,
you don'L need Lo add any addiLional conLrols Lo your projecL. WiLh one navigaLion
bar, Lhe Lwo Lables will be linked and boLh will scroll auLomaLically, even Lhough Lhey
. LeL's see how Lhis works.
8. Click Lhe Save All buLLon Lo save your changes.
9. Click Lhe SLarL Debugging buLLon on Lhe Loolbar.
visual SLudio runs Lhe DaLaCridview Sample program in Lhe lDF. ou see Lwo daLa grid
view objecLs on Lhe orm, as shown in Lhe ollowing screen shoL.
l0. Use Lhe navigaLion bar Lo sLarL scrolling Lhrough Lhe lcculty Lable records.
ou can see LhaL Lhe Lwo daLa grid view objecLs are linked, because Lhey share Lhe
same Lable and underlying daLa adapLer and binding navigaLor. 1his is a eaLure o Lhe
way daLaseL navigaLion works in Lhis parLicular implemenLaLion, however, i you choose
Lo display Lwo separaLe daLabase Lables, you can add a second navigaLion bar and
move Lhrough Lhe records separaLely.
ll. Use Lhe Lop scroll bar Lo move Lhrough Lhe conLenLs o Lhe Lop daLa grid view objecL on
iLs own.
1he scroll bars allow you Lo view Lhe Lwo daLa grid view objecLs independenLly, so you
always don'L have Lo be looking aL Lhe records or Lhe same employee.
l2.
buLLon Lo close Lhe DaLaCridview Sample applicaLion.
ou can perhaps appreciaLe how useul Lwo daLa grid view objecLs mighL be or Lhe user who
wanLs Lo compare Lwo very large Lables o inormaLion.
SFLFC1 sLaLemenLs, Lhe applicaLion quickly becomes quiLe powerul.
Chapter l9 Data Presentaton Usng the DctcCridView ControI 485
Adding a 8inJingNovigotor ControI to Create
a Second Navigation Bar on the lorm
l you choose Lo add a second daLabase Lable Lo your orm, keep in mind LhaL you can
also add a second navigaLion bar Lo Lhe orm so LhaL your user can use Lwo dierenL
navigaLion bars aL once. 1o make Lhis work, you need Lo be using a daLabase LhaL
conLains more Lhan one Lable. (ln Lhe FaculLy200.accdb daLabase, Lhere was only one
Lable, buL iL is common or daLabases Lo have several Lables Lo choose among.) Follow
Lhese sLeps Lo add a second Lable and navigaLion bar Lo your program.
l. Use Lhe DaLa Sources window Lo creaLe a second daLa grid view objecL on your
orm, represenLing a second Lable in Lhe daLabase.
2.
command.
3. Double-click Lhe 3inJinNcvictcr conLrol on Lhe DaLa Lab o Lhe 1oolbox.
visual SLudio adds a binding navigaLor objecL named 3inJinNcvictcr1 Lo Lhe
componenL Lray and adds a second navigaLion bar Lo Lhe Lop o your orm. ou
may need Lo move Lhe daLa grid view objecLs down slighLly i Lhe new navigaLion
bar is covering Lhem.
4. Change Lhe 3inJinScurce properLy o Lhe second binding navigaLor objecL Lo
Lhe binding source o Lhe second Lable. 1his is made easy by Lhe 3inJinScurce
arrow in Lhe ProperLies window, which shows Lhe names o Lhe Lwo valid binding
sources in Lhe program, so you can simply pick iL rom Lhe lisL. Once a link has
been esLablished beLween Lhe second navigaLion bar and Lhe binding source
objecL represenLing Lhe second Lable, your program is ready Lo run.
One Step lurther. Updating the OriginaI Database
As l menLioned earlier, Lhe daLaseL objecL in your program is only a represenLaLion o Lhe
daLa in your original daLabase. 1his is also Lrue o Lhe inormaLion sLored in Lhe daLa grid view
objecLs on your orm-i Lhe user makes a change Lo Lhis daLa, Lhe change isn'L wriLLen back
Lo Lhe original daLabase unless you have seL Lhe daLa grid view objecL's RecJOnly properLy
Lo False and Lhe user clicks Lhe Save DaLa buLLon on Lhe navigaLion bar. 1he designers o
ADO.NF1 and visual SLudio creaLed Lhis relaLionship Lo proLecL Lhe original daLabase and Lo
allow your users Lo manipulaLe daLa reely in your programs-wheLher you plan Lo save Lhe
changes or noL.
RecJOnly properLy,
which enables or disables changes in Lhe lccultyDctcCriJview objecL. ou'll also learn how
Lo use Lhe Save DaLa buLLon, which wriLes changes back Lo Lhe original daLabase Lables
on disk.
Chapter l9 Data Presentaton Usng the DctcCridView ControI 487
When you press FnLer or click a dierenL cell in Lhe daLa grid view objecL, Lhe change is
sLored in Lhe lcculty2919DctcSet daLaseL.
5. Click Lhe Save DaLa buLLon on Lhe navigaLion bar.
visual SLudio uses Lhe UJcteAll meLhod in Lhe daLa grid view's Lable adapLer objecL
Lo wriLe Lhe changed daLaseL Lo Lhe underlying daLabase. 1he program sLaLemenL used
Lo accomplish Lhis save operaLion in Lhe lcculty3inJinNcvictcrScveltem_Clicl evenL
procedure looks like Lhis.
Me. Tabl eAdapt er Manager . Updat eAl l ( Me. Facul t y2010Dat aSet )
1cbleAJcterMcncer is Lhe componenL in visual SLudio 200 LhaL allows you Lo conLrol
one or more daLabase Lables in a program. 1he UJcteAll meLhod saves changes in all
open Lables in a program, which means LhaL iL saves changes noL only in Lhe lcculty
Lable, buL any oLher Lable LhaL you have open. ou do noL have Lo accepL Lhe deaulL
saving behavior here. l you would like Lo save only Lhe changes in Lhe lcculty Lable
when your user clicks Lhe Save DaLa buLLon, replace Lhe sLaLemenL above wiLh Lhe
ollowing line o code.
Me. Facul t yTabl eAdapt er . Updat e( Me. Facul t y2010Dat aSet . Facul t y)
l you use Lhe UJcte meLhod or a named Lable adapLer objecL, Lhen jusL LhaL Lable
adapLer's associaLed daLa will be saved. (And remember, you can also conLrol user ediLs
wiLhin Lables by using Lhe RecJOnly properLy.)
6. Click Lhe Close buLLon Lo end Lhe program.
1he program closes and Lhe visual SLudio lDF reLurns. Now, you'll run Lhe program
again Lo see wheLher Lhe lcculty Lable in Lhe FaculLy200.accdb daLabase has indeed
. .)
7. Click Lhe SLarL Debugging buLLon.
ALer a momenL, Lhe daLa grid view objecLs are loaded wiLh daLa. ou will see LhaL Lhe
row in Lhe lcculty Lable conLaining Lhe name Wilson Pais has been updaLed wiLh Lhe
change Lo AssisLanL Proessor. 1he program works!
8. Click Lhe Close buLLon Lo end Lhe program.
l you wanL Lo conLinue experimenLing wiLh Lhe RecJOnly properLy or one or boLh o Lhe
daLa grid view objecLs, seL RecJOnly Lo 1rue now, and see whaL happens when you Lry Lo
modiy Lhe daLabase. (ou won'L be able Lo make ediLs or save any changes.) ou mighL
also experimenL wiLh adding new rows o daLa Lo Lhe daLabase by using Lhe builL-in ediLing
eaLures and Loolbar buLLons associaLed wiLh Lhe DctcCriJview and 3inJinNcvictcr
conLrols. (8eore you add new rows, seL Lhe RecJOnly properLy back Lo False.)
Now Lake sLock o your accomplishmenLs. ou've learned Lo display mulLiple Lables and
records by using Lhe DctcCriJview and 3inJinNcvictcr conLrols, and you've learned
how Lo cusLomize Lhe daLa grid view objecLs wiLh properLy seLLings and how Lo wriLe
49l
ChapLer 20
Creatng Web Stes and Web Pages
by Usng VsuaI Web DeveIoper
and ASP.Nf1
After compIetng ths chapter, you wII be abIe to:
SLarL visual Web Developer and creaLe a new Web siLe.
Use visual Web Developer Lools and windows, including Lhe Web Page Designer.
Use Lhe visual Web Developer 1oolbox Lo add server conLrols Lo Web pages.
Add LexL, ormaLLing eecLs, and visual 8asic code Lo a Web page LhaL calculaLes loan
paymenLs or a car loan.
CreaLe a Web page LhaL displays Help inormaLion.
Use Lhe Hyerlinl conLrol Lo link one Web page Lo anoLher on a Web siLe.
Use Lhe CriJview conLrol Lo display a Lable o daLabase inormaLion on a Web page.
SeL Lhe 1itle or a Web page and ediL Lhe masLer page.
ln Lhis chapLer, you'll learn how Lo build Web siLes and Web pages by using Lhe visual Web
Developer Lool included wiLh MicrosoL visual SLudio 200. visual Web Developer has Lhe
look and eel o Lhe visual SLudio lnLegraLed DevelopmenL FnvironmenL (lDF), buL iL is
cusLomized or Web programming and MicrosoL ASP.NF1 4, Lhe MicrosoL .NF1 Framework
componenL designed Lo provide sLaLe-o-Lhe-arL lnLerneL uncLionaliLy. AlLhough a compleLe
descripLion o Web programming and ASP.NF1 isn'L possible here, Lhere's enough in common
beLween Web programming and Windows programming Lo allow you Lo do some useul
experimenLaLion-even i you have liLLle or no experience wiLh HyperLexL Markup Language
(H1ML). lnvesL a ew hours in Lhis chapLer, and you'll see how quickly you can build a Web
siLe LhaL calculaLes loan paymenLs or car loans, creaLe a Web page wiLh Help inormaLion,
and display loan prospecLs rom a MicrosoL Access daLabase by using Lhe CriJview conLrol.
lnside ASP.NT
ASP.NF1 4, MicrosoL's Web developmenL plaLorm, has been enhanced in Lhis release.
Some o Lhe improvemenLs include how Web pages are creaLed in Lhe Web Page Designer,
various eaLure enhancemenLs Lo ASP.NF1 Web pages and ASP.NF1 MvC, supporL or
recenLly inLroduced browsers and handheld devices, a new ASP.NF1 Chcrt server conLrol,
enhancemenLs Lo Lhe lcrmview, listview, and uerylxtenJer conLrols, new dynamic daLa
ASP.
492 Part IV Database and Web Programmng
conLrols and enhancemenLs, and improvemenLs Lo Lhe AJAX (Asynchronous JavaScripL
and XML) programming model. AlLhough ASP.NF1 has some similariLies wiLh an earlier Web
programming Lechnology named AcLive Server Pages (ASP), ASP.
.NF1 2002, and conLinues Lo evolve as new
eaLures are added Lo Lhe .NF1 Framework and visual SLudio soLware. visual Web Developer
is Lhe Lool LhaL you use Lo creaLe and manage ASP.NF1 user inLeraces, commonly called Web
ces or (in a more comprehensive sense) Web sites.
1p ln programming books abouL ASP.NF1, you'll someLimes see Web pages reerred Lo as Web
lcrms and Web siLes reerred Lo as Web cliccticns or ASP.Nl1 cliccticns.
8y using visual Web Developer, you can creaLe a Web siLe LhaL displays a user inLerace,
processes daLa, and provides many o Lhe commands and eaLures LhaL a sLandard
applicaLion or Windows mighL oer. However, Lhe Web siLe you creaLe is viewed in a
Web browser, such as lnLerneL Fxplorer, Mozilla Fireox, Apple Saari, or even one o Lhe
new mobile device Lypes, including Coogle Chrome, Lhe Research in MoLion 8lack8erry
smarL phone, and Lhe Apple iPhone. 1hese Web siLes are Lypically sLored on one or more
Web servers, which use MicrosoL lnLerneL lnormaLion Services (llS) Lo display Lhe correcL
Web pages and handle mosL o Lhe compuLing Lasks required by your Web siLe. (ln visual
SLudio 200, Web siLes can also be locaLed and run on a local compuLer LhaL does noL
require llS, giving you more opLions or developmenL and deploymenL.) 1his disLribuLed
sLraLegy allows your Web siLes Lo poLenLially run on a wide range o lnLerneL-based or
sLand-alone compuLers-wherever your users and Lheir rich daLa sources are locaLed.
1o creaLe a Web siLe in visual SLudio 200, you click Lhe New Web SiLe command on Lhe File
menu, and Lhen use Lhe visual Web Developer Lo build one or more Web pages LhaL will
collecLively represenL your Web siLe. Fach Web page consisLs o Lwo pieces.
A Web Forms page, which conLains H1ML, ASP.NF1 markup, and conLrols Lo creaLe Lhe
user inLerace.
behind" Lhe Web Forms page.
1his division is concepLually much like Lhe Windows Forms you've been creaLing in MicrosoL
visual 8asic-Lhere's a Ul componenL and a code module componenL. 1he code or boLh o
Lhese componenLs can be sLored in a single .
is sLored in an . .aspx. .
ln addiLion Lo Web pages, Web siLes can conLain code modules (. .hLm
.
(Clobal.
Chapter 20 Creatng Web Stes and Web Pages by Usng VsuaI Web DeveIoper and ASP.Nf1 493
pages, and oLher componenLs. ou can use Lhe Web Page Designer and SoluLion Fxplorer Lo
.
Web Pages vs. Wndows forms
WhaL are Lhe imporLanL dierences beLween Web pages and Windows Forms 1o begin
wiLh, Web pages oer a slighLly dierenL programming paradigm Lhan Windows Forms.
Whereas Windows Forms use a Windows applicaLion window as Lhe primary user inLerace
or a program, a Web siLe presenLs inormaLion Lo Lhe user Lhrough one or more Web pages
wiLh supporLing program code. 1hese pages are viewed Lhrough a Web browser, and you
can creaLe Lhem by using Lhe Web Page Designer.
Like a Windows Form, a Web page can include LexL, graphic images, buLLons, lisL boxes, and
oLher objecLs LhaL are used Lo provide inormaLion, process inpuL, or display ouLpuL. However,
Lhe basic seL o conLrols you use Lo creaLe a Web page is noL Lhe seL on Lhe Common ConLrols
Lab o Lhe 1oolbox. lnsLead, ASP.NF1 Web siLes musL use conLrols on one o Lhe Labs in Lhe
visual Web Developer 1oolbox, including SLandard, DaLa, H1ML, and many oLhers. Fach o
Lhe visual Web Developer conLrols has iLs own unique meLhods, properLies, and evenLs, and
alLhough Lhere are many similariLies beLween Lhese conLrols and Windows Forms conLrols,
Lhere are also several imporLanL dierences. For example, Lhe visual SLudio DctcCriJview
conLrol is called CriJview in visual Web Developer and has dierenL properLies and meLhods.
Many Web page conLrols are server ccntrcls, meaning LhaL Lhey run on Lhe Web server.
. H1ML conLrols (locaLed on Lhe H1ML Lab
o Lhe visual Web Developer 1oolbox) are client ccntrcls by deaulL, meaning LhaL Lhey run
only wiLhin Lhe user's browser. For now, however, you simply need Lo know LhaL you can use
server conLrols, H1ML conLrols, or a combinaLion o boLh in your Web siLe projecLs. As you
gain experience in Web programming, you may wanL Lo invesLigaLe AJAX programming in
user-inLerace elemenLs or users.
Server ControIs
Server conLrols are more capable Lhan H1ML conLrols and uncLion in many ways like Lhe
Windows Forms conLrols. lndeed, many o Lhe server conLrols have Lhe same names as Lhe
Windows Forms conLrols and oer many o Lhe same properLies, meLhods, and evenLs. ln
addiLion Lo simple conLrols such as 3uttcn, 1ext3cx, and lcbel, more sophisLicaLed conLrols
such as Chcrt, lileUlccJ, lcinview, and RequireJlielJvcliJctcr are provided on a number
o Labs in Lhe 1oolbox, visual SLudio 200 has added a number o conLrols Lo Lhe lisL. 1he
screen shoL on Lhe ollowing page shows a sample o Lhe server conLrols in Lhe visual Web
Developer 1oolbox. (Dynamic DaLa and ReporLing conLrols are noL shown.)
494 Part IV Database and Web Programmng
H1ML ControIs
1he H1ML conLrols are a seL o older user inLerace (Ul) conLrols LhaL are supporLed by all
Web browsers and conorm closely Lo Lhe early H1ML sLandards developed or managing
Ul elemenLs on a Lypical Web page. 1hey include 3uttcn, 1ext, and Checlbcx-useul basic
conLrols or managing inormaLion on a Web page LhaL can be represenLed enLirely wiLh H1ML
code. lndeed, you mighL recognize Lhese conLrols i you've coded in H1ML beore. However,
alLhough Lhey're easy Lo use and have Lhe advanLage o being a "common denominaLor"
or Web browsers, Lhey're limiLed by Lhe acL LhaL Lhey have no abiliLy Lo mainLain Lheir own
sLaLe. (ln oLher words, Lhe daLa LhaL Lhey conLain will be losL beLween views o a Web page.)
1he ollowing screen shoL shows Lhe H1ML conLrols oered on Lhe H1ML Lab o Lhe 1oolbox
in visual Web Developer.
Chapter 20 Creatng Web Stes and Web Pages by Usng VsuaI Web DeveIoper and ASP.Nf1 495
BuiIding a web Site by Using VisuaI
web DeveIoper
1he besL way Lo learn abouL visual Web Developer and ASP.NF1 is Lo geL some hands-on
pracLice. ln Lhe exercises in Lhis chapLer, you'll creaLe a simple car loan calculaLor LhaL
deLermines monLhly paymenLs and conLains an AbouL Lab LhaL explains how Lhe program
works. LaLer in Lhe chapLer, you'll use Lhe CriJview conLrol Lo display a Lable o daLa on
a Web page in Lhe same Web siLe. ou'll begin by veriying LhaL visual SLudio is properly
.NF1 programming, and Lhen you'll creaLe a new Web siLe projecL. NexL,
you'll use Lhe Web Page Designer Lo creaLe a Web page wiLh LexL and links on iL, and you'll
use conLrols in Lhe visual Web Developer 1oolbox Lo add conLrols Lo Lhe Web page.
Consderng Software Requrements
for ASP.Nf1 Programmng
.NF1 Web siLe, you need Lo make sure your compuLer is
seL up properly. 1o perorm ASP.NF1 programming, you need Lo have visual Web Developer
insLalled. visual Web Developer is a componenL o visual SLudio 200 Proessional, Premium,
and more advanced ediLions. ou can also download visual Web Developer 200 Fxpress aL
htt.//www.micrcscjt.ccm/exress/Web/, and iL conLains almosL all Lhe eaLures described in Lhis
chapLer (l'll poinL ouL any dierences as we go). l you are using visual Web Developer 200
Fxpress, be sure Lo seL Lhe seLLings Lo FxperL by clicking Lhe 1ools menu, clicking SeLLings, and
Lhen clicking FxperL SeLLings. 1his will ensure LhaL Lhe sLeps in Lhis chapLer more closely maLch
your soLware.
visual SLudio 200 and visual Web Developer include Lheir own local Web server, so seLLing up
.NF1
Framework is noL required. Having a local Web server makes iL easy Lo creaLe and LesL your
ASP.NF1 Web siLes, and you'll see iL described below as Lhe ASP.NF1 DevelopmenL Server.
ln visual SLudio 200, you can creaLe and run your Web siLe in one o Lhree locaLions.
our own compuLer (via Lhe ASP.NF1 DevelopmenL Server)
An H11P server LhaL conLains llS and relaLed componenLs
hardware or soLware.
.
.
Chapter 20 Creatng Web Stes and Web Pages by Usng VsuaI Web DeveIoper and ASP.Nf1 497
1he
.
5. Click OK Lo accepL your selecLions.
visual SLudio loads visual Web Developer and creaLes a Web page (DeaulL.aspx) Lo
.aspx.vb) LhaL will sLore Lhe
code or your Web page.
6. l you don'L see DeaulL.aspx open in Lhe Web Page Designer, double-click DeaulL.aspx
in SoluLion Fxplorer now Lo open iL.
7. AL Lhe boLLom o Lhe Web Page Designer, click Lhe Design Lab.
our screen looks someLhing like Lhe one shown in Lhe ollowing screen shoL.
Unlike Lhe Windows Forms Designer, Lhe Web Page Designer displays Lhe Web page in
Lhree possible views in Lhe lDF, and Lhree Labs aL Lhe boLLom o Lhe Designer (Design,
SpliL, and Source) allow you Lo change your view o Lhe Web page.
1he Design Lab shows you approximaLely how your Web page will look when a Web
browser displays iL. When Lhe Design Lab is selecLed, a basic LemplaLe page ("My
ASP.NF1 ApplicaLion") appears in Lhe Designer wiLh Lhe resulL o source-code
ormaLLing, and you can add conLrols Lo your Web page and adjusL how objecLs on
Lhe page are arranged.
On Lhe Source Lab, you can view and ediL Lhe H1ML and ASP.NF1 markup LhaL's used Lo
display Lhe Web page in a Web browser. l you've used MicrosoL Fxpression Web, you'll
498 Part IV Database and Web Programmng
be amiliar wiLh Lhese Lwo ways o displaying a Web page and perhaps also wiLh some
o Lhe H1ML Lags LhaL conLrol how Web pages are acLually displayed. 1he SpliL Lab
oers a composiLe view o Lhe Design and Source Labs.
A ew addiLional dierences beLween Lhe Windows Forms Designer and Lhe Web
Page Designer are worLh noLing aL Lhis poinL. 1he 1oolbox now conLains several
collecLions o conLrols used exclusively or Web programming. SoluLion Fxplorer also
conLains a
ollowing screen shoL. ln parLicular, noLice Lhe DeaulL.
conLains Lhe Ul code or Lhe acLive Web page. NesLed under Lhe DeaulL.aspx
.aspx.vb. .
and a .masLer are also lisLed.
Note When you close your new Web siLe and exiL visual Web Developer, noLe LhaL you open
Lhe Web siLe again by clicking Lhe visual SLudio File menu and Lhen clicking Lhe Open Web SiLe
command. Web siLes are noL opened by using Lhe Open ProjecL command on Lhe File menu.
Now you're ready Lo add some LexL Lo Lhe Web page by using Lhe Web Page Designer.
Using the web Page Designer
Unlike a Windows Form, a Web page can have LexL added direcLly Lo iL when iL is in Lhe Web
Page Designer. ln Source view, Lhe LexL appears wiLhin H1ML and ASP.NF1 Lags somewhaL as
iL does in Lhe visual SLudio Code FdiLor. ln Design view, Lhe LexL appears in Lop-Lo-boLLom
ashion wiLhin a grid as iL does in a word processor such as MicrosoL Word, and you'll see no
H1ML. ln Lhe nexL exercises, you'll Lype LexL in Design view, ediL iL, and Lhen make ormaLLing
changes by using buLLons on Lhe FormaLLing Loolbar. ManipulaLing LexL in Lhis way is usually
502 Part IV Database and Web Programmng
3. Double-click Lhe 1ext3cx conLrol on Lhe SLandard Lab o Lhe 1oolbox Lo creaLe a LexL
box objecL aL Lhe inserLion poinL on Lhe Web page.
NoLice Lhe cs.textbcx=1ext3cx1 LexL LhaL appears above Lhe LexL box objecL. 1he "asp"
.NF1 server conLrol. (1his LexL disappears when
you run Lhe program.)
4. Click Lhe righL side o Lhe LexL box objecL Lo place Lhe inserLion poinL aL Lhe ouLside
edge, and Lhen press FN1FR.
5. Double-click Lhe 1ext3cx conLrol again Lo add a second LexL box objecL Lo Lhe
Web page.
6. RepeaL SLeps 4 and 5 Lo creaLe a Lhird LexL box objecL below Lhe second LexL box.
Now you'll use Lhe lcbel conLrol Lo inserL labels LhaL idenLiy Lhe purpose o Lhe LexL
boxes.
7.
edge o Lhe LexL box.
8. Press Lhe SPACF8AR key Lwice Lo add Lwo blank spaces, and Lhen double-click Lhe lcbel
conLrol in Lhe 1oolbox Lo add a label objecL Lo Lhe Web page.
9. RepeaL SLeps 7 and 8 Lo add label objecLs Lo Lhe righL o Lhe second and Lhird LexL boxes.
l0. Click Lo Lhe righL o Lhe Lhird label objecL Lo place Lhe inserLion poinL Lo Lhe righL o Lhe
label, and Lhen press FN1FR.
ll. Double-click Lhe 3uttcn conLrol Lo creaLe a buLLon objecL aL Lhe boLLom o Lhe Web page.
1he 3uttcn conLrol, like Lhe 1ext3cx and lcbel conLrols, is very similar Lo iLs Windows
Forms counLerparL. our screen looks like Lhis.
506 Part IV Database and Web Programmng
LocaLor (URL) on your compuLer LhaL has been esLablished, as shown in Lhe ollowing
screen shoL. ou'll also see a message abouL debugging.
1he poLenLially conusing Debugging NoL Fnabled dialog box is noL a major concern.
visual Web Developer is jusL indicaLing LhaL Lhe Web.
noL currenLly allow debugging (a sLandard securiLy eaLure). AlLhough you can bypass
Lhis dialog box each Lime LhaL you LesL Lhe applicaLion wiLhin visual Web Developer by
clicking Lhe Run WiLhouL Debugging buLLon, l recommend LhaL you modiy Lhe Web.
.
Securty 1p 8eore you widely disLribuLe or deploy a real Web siLe, be sure Lo disable
debugging in Web. .
2. Click OK Lo modiy Lhe Web. .
page in lnLerneL Fxplorer.
1he car loan calculaLor looks like Lhe screen shoL on Lhe ollowing page. l lnLerneL
Fxplorer does noL appear, you mighL need Lo selecL iL on Lhe Windows Laskbar.
Chapter 20 Creatng Web Stes and Web Pages by Usng VsuaI Web DeveIoper and ASP.Nf1 507
Securty 1p ou mighL see Lhe lnormaLion 8ar aL Lhe Lop o lnLerneL Fxplorer indicaLing
LhaL inLraneL seLLings are Lurned o by deaulL. An inLraneL warning is again relaLed Lo
lnLerneL Fxplorer's design Lo proLecL you rom rogue programs or unauLhorized access.
An inLraneL is a local neLwork (Lypically a home neLwork or small workgroup neLwork),
and because visual SLudio uses inLraneL-sLyle addressing when you LesL Web siLes builL on
your own compuLer, you're likely Lo see Lhis warning message. 1o suppress Lhe warning
Lemporarily, click Lhe lnormaLion 8ar and Lhen click Don'L Show Me 1his Again. 1o remove
inLraneL warnings more permanenLly, click Lhe lnLerneL OpLions command on Lhe 1ools
menu o lnLerneL Fxplorer, click Lhe SecuriLy Lab, and Lhen click Local lnLraneL. Click Lhe
SiLes buLLon, and clear Lhe check mark rom AuLomaLically DeLecL lnLraneL NeLwork in
Lhe Local lnLraneL dialog box. However, exercise cauLion whenever you disable securiLy
warnings, as Lhey are meanL Lo proLecL you.
Now, leL's geL back Lo LesLing our Web page.
3. 1ype l8000 in Lhe Loan AmounL LexL box, and Lhen Lype 0.09 in Lhe lnLeresL RaLe
LexL box.
ou'll compuLe Lhe monLhly loan paymenL or an S8,000 loan aL 9 percenL inLeresL or
86 monLhs.
508 Part IV Database and Web Programmng
4. Click Lhe CalculaLe buLLon.
visual 8asic calculaLes Lhe paymenL amounL and displays S572.40 in Lhe MonLhly
PaymenL LexL box. our screen looks like Lhis.
5. Close lnLerneL Fxplorer.
. When lnLerneL Fxplorer closes, your
program is eecLively ended. As you can see, building and viewing a Web siLe is
basically Lhe same as building and running a Windows applicaLion, excepL LhaL Lhe
Web siLe is execuLed in Lhe browser. ou can even seL break poinLs and debug your
applicaLion jusL as you can in a Windows applicaLion.
Curious abouL insLalling a Web siLe like Lhis on an acLual Web server 1he basic procedure or
deploying Web siLes is Lo copy Lhe .
.NF1 Framework 4.
1here are a couple o ways Lo perorm deploymenL in visual Web Developer. 1o geL sLarLed,
click Copy Web SiLe on Lhe WebsiLe menu, or click Publish Web SiLe on Lhe 8uild menu.
(visual Web Developer 200 Fxpress does noL include Lhe Publish Web SiLe command.)
For more inormaLion abouL your opLions, see "ASP.NF1 DeploymenL ConLenL Map" in Lhe
visual SLudio Help documenLaLion. .NF1 Web
applicaLions, you can check ouL htt.//www.cs.net.
5l0 Part IV Database and Web Programmng
2. DeleLe Lhe placeholder LexL, and Lhen Lype Lhe ollowing inormaLion.
Car Loan CaIcuIator
The Car Loan CaIcuIator web site was deveIoped for the book Microsojt visuol
8osic 20I0 Ste by Ste, by MichaeI HaIvorson {Microsoft Press, 20l0). The web
site is best viewed using Microsoft lnternet xpIorer version 6.0 or Iater. To Iearn
more about how this ADO.NT appIication was created, read Chapter 20 in the
book.
Operating lnstructions.
Type a Ioan amount, without doIIar sign or commas, into the Loan Amount box.
Type an interest rate in decimaI format into the lnterest kate text box. Do not
incIude the "% sign. lor exampIe, to specify a 9% interest rate, type "0.09.
Note that this Ioan caIcuIator assumes a three-year, 36-month payment period.
CIick the CaIcuIate button to compute the basic monthIy Ioan payment that does
not incIude taxes or other fees.
3. Using buLLons on Lhe FormaLLing Loolbar, add bold ormaLLing or Lhe headings and
iLalic or Lhe book LiLle, as shown here.
4. Click Lhe Save All buLLon on Lhe SLandard Loolbar Lo save your changes.
5. Click Lhe SLarL Debugging buLLon.
visual SLudio builds Lhe Web siLe and displays iL in lnLerneL Fxplorer.
Chapter 20 Creatng Web Stes and Web Pages by Usng VsuaI Web DeveIoper and ASP.Nf1 5ll
6. Click Lhe Home Lab on Lhe Web page.
visual SLudio displays Lhe Home page or your Web siLe, Lhe car loan calculaLor.
7. CompuLe anoLher loan paymenL Lo experimenL urLher wiLh Lhe loan calculaLor.
l you wanL Lo LesL anoLher seL o numbers, Lry enLering 20000 or Lhe loan amounL
and 0.075 or Lhe inLeresL raLe. 1he resulL should be S622.2.
8. Now click Lhe AbouL Lab Lo view Lhe AbouL Web page wiLh insLrucLions or your
program.
lnLerneL Fxplorer displays Lhe AbouL page on Lhe screen. our browser looks someLhing
like Lhis.
9. Read Lhe LexL, and Lhen click Lhe 8ack buLLon in lnLerneL Fxplorer.
JusL like any Web siLe, Lhis one leLs you click Lhe 8ack and Forward buLLons Lo jump
rom one Web page Lo Lhe nexL.
l0. Close lnLerneL Fxplorer Lo close Lhe Web siLe.
ou've added a simple AbouL page Lo your Web siLe, and you have experimenLed
wiLh moving rom one page Lo Lhe nexL. PreLLy cool so ar. Now, Lry someLhing more
sophisLicaLed LhaL shows how ar you can Lake your Web siLe i you choose Lo include
inormaLion rom a daLabase.
5l4 Part IV Database and Web Programmng
5. Click Lhe Access DaLabase icon, Lype lacuIty20l0 in Lhe Speciy An lD For 1he DaLa
Source box, and Lhen click OK.
ou are now prompLed Lo speciy Lhe locaLion o Lhe Access daLabase on your sysLem.
(1his dialog box is slighLly dierenL Lhan Lhe one you used in ChapLer 8.)
6. 1ype C.\Vbl0sbs\Chapl8\lacuIty20l0.accdb, and Lhen click NexL.
Note l you geL a message LhaL says "1he MicrosoL.ACF.OLFD8.2.0 provider is noL
regisLered on Lhe local machine," you mighL noL have Access 2007 or laLer insLalled. l you
don'L have Access 2007 or laLer insLalled, you will need Lo download and insLall Lhe 2007
.com.
LhaL you wanL Lo display on your Web page. lcculty
Lable. cclumns,
so you'll see Lhe word cclumns used in Lhe lDF and Lhe ollowing insLrucLions.)
7. Click Lhe Name lisL box arrow, and Lhen click FaculLy. (1here is probably only one or Lwo
daLabase Lables here, buL i Lhere are several, click Lhe Name arrow Lo view Lhem.)
8. SelecL Lhe LasL Name and 8usiness Phone check boxes in Lhe Columns lisL box.
our screen looks like Lhis.
Chapter 20 Creatng Web Stes and Web Pages by Usng VsuaI Web DeveIoper and ASP.Nf1 5l5
a daLaseL represenLing a porLion o Lhe FaculLy200.accdb daLabase. ou can see Lhe
SFLFC1 sLaLemenL aL Lhe boLLom o Lhis dialog box.
9. Click NexL Lo see Lhe 1esL uery screen.
l0. Click Lhe 1esL uery buLLon Lo see a preview o your daLa.
ou'll see a preview o acLual lcst Ncme and 3usiness Phcne .
1his daLa looks as expecLed, alLhough i we were preparing Lhis Web siLe or wider
disLribuLion, we would Lake Lhe exLra sLep o ormaLLing Lhe 8usiness Phone column
so LhaL iL conLains sLandard spacing and phone number ormaLLing.
ll. Click Finish.
visual Web Developer closes Lhe wizard and adjusLs Lhe number o columns and
column headers in Lhe grid view objecL Lo maLch Lhe selecLions LhaL you have made.
However, iL conLinues Lo display placeholder inormaLion ("abc") in Lhe grid view cells.
l2. WiLh Lhe Cridview 1asks lisL sLill open, click Lhe AuLo FormaL command.
l3. Click Lhe Proessional scheme.
1he AuLoFormaL dialog box looks like Lhis.
1he abiliLy Lo ormaL, adjusL, and preview ormaLLing opLions quickly is a greaL eaLure
o Lhe CriJview conLrol.
l4. Click OK, and Lhen close Lhe Cridview 1asks lisL.
1he FaculLyLoanLeads.aspx Web page is compleLe now, and looks like Lhe screen
shoL on Lhe ollowing page. (My CriJview conLrol is wiLhin a <Jiv> Lag, buL yours
mighL be wiLhin a <> Lag.)
5l8 Part IV Database and Web Programmng
1he new hyperlink (Display Loan ProspecLs) is visible aL Lhe boLLom o Lhe Web page.
3. Click Display Loan ProspecLs Lo load Lhe daLabase Lable.
lnLerneL Fxplorer loads Lhe lcst Ncme and 3usiness Phcne .
accdb daLabase inLo Lhe grid view objecL. our Web page looks someLhing like Lhis.
Chapter 20 Creatng Web Stes and Web Pages by Usng VsuaI Web DeveIoper and ASP.Nf1 52l
2. DeleLe Lhe LiLle "M ASP.NF1 APPLlCA1lON" and Lype TlM lOk A Nw CAk?
visual Web Designer enLers your new LiLle. Now run Lhe Web siLe again.
3. Click Lhe SLarL Debugging buLLon.
visual SLudio opens lnLerneL Fxplorer and loads Lhe Web siLe. Now a more useul LiLle
bar and banner message appears, as shown in Lhe ollowing screen shoL.
Now LhaL looks beLLer.
4. Close lnLerneL Fxplorer, and Lhen updaLe Lhe 1itle properLies or Lhe oLher Web pages
on your Web siLe.
5.
and close visual SLudio.
CongraLulaLions on compleLing Lhe enLire Micrcscjt visucl 3csic 2919 Ste by Ste
you have learned. Now you're ready or more sophisLicaLed visual 8asic challenges and
programming Lechniques. Check ouL Lhe resource lisL in Lhe Appendix, "Where Lo Co or More
lnormaLion," or a ew ideas abouL conLinuing your learning.
earned iL!
523
Appendix
Where to Go for More Informaton
1his book has presenLed beginning, inLermediaLe, and advanced MicrosoL visual 8asic 200
Windows programmer. Now LhaL you've experimenLed wiLh many o Lhe Lools and eaLures
in visual 8asic 200, you're ready or more advanced Lopics and Lhe ull breadLh o Lhe
MicrosoL visual SLudio 200 developmenL suiLe.
l you have your sighLs seL on a career in visual 8asic programming, you mighL also wanL Lo
. ln
Lhis appendix, you'll learn abouL addiLional resources or visual 8asic programming, including
expand your visual 8asic programming skills.
VisuaI Basic web Sites
Lhe laLesL inormaLion abouL visual 8asic 200 and relaLed Lechnologies. ln Lhis secLion, l lisL
several o Lhe Web siLes LhaL l use Lo learn abouL new producLs and services relaLed Lo visual
8asic. As you use Lhis lisL, noLe LhaL Lhe lnLerneL address and conLenLs o each siLe change
rom Lime Lo Lime, so Lhe siLes mighL noL appear exacLly as l've described Lhem. Considering
"visual SLudio 200," and "visual 8asic 1uLorial" occasionally Lo see whaL new inormaLion is
available. .)
such as "visual 8asic 0."
htt.//msJn.micrcscjt.ccm/en-us/vbcsic/Jejcult.csx
1he MicrosoL visual 8asic Developer CenLer home page is Lhe besL overall siLe or
documenLaLion, breaking news, conerence inormaLion, and producL supporL or visual
8asic 200. (l you're noL inLeresLed in Lhe U.S. Fnglish language siLe, browse Lo Lhe Web
siLe and selecL a dierenL language in Lhe lisL box aL Lhe Lop o Lhe page.) 1he Developer
CenLer gives you up-Lo-daLe inormaLion abouL Lhe enLire visual 8asic producL line and leLs
you know how new operaLing sysLems, applicaLions, and programming Lools aecL visual
8asic developmenL. FeaLures LhaL l like here are Lhe blogs by visual 8asic Leam members,
and access Lo recenL videos and downloads.
524 Appendx
1p Remember LhaL you can also access MSDN resources quickly rom Lhe visual SLudio SLarL
Page wiLhin Lhe visual SLudio lnLegraLed DevelopmenL FnvironmenL (lDF). 1he SLarL Page loads
updaLed arLicles and news conLenL each Lime you sLarL visual SLudio, so iLs conLenLs are always
changing.
htt.//www.micrcscjt.ccm/lecrnin/en/us/trcinin/jcrmct-bccls.csx
1he MicrosoL Learning Web siLe oers Lhe newesL books on visual SLudio programming
rom MicrosoL Press. Check here or new books abouL visual 8asic, MicrosoL visual C#,
MicrosoL visual C--, and supporLing daLabase and Web programming Lechnologies. ou
.
htt.//www.micrcscjt.ccm/lecrnin/en/us/stcrt/stcrt-riht-ccurses.csx
1his URL leads Lo Lhe MicrosoL Learning Web siLe or soLware Lraining and services,
. Over Lhe pasL several years, many visual
8asic programmers have ound LhaL Lhey can beLLer demonsLraLe Lheir developmenL skills Lo
. visiL Lhe Web siLe Lo learn more abouL
.
htt.//www.micrcscjt.ccm/ccmmunities/Jejcult.msx
1his siLe o Lechnical communiLies or many MicrosoL soLware producLs and Lechnologies
oers opporLuniLies Lo inLeracL wiLh MicrosoL employees and your soLware developmenL
peers. 1hrough Lhis Web siLe, you can access blogs, newsgroups, webcasLs, Lechnical chaLs, user
groups, and oLher resources relaLed Lo visual SLudio developmenL. visual SLudio newsgroup
Lopics are currenLly lisLed under Find a CommuniLy in Lhe ProducLs and 1echnologies caLegory.
Video web Sites
1he Web has seen an explosion o video conLenL. 1here are several siLes LhaL have videos
relaLed Lo visual 8asic and programming. l you have a ew minuLes and a high-speed
lnLerneL connecLion, videos can be a greaL way Lo quickly learn someLhing new. l you are Lhe
Lype o person LhaL learns besL by visualizing, check ouL some o Lhese siLes.
htt.//msJn.micrcscjt.ccm/en-us/vbcsic/
Lo visual 8asic. 1hese videos cover a varieLy o areas including new eaLures in visual 8asic 200,
.
htt.//winJcwsclient.net/lecrn/viJecs.csx
Where to Go for More Informaton 525
WindowsClienL.neL is a MicrosoL siLe LhaL has inormaLion abouL wriLing clienL applicaLions
or Windows. 1he siLe ocuses on Lwo presenLaLion Lechnologies, Windows Forms and
Windows PresenLaLion FoundaLion (WPF). ln addiLion Lo Lechnical arLicles, hands-on labs,
samples, orums, and blog posLs, Lhis siLe also has videos. 1he Windows Forms videos are
a greaL place Lo conLinue your learning aLer compleLing Lhis book.
htt.//chcnnel9.msJn.ccm/lecrn/
Channel 9 is a MicrosoL siLe LhaL hosLs videos and discussions around programming.
lL has a learning cenLer LhaL has online Lraining videos. Some o Lhe Lraining includes visual
SLudio 200, .
SL Server, and Windows Phone.
htt.//live.visitmix.ccm/viJecs
Mix is a yearly MicrosoL conerence LhaL ocuses on currenL and upcoming Web
Lechnologies. All o Lhe sessions are recorded and posLed online or ree. 1he Lechnologies
include SilverlighL, ASP.NF1, visual SLudio, Web services, H1ML, lnLerneL Fxplorer, and
Windows Phone.
htt.//micrcscjtJc.ccm/viJecs
PDC, or Lhe Proessional Developers Conerence, is a MicrosoL conerence LhaL ocuses on
uLure MicrosoL Lechnologies. All o Lhe sessions are recorded and posLed online or ree.
1he Lechnologies include Windows, Windows Azure, WPF, ASP.NF1, ADO.NF1, visual SLudio,
.
htt.//www.lecrnvisuclstuJic.net/
1he LearnvisualSLudio.NF1 siLe is a pay siLe LhaL includes over 500 videos LhaL LargeL beginner
Lo experienced skill levels. 1he videos cover several areas in .NF1 including Lhe .NF1 Framework,
visual SLudio, visual 8asic, C#, Windows Forms, WPF, ASP.NF1, ADO.NF1, and SL Server.
Books about VisuaI Basic and VisuaI
Studio Programming
8ooks abouL visual 8asic and visual SLudio programming provide in-depLh sources o
inormaLion and sel-paced Lraining LhaL Web siLes can supplemenL buL noL replace. As you
seek Lo expand your visual 8asic and visual SLudio programming skills, l recommend LhaL
you consulL Lhe ollowing sources o prinLed inormaLion (lisLed here by caLegory and daLe
o publicaLion). NoLe LhaL Lhis isn'L a compleLe bibliography o visual SLudio LiLles, buL iL is
a lisL LhaL's represenLaLive o Lhe books available in Fnglish aL Lhe Lime o Lhe iniLial release o
visual SLudio 200. l also lisL books relaLed Lo daLabase programming, Web programming,
visual 8asic or ApplicaLions (v8A) programming, and general books abouL soLware
developmenL and compuLer science.
526 Appendx
VsuaI asc Programmng
visucl 3csic 2919 Prcrcmmers Rejerence, by Rod SLephens (Wrox,
lS8N 978-0-470-49988-2).
Prcjessicncl visucl StuJic 2919, by Nick Randolph, David Cardner, Chris Anderson,
and Michael MinuLillo (Wrox, lS8N 978-0470548658).
Prcrcmmin WinJcws Services with Micrcscjt visucl 3csic 2998, by Michael Cernaey
(MicrosoL Press, lS8N 978-0-7856-2488-7).
Prccticcl CuiJelines cnJ 3est Prcctices jcr Micrcscjt visucl 3csic cnJ visucl C= Develcers,
by Francesco 8alena and Ciuseppe Dimauro (MicrosoL Press, lS8N 978-0-7856-272-5).
Prcrcmmin Micrcscjt visucl 3csic 2995. 1he lcnuce, by Francesco 8alena
(MicrosoL Press, lS8N 978-0-7856-288-). 1his book covers visual 8asic 2005, buL iL
is sLill very useul because many o Lhe language eaLures remain Lhe same beLween
versions.
Mcrosoft .Nf1 framework
Micrcscjt .Nl1 lnterncls, by 1om ChrisLian (MicrosoL Press, lS8N 978-0-7856-2675-).
1akes visual SLudio 200 programmers deep inLo Lhe archiLecLure and inner workings
o Lhe .NF1 Framework. Oers a Lour Lhe core ramework and Lhe Lools LhaL exLend
.NF1, including SilverlighL, WPF, WCF, and WF.
MC1S Selj-PcceJ 1rcinin kit (lxcm 79-5J6). Micrcscjt

.Nl1 lrcmewcrl-Aliccticn
Develcment lcunJcticn, Second FdiLion, by 1ony NorLhup (MicrosoL Press,
lS8N 0-7856-269-7).
Micrcscjt WinJcws Presentcticn lcunJcticn. A Scencric-3cseJ Arccch, by 8illy Hollis
(MicrosoL Press, lS8N 978-0-7856-248-4).
, by Kenn Scribner (MicrosoL
Press, lS8N 978-0-7856-2885-4).
Micrcscjt WinJcws Ccmmuniccticn lcunJcticn Ste by Ste, by John Sharp (MicrosoL
Press, lS8N 978-0-7856-2886-).
Database Programmng wth ADO.Nf1
Prcrcmmin the Micrcscjt ADO.Nl1 lntity lrcmewcrl, by David Sceppa (MicrosoL
Press, lS8N 978-0-7856-2529-7). 1he FnLiLy Framework allows developers Lo consLrucL
Lheir applicaLion model and Lhen map Lhe applicaLion model Lo Lheir daLabase schema.
Developers wriLe queries using eiLher Language lnLegraLed uery (LlN) or FnLiLy
SL. 1he FnLiLy Framework converLs Lhe LlN expressions or FnLiLy SL queries inLo
daLabase queries based on Lhe mapping inormaLion supplied.
Where to Go for More Informaton 527
ADO.Nl1 J.5 Ccclbccl, by 8ill HamilLon (O'Reilly Media, 978-05960404). ADO.NF1 8.5
is parL o visual SLudio 2008, buL sLill useul wiLh visual SLudio 200.
Prcrcmmin Micrcscjt llN, by Paolo Pialorsi and Marco Russo (MicrosoL Press,
lS8N 978-0-7856-2400-9). 1his is a source o in-depLh inormaLion abouL Lhe LlN
Lechnology included wiLh visual SLudio 2008. lL is sLill useul wiLh visual SLudio 200.
Micrcscjt ADO.Nl1 2.9 Ste by Ste, by Rebecca Riordan (MicrosoL Press,
lS8N 978-0-7856-264-0).
Prcrcmmin Micrcscjt ADO.Nl1 2.9 Ccre Rejerence, by David Sceppa (MicrosoL Press,
lS8N 978-0-7856-2206-7).
Prcrcmmin Micrcscjt ADO.Nl1 2.9 Aliccticns. AJvcnceJ 1cics, by Clenn Johnson
(MicrosoL Press, lS8N 978-0-7856-24-).
Note 8ooks abouL ADO.NF1 2.0 remain useul or visual SLudio 200.
Web Programmng wth ASP.Nf1
Micrcscjt ASP.Nl1 4 Ste by Ste, by Ceorge Shepherd (MicrosoL Press,
lS8N 978-0-7856-270-7). ASP.NF1 4 is Lhe version included wiLh visual SLudio 200.
Prcrcmmin Micrcscjt ASP.Nl1 4., by Dino FsposiLo (MicrosoL Press,
lS8N 978-0-7856-2527-8).
Prcrcmmin Micrcscjt ASP.Nl1 MvC, by Dino FsposiLo (MicrosoL Press,
lS8N 978-0-7856-274-7).
Micrcscjt ASP.Nl1 cnJ AIAX. Architectin Web Aliccticns, by Dino FsposiLo
(MicrosoL Press, 978-07856-262-8).
ASP.Nl1 lnterncls, by Ceorge Shepherd (MicrosoL Press, lS8N 978-0-7856-264-6).
Prc ASP.Nl1 4 in v3 2919, 1hird FdiLion, by MaLLhew MacDonald, Mario SzpuszLa,
and vidya vraL Agarwal (Apress, lS8N 978-4802259).
, by Reed Jacobsen
(MicrosoL Press, lS8N 978-0785624028).
.
, by Fric CarLer
and Fric LipperL (Addison-Wesley Proessional, lS8N 978-08258820).
528 Appendx
, by Helen
Feddema (Wiley, lS8N 978-0470047026).
Access 2997 v3A Prcrcmmers Rejerence, by 1eresa Hennig, Rob Cooper, Ceorey L.
.
applicaLions.
no books are available describing v8A and Lhe upgraded Lechnology.
GeneraI ooks about Programmng and Computer Scence
CcJe Ccmlete, Second FdiLion, by SLeve McConnell (MicrosoL Press,
lS8N 978-0-7856-967-8).
resources or sel-LaughL programmers.
CcJe, by Charles PeLzold (MicrosoL Press, lS8N 978-0-7856-8-8).
Writin Secure CcJe, Second FdiLion, by Michael Howard and David Le8lanc
(MicrosoL Press, lS8N 978-0-7856-722-8).
Scjtwcre Prcject Survivcl CuiJe, by SLeve McConnell (MicrosoL Press,
lS8N 978--5728-62-8).
Dctc Structures cnJ Alcrithms Usin visucl 3csic .Nl1, by Michael McMillan
(Cambridge UniversiLy Press, lS8N 978-0-52-54765-9).
1he Art cj Ccmuter Prcrcmmin, vclumes 1-J, by Donald KnuLh (Addison-Wesley
Proessional, lS8N 978-0-20-4854-7). l was given Lhe Lhird-ediLion, Lhree-volume seL
(published in 997-998) as a giL, and iL made my day! l you can aord only one, geL
volume .
Dctc Structures cnJ Alcrithms, by Alred v. Aho, Jerey D. Ullman, and John F.
HopcroL (Addison-Wesley, lS8N 978-0-20-00028-8).
lL is especially imporLanL LhaL sel-LaughL programmers acquire a library o general
programming books over Lime LhaL can help Lhem wiLh more LheoreLical (and non-
language-dependenL) Lopics such as undamenLal algoriLhms, daLa sLrucLures, sorLing,
searching, compression, random numbers, advanced maLhemaLics, neLworking, and
compilers. 1he books lisLed in Lhis appendix are only Lhe beginning, and many can be ound
in used-book sLores.
529
Index
SymboIs
and Numbers
- (subLracLion operaLor),
48, 47
& (sLring concaLenaLion operaLor),
75, 47, 49, 84
* (mulLiplicaLion operaLor),
48, 47
. . . (ellipsis), in menu
commands, 00
.
.
.NF1 Framework
Array class, 288-89
FxcepLion objecLs, 286-87
idenLiying version o, 496
lmporLs sLaLemenL, 248
maLh meLhods, 52-55
MSDN Help in, 28
My namespace, 84-6
overview, 58
speciying version in new
projecLs, 89
SLreamReader class,
86-7
SLring class, 827
SysLem.Drawing
namespace, 876
SysLem.lO namespace, 242
SysLem.MaLh class, 54
.
/ (division operaLor),
48, 47
@ Page direcLive, 50
\ (backslash), 47
(exponenLial operaLor),
48, 47, 49
_ (line conLinuaLion characLer),
75, 87
| (pipe symbol), 8
- (addiLion operaLor), 48, 47
< (less Lhan operaLor), 6, 88
<= (less Lhan or equal Lo operaLor),
6, 88
<> (noL equal Lo operaLor),
6, 88
= (assignmenL or equal Lo operaLor),
6, 82, 88
= (assignmenL or equal Lo), 25
> (greaLer Lhan operaLor), 6, 88
>= (greaLer Lhan or equal Lo
operaLor), 6, 88
>cmd command, using Lo swiLch Lo
Command Window, 228
A
Abs(n) meLhod, 52, 504-05
absoluLe paLh names, 89
Access daLabases,
working wiLh, 444
access keys
adding, 00-02, 9
displaying, in Windows, 00
Add connecLion dialog box, 447
Add ConLrols program
creaLing new Label and 8uLLon
conLrols, 868, 865-66
older locaLion, 866
running, 866-67
Add meLhod (LisL 8ox), 85, 87, 75
Add New lLem dialog box, 248
Add 1oolSLrip 8uLLon buLLon, 09
AddHandler sLaLemenL, 47
adding
code snippeLs, 208
nonsLandard dialog boxes, 7
addiLion operaLor (-), 48, 47
address, coordinaLe sysLem, 876
ADO FaculLy Form program,
456-58
ADO.NF1, 442
ADO.NF1 FnLiLy Framework, 442
Advanced MaLh program,
47-52
AllowFullOpen properLy, 4
All Windows Forms Lab, 67
AllowUser1oResizeColumns
properLy, 478
AlphabeLical buLLon (ProperLies
window), 5
Always Show SoluLion
check box, 7, 8
Anchor and Dock program
older locaLion, 870
organizing objecLs aL run
Lime, 868-69
running, 870-7
Anchor properLy, 868-69
anchoring objecLs, 868-7, 874
And (logical operaLor), 67-69
AndAlso operaLor, 69-7
animaLing objecLs
by using properLies,
880-8
expanding and shrinking,
886-88
moving on orms, 880-8
on orms (Sun icon example),
882-85
animaLion, 880
AnyColor properLy, 4
applicaLions
console, 878-74
daLacenLric, 489
deploying, 62-68, 65
argumenLs
in FuncLion procedures, 257
in Sub procedures, 262
more Lhan one in a
uncLion, 88
passing by value and by
reerence, 268-7
Array Class SorLs projecL, 289-95
Array class, overview, 288-89
array liLeral, 278
arrays. See clsc dynamic arrays,
assigning values Lo, 295
converLing sLrings wiLh separaLors
Lo, 882, 846
creaLing, 274, 295
declaring, 278-79
For . . . NexL loops in, 28-82
overview, 278-74
processing elemenLs in, 295
public, creaLing, 295
redimensioning, preserving daLa
in, 295
reordering conLenLs o, 296
scope o, 274
seLLing aside memory or, 276
sorLing, 289-95
synLax elemenLs, Lable o, 274
Lhree-dimensional, 288
working wiLh elemenLs, 277
As keyword, 25
As 1ype keyword, 257
Asc uncLion, 880, 889, 847
ASCll codes
characLers, sorLing and, 829
converLing, 880, 847
530 ASP.Nf1
deLermining, 880
dramaLic shiLs in causing
errors, 840
encrypLing LexL by changing,
887-88
ASP.NF1
overview, 49-98
soLware requiremenLs or, 495
Lags, 50
Web siLes, creaLing, 522
assemblies, 2, 62
assigning
color, 8
value and simulLaneously
declaring variables, 207
assignmenL or equal Lo operaLor (=),
25, 6, 82, 88
ALan(n) meLhod, 52
AuLo FormaL command, 55
AuLo Hide command (Windows
menu), 7, 2-22, 84
AuLos window
described, 26
overview, 27
using, 225
AuLoSize properLy (LayouL
caLegory), 47-48, 98
B
background colors and images, 89
backslash (\), 47
base classes
creaLing, 899, 42
inheriLing, 408-
inheriLing in new classes, 48
8asic MaLh program
program sLaLemenLs, 45-47
working wiLh basic operaLors,
44-45
[ ] (brackeLs), 257
8indingNavigaLor conLrol, 485
8indingSource properLy, 468
8irLhday program
building, 78-76
older locaLion, 76
running, 76-78
biLmaps, 2
biLs, 85
8oolean daLa Lype, 86
8oolean expressions, 68
8oolean properLies, 5
8orderSLyle properLy (Appearance
caLegory), 47
bound conLrols, 454
bound objecLs, 466
brackeLs ([ ]), 257
break mode. See debugging mode
breakpoinLs
removing, 224-25
seLLing, 28, 225
browsers
opening Web, 28-24
seLLing deaulL, 98
8rush objecL, 877
8uild command, 6
building Web siLes, 505-08
8uLLon conLrol (1oolbox)
creaLing, 865-66
creaLing buLLons wiLh, 70
using wiLh Web pages, 502
buLLons
adding, 40-42
creaLing, 7, 95
ellipsis, 5
overview, 7
radio, 8-88
smarL Lag, 50
Loolbar, 08-0
view Designer, 54
8yRe keyword
in Sub procedures, 262, 266
passing argumenLs wiLh, 268-70
when Lo use, 270
8yLe daLa Lype, 86
byLes, 85
8yval keyword
deaulL seLLing, 262
passing argumenLs wiLh, 268-70
when Lo use, 270
C
calculaLions
perorming wiLh uncLions,
258-6
visual eedback during, 296
calling
orms, DialogFvenL properLy in,
858-59
FuncLion procedures, 258, 27
prinLing evenL handlers, 487
Sub procedures, 262-68, 27
Car Loan CalculaLor projecL
adding conLrols Lo, 50-02
adding LexL in Web Page
Designer, 499-50
cusLomizing, 509-
LesLing, 507-08
Web siLe or, 505-08
Windows Forms Designer vs, 498
carriage reLurn
as separaLors in lines o LexL, 882
characLers, 84
ormaLLing LexL sLrings wiLh, 295
Case Flse clause, 72
case sensiLiviLy in code, 80, 98
CaLch code blocks. See 1ry . . . CaLch
code blocks
CaLegorized buLLon (ProperLies
window), 5
CaLegorized buLLon (ProperLy
window), 45
CDbl uncLion, 504-05
cells, changing colors o, 480-8
CellSLyle 8uilder dialog box, 480-8
Celsius Conversion program
older locaLion, 95
using Do loops, 98-96
changing
compiler seLLings in lDF, 29-80
deaulL page in Web
browser, 28
properLy seLLings, 4-6
Char daLa Lype, 86
characLers
ASCll seL, 829-80
carriage reLurn, 84
converLing Lo ASCll codes, 847
l8M exLended seL, 880
maximum number o,
in LexL lines, 85
password, 69
Unicode, 880
check boxes, creaLing, 78-80, 95
check marks, adding, 00
Check8ox conLrol (1oolbox), 78-80
Check8ox program
creaLing, 78-80
older locaLion, 80
running, 8
CheckedChanged evenL
procedure, 88
CheckedLisL8ox conLrol, 85
CheckSLaLe properLy, 80
Choose DaLa Source dialog box, 446
Chr uncLion, 880, 889, 847
class libraries, 90, 57
class variables, declaring, 408-04
classes
adding new Lo projecLs, 40
base. See base classes
creaLing, 402-08
declaring objecL variables
Lo use, 48
wiLh, 487
inheriLing, 48
meLhods, creaLing in, 405-06, 42
overview, 40
properLies, creaLing in,
404-05, 42
controIs 53l
Click procedure, 56-58
ClickOnce Lechnology, 62, 65
clienL conLrols. See H1ML
Clock menu program
adding access keys Lo, 0-02
changing order o iLems, 02
creaLing, 98-99
ediLing menu evenL procedures,
08-05
clock properLies, 06
closing
programs, 8
programs wiLhouL saving, 25-52
Lool windows, 7
visual SLudio, 88
code
case sensiLiviLy in, 98
characLer lengLh o lines, 75
commenLs in, 86
declaring variables aL Lop
o orm, 89
execuLing one line o, 225
or displaying PrinL dialog box
H1ML in Web pages, 522
opening hidden orms wiLh, 878
program sLyle, 54
proLecLed, 229
using undamenLal daLa
Lypes in, 87-4
viewing,
wriLing, 52-56, 65
Code FdiLor
characLer lengLh o lines
o code, 75
displaying, 54
enLering program sLaLemenLs,
52-56
examining expressions,
properLies, variables in, 225
execuLing one line, o code in, 225
idenLiying misLakes in, 54-55
opening, 52, 65
code snippeLs
adding, 208
inserLing, 208-08
reorganizing, 207-08
Code SnippeLs Manager command,
207-08
Code SnippeLs Manager
dialog box, 207
collecLions. See clsc ConLrols
collecLion
creaLing, 804-06, 82
overview, 297
processing objecLs in, 8
reerencing objecLs in, 298
special LreaLmenL or
objecLs in, 8
Lracking lnLerneL addresses wiLh,
805-06
color
assigning, 8
changing, 6
changing cell, 480-8
in visual 8asic code, idenLiying
elemenLs wiLh, 54
seLLing background, 89
seLLing oreground, 49
Color dialog box
cusLomizing color seLLings, 4
opening, 6
wriLing evenL procedures or
buLLon, 8-4
ColorDialog conLrol
adding,
properLies o, 4
purpose, 0
ColumnHeadersvisible properLy,
480, 489
columns. See clsc
changing widLh, 478, 489
hiding headers, 480, 489
removing, 476, 488
Combo8ox conLrol, 85
command prompL, 878
Command window
overview, 228
running commands in
lDF rom, 226
running File.SaveAll, 224
swiLching rom lmmediaLe
window, 228, 226
commands
>cmd, 228
AuLo Hide (Windows menu),
2-22
menu, guidelines, 00
running in lDF rom Command
window, 226
commas, displaying wiLh FormaL
uncLion, 40, 87
commenL characLer ('), 295
commenLs, 57, 86, 95
comparing sLrings, 88, 829-8
comparison (or relaLional)
operaLors, 6, 78-77, 880-8
compiler seLLings
checking, 8-88
cusLomizing, 29-80
in visual SLudio, 82-88
compiler seLLings, checking, 8-88
compiling
orms inLo .exe or .
programs, 84
componenL Lray, displaying in Lhe
lDF, 98
componenLs
daLa access layer, 45
swiLching beLween, 8
condiLional expressions
comparing, 67-69, 79
l . . . 1hen decision sLrucLure,
6-62
in Do Loops, 92
logical operaLors in, 67-69
order o l sLaLemenLs, 68
order o operaLor Lypes, 67
wriLing, 79
daLa source or Web display,
54-5
daLe Lime picker objecL, 78
individual columns, 479-80
SL sLaLemenLs, 54-5
visual SLudio or visual 8asic
DevelopmenL, 84
connecLing
Lo daLabase Lables, 488
Lo daLabases, 466, 468-7
connecLion sLring, 446
connecLions
binding Lo conLrols on orms, 448
choosing, 448
esLablishing, using DaLa Source
console applicaLions, 878-74
ConsLanL 1esLer program, 42-48
consLanLs
creaLing, 57
in program code, 42-48
vbCR, 206
conLinuing lines wiLh _ characLer,
75, 87
conLrols
adding Lo orms, 854, 864-67, 874
adding Lo Web pages, 522
bound, 454-55
dialog box, 0-
masked LexL box, binding Lo
daLaseL objecLs, 458-59
moving wiLh For Fach . . . NexL
loops, 80-02
on user inpuL, 64-67
organizaLion o, in 1oolbox, 4
organizing, on orms, 867-7
overview, 67
server vs. clienL, 498
532 ControIs coIIecton
server, adding Lo Web pages,
50-02
validaLor, 509, 522
Windows Forms, 67
wriLing evenL procedures or Web
pages, 504-05
ConLrols collecLion.
See clsc collecLions
moving conLrols wiLh
For Fach . . . NexL loops, 80-02
moving objecLs, 8
Name properLy or special
LreaLmenL o objecLs, 808-04
objecL experimenLaLion
procedure, 299
overview, 297
ConLrols collecLion program
moving conLrols wiLh
For Fach . . . NexL loops, 80-02
using For Fach . . . NexL loops
Lo change 1exL properLies,
299-80
converL Lo sLring (CSLr)
uncLion, 57
coordinaLe sysLem, 876
Cos(n) meLhod, 52
counLer variables
global, 40, 90-9
in loops, 82
oLher uses or, 86
overview, 88
crashes, program. See run-Lime
errors
creaLing
olders, 72
modules, 248-5
sLandard-sized objecLs, 88
Loolbars wiLh 1oolSLrip conLrol,
07-0
creaLing lines, shapes on, 890
CSLr (converL Lo sLring) uncLion, 57
cusLomizing
color seLLings, wiLh ProperLies
window, 4
compiler seLLings in lDF, 29-80
inheriLed orms, 42
Web pages, 509-
D
daLa access in Web orms
environmenL, 488
daLa grid view objecLs
adding second, 482-84, 489
changing column widLh, 489
creaLing, 47-74
creaLing color scheme or
rows, 489
creaLing Lo display daLabase
Lables, 488
hiding column headers in, 489
prevenLing ediLing or changing
o daLa, 489
previewing daLa bound Lo,
474-75, 488
removing columns rom, 476, 488
seLLing properLies, 479-82
sorLing daLa in, 478-79
daLa navigaLor, 448
choosing daLabase model, 445
creaLing daLaseLs in, 448
sLarLing, 445
DaLa Sources window
creaLing daLabase objecLs on
orms wiLh, 454-58
overview, 452
daLa Lypes
assigning, 25
undamenLal, 85-4
inerence o, by visual 8asic,
26-27
signed, 85
speciying in uncLion
procedures, 257
sLring, 85
unsigned, 85
DaLa 1ypes program, 87-4
daLabase objecLs
creaLing by using DaLa Sources
window, 454-58
daLabases
choosing ormaL, 446
copying local, 449
displaying inormaLion on Web
pages, 52-8
esLablishing connecLion Lo, 466,
468-7
FaculLy.mdb sample, 444
sLored in daLaseLs, 466
ormaLLing daLa on orms, 466
overview, 44
relaLional, 448
updaLing, 485-87, 489
DaLa8indings properLy,
overview, 459
daLacenLric applicaLions, 489
DaLaCridview conLrol
overview, 467
scrolling, resizing, and sorLing
wiLh, 478-79
DaLaCridview Lasks lisL, 476
DaLaCridview 1asks lisL, 474
DaLaseL Designer, 45-52
daLaseLs
binding conLrols Lo, 458-59
creaLing, 466
displaying inormaLion on orms,
458-55
Wizard, 445, 452
inormaLion, displaying during
debugging sessions, 226
Lyped vs unLyped, 45
visualizers, 220
DaLa1ips, 25-6
DaLe daLa Lype, 86
daLe, seLLing sysLem,
in Windows, 05
DaLeSLring properLy, 04-05, 07
DaLe1imePicker conLrol, 78-78
DayOear properLy, 75
visual SLudio, 60
Debug 1esL program
debugging, 22-4
older locaLion, 28
removing breakpoinLs, 224-25
Debug Loolbar, displaying, 225
debugging mode. See clsc LesLing
opening LexL visualizers in,
220-2
sLarLing, 24
sLopping, 226
using, 22-7
Debugging NoL Fnabled dialog box,
505-06
debugging sessions
displaying H1ML, XML, daLaseL
inormaLion during, 226
sLopping, 226
Decimal daLa Lype, 86, 82
decision sLrucLures. See clsc l . . . 1hen
decision sLrucLures, SelecL Case
decision sLrucLures
declaraLion sLaLemenLs, array
inormaLion included in, Lable,
282, 274
declared variables, hiding in
classes, 42
declaring collecLions as variables,
804-05
declaring variables
aL Lop o orm's code, 89
by inerence, 26-27
impliciLly, 26-27
error handIers 533
in Dim sLaLemenL, 25-26
in projecLs wiLh more Lhan one
orm, 40
objecL, Lo use classes, 48
public, in modules, 258-55
required compiler seLLings or, 82
while assigning values, 90, 207
DecrypL sLring variable, 844, 847
DeaulL.aspx, 497
deensive programming
Lechniques, 248
delayed saving eaLure, 8, 40
deleLing
breakpoinLs, 226
menu iLems, 02
objecLs, 48, 65
Loolbar buLLons, 0
deploying
applicaLions, 62-68, 65
Web siLes, 508
descripLive label properLies,
seLLing, 48-49
Design mode
moving objecLs in, 42
Source mode, swiLching
beLween, 522
Design view, adding LexL in,
499-500
Designer. See clsc Menu Designer,
view Designer, Web Page
Designer
changing sLarLup orms using,
87-78
DaLaseL, 45-52
displaying, 0-
locaLion in lDF, 8
scroll bars in, 40
Source Lab, 500
swiLching Lo, 0
view buLLon, 54
Window Forms. See Windows
Forms Designer
DeskLop 8ounds program
older locaLion, 868
seLLing DeskLop8ounds properLy,
862-64
DeskLop8ounds properLy, 859,
862-64
deLecLing mouse evenLs, 77-78
developmenL environmenL. See lDF
dialog box conLrols, 0-, 20
dialog boxes
Add New lLem, 248
adding PrinL Preview and Page
SeLup, 480-88
Code SnippeLs Manager, 207
Color, 8-4
displaying, 20
displaying aLer creaLion, 2
displaying ouLpuL, 57
displaying prinLing in
programs, 487
FdiL Columns, 476
geLLing inpuL by using, 56
inheriLing, 894-97
inpuL uncLion o, 78
lnpuL Mask, 64-65, 458
message, 88
New ProjecL, 88-89
nonsLandard, 7
Open. See Open dialog box
Open ProjecL, 5-6
opening, 2
opening orms in. See ShowDialog
meLhod
Page SeLup, 480-88
ProjecL LocaLion, 72
SelecL Resource, 49
DialogResulL properLy, 858-59
DigiLal Clock program
creaLing, 97-99
older locaLion, 99
running, 99
Dim keyword, 275
Dim sLaLemenL, 24-26, 56, 208
dimensioning, 286-87
Disc Drive Frror projecL
older locaLion, 280
loading, 280-82
disc drive errors,
wriLing handlers, 288
Disc Drive Handler program
older locaLion, 240
Lracking run-Lime errors wiLh
variables, 240-42
Discard buLLon, closing wiLhouL
saving, 252
disconnecLed daLa sources, 450
division by zero, 45, 7
division operaLor (/), 48, 47
division, inLeger, 47
Do loops
avoiding endless, 98-96, 207
converLing LemperaLures by using
(Celsius Conversion program
example), 98-96
described, 92
synLax, 92-98
UnLil keyword in, 96, 208
Dock properLy, 8, 868-69, 874
docking
objecLs, 868-7, 874
Lool windows, 7, 9-2, 84
windows, 8
docking guides, 7-8
documenLs
mulLipage, prinLing, 487
Labbed. See Labbed documenLs
Double daLa Lype, 86
double-clicking
names o properLies, 5
Lo creaLe sLandard-sized
objecLs, 88
Draw Shapes program
creaLing lines, recLangles, and
ellipse shapes, 878-80
older locaLion, 879
Drawlmage meLhod, 49
DrawLine meLhod, example, 877
drop-down lisL boxes, 85, 95
Dynamic Array program
older locaLion, 286
LesLing, 286-87
using, Lo hold LemperaLures,
284-86
dynamic arrays. See clsc arrays
creaLing, 288-84, 295
recording LemperaLures in,
284-87

FdiL Columns dialog box, 476,


479-80
ediLing
evenL procedures, 2-8
menu evenL procedures, 02-05
ellipsis ( . . . ), in menu commands, 00
ellipsis buLLons, 5
Flse l keyword, 62-68
Flse keyword, 62-68
FncrypL 1exL program
examining Lhe code o, 888
older locaLion, 887
encrypLion, proLecLing LexL wiLh,
886-40, 844, 847
Fnd buLLon, wriLing code or, 52-54
Fnd l keyword, 62-68
Fnd keyword, 58
Fnd SelecL keywords, 72
FndoSLream properLy, 87, 845
FndsWiLh meLhod, 882
environmenL seLLings,
changing, 29-80
equal Lo or assignmenL operaLor (=),
7, 6, 88
error handlers. See clsc errors
deensive programming
Lechniques vs, 248
534 errors
or prinLing, 422
nesLed 1ry . . . CaLch code blocks
in, 242
overview, 228
speciying reLry periods, 240-42
sLrucLured, 248
sLrucLured, uncLion o, 227
LesLing (Disc Drive Frror
projecL), 284
when Lo use, 228
wriLing disc drive, 288
errors. See clsc error handlers
creaLing, in programs, 245
disc drive, 229
generaLing or LesLing purposes,
240-42
indicaLors or (jagged)***, 2
logic, 20
paLh, 229
run-Lime, 49-52, 20, 244
synLax, 20
handlers, 245
Lypes o problems addressed by
handlers, Lable, 228-29
evenL handlers
calling prinLing, 487
creaLing prinLing, 487
condiLions in, 245
wriLing, 77-78
evenL procedures
consLanLs in, 42-48
displaying addiLional orms by
using, 856-57
ediLing, 2-8
menu, ediLing, 02-05
wriLing color buLLon, 8-4
wriLing, or objecLs on Web
pages, 522
wriLing, or Web page conLrols,
504-05, 509-
evenL-driven programming, 59-60
evenLs
in visual 8asic, 60
mouse, deLecLing, 77-78
FxcepLion objecLs
combining CaLch sLaLemenLs
wiLh, 289
overview, 286
Lypes o, Lable, 286-87
whaL Lo use, 287
excepLions. See run-Lime errors
.exe)
and Windows applicaLions, 6
creaLing, 60-6, 65
overview, 60
execuLing
one line o code, 225
sLaLemenLs more Lhan
once, 8
Limes, 207
sLaLemenLs unLil condiLions
meL, 207
FxiL For sLaLemenL, 9, 207
FxiL 1ry sLaLemenL, 248-44
Fxp(n) meLhod, 52
expanding objecLs aL run Lime,
886-88
Fxplorer Form LemplaLe, 858
exponenLial operaLor (), 48,
47, 49
expressions
adding Lo WaLch window, 226
8oolean, 68
condiLional, 6-68, 92
examining in Code FdiLor, 225
l
F Help key, 26-27
F8 key, alLernaLive Lo SLep lnLo
buLLon, 29
FaculLy.mdb sample daLabase
older locaLion, 447
overview, 444
eedback, visual. See progress bar
. See clsc columns
backing, 408
displaying mulLiple daLabase,
454-56
File menu, Save All command, 56
File.SaveAll command, 224
code-behind, 468
deleLing orm, 854
encrypLing, 886
orms, saving, 65
opening using For . . . NexL loops,
86-88
renaming orm, 854
sequenLial, 87
swiLching beLween, 22-28, 84
Lrashing, 886
wiLh, 487
Fill Array buLLon, 29-92
FilLer lisL, adding iLems Lo, 8
FilLer properLy, 2
daLa, by wriLing SL
sLaLemenLs, 466
daLabase inormaLion sLored in
daLaseLs, 466
inpuL, 65-66
Finally clause
displaying message boxes
wiLh, 285
wiLh 1ry . . . CaLch code blocks,
284-85
Fixed Array program
creaLing, 279-82
older locaLion, 282
running, 288
LesLing, 282-88
. See clsc arrays
declaring, synLax iLems, 275
recording LemperaLures in,
279-88
ocus, in LexL boxes, 44
Folder8rowserDialog conLrol, 0
olders, creaLing, 72-78
FonL properLy, 5, 47-48
FonLDialog conLrol, 0
For Fach . . . NexL loops
changing 1exL properLies wiLh
(ConLrols CollecLion program
example), 299-80
Name properLy in, 802-04
reerencing objecLs in collecLions,
298-99
For keyword, 82
For Loop lcon program
older locaLion, 90
loading, 86-89
running, 88-89
For Loop program
displaying LexL by using
For . . . NexL loop, 87, 88-85
older locaLion, 84
LesLing, 84-85
For Loops, complex, 85-86
For . . . NexL loops
complex, 85-86
described, 82
displaying LexL by using, 88-85
exiLing, 207
in arrays, 28-82
90-9
synLax, 82
wriLing, 8-82
ForeColor properLy (ProperLies
window), 6, 49, 8, 90-9
Form lnheriLance program,
894-99
orm variables, public vs., 255
If. . .1hen decson structures 535
Form_Load procedure, 68, 87
FormaL uncLion, Lo display
commas, 87
ormaLLing
daLabase daLa on orms, 466
.
See clsc masks
program sLaLemenLs, 58
LexL, 5
FormaLLing Loolbars, 499-500
orms
adding navigaLion conLrols Lo, 466
adding Lo programs, 85-56, 878
anchoring objecLs on, 868-7, 874
changing Lransparency o, 888-90
conLrols, adding aL run Lime,
864-67, 874
creaLing bound objecLs capable o
displaying daLaseL daLa on, 466
creaLing wiLh code, seLLing
properLies, 874
displaying addiLional, using evenL
procedures, 856-57
docking objecLs on, 868-7
ormaLLing daLabase inormaLion
on, 466
hidden, opening, 878
inheriLed, cusLomizing,
897-99, 42
minimizing, maximizing, and
resLoring, 864, 874
opening, 0, 857
posiLioning on Windows deskLop,
859-64
public variables vs. variables
in, 255
sLarLup, 87-74
Lransparency, changing, 89
uses or, 852
variables in projecLs wiLh
mulLiple, 40
ormulas
creaLing, 57
parenLheses in, 56-57
rames, creaLing, 8
Framework. See .NF1 Framework
Framework MaLh program, 58-55
FromFile meLhod, 88, 87, 87, 287
ronL ends, daLabase, 489
FullOpen properLy, 4
FuncLion procedures
calling, 258, 27
overview, 256
synLax iLems in, 257-58
uncLion sLaLemenLs, 257
uncLions
lnpuL8ox, 8-82
L8ound, U8ound, 280
Msg8ox, 88
perorming calculaLions wiLh
(win raLe example), 258-6
public, creaLing, 270
synLax iLems, using, 257-58
wiLh more Lhan one
argumenL, 88
G
CDl- graphics services, changing
orm Lransparency, 876, 888
general-purpose procedures, 256
global counLer variables, 40,
90-9
graphics
prinLing, 48, 487
resizing, 49
Craphics lnLerchange FormaL (.gi).
See .
Craphics.Drawlmage
meLhod, 48, 487
Craphics.DrawSLring meLhod,
420-28, 487
Craphics.MeasureSLring
meLhod, 424
greaLer Lhan operaLor (>), 6, 88
greaLer Lhan or equal Lo operaLor
(>=), 6, 88
CridColor properLy, 886
grids
aligning objecLs Lo, 42
cell color, changing, 480-8
gridline color, changing, 48, 489
hidden by deaulL, 42
reversing direcLion o
sorL, 489
snapline, 42
sorLing records in, 489
Cridview conLrol, 52-5
group boxes, properLy seLLings,
Lable o, 88
Croup8ox conLrol, 8-82
guide diamonds, 7
H
HeighL properLy, 886
Hello World program
creaLing, 68
older locaLion, 72
overview, 67
running, 72-78
accessing, 28, 84
cusLomizing, 84
F key, 26-27
managing seLLings, 25-26
MSDN, 27-28
navigaLing, 28
Lopic locaLions in visual
SLudio 200, 28
Help Library Manager, 25-26
hidden orms, opening by using
program code, 878
hiding
declared variables in classes, 42
orms, 878
shorLcuL keys, 8
Lool windows, 2, 84
Hour (daLe) meLhod,
descripLion, 07
H1ML
conLrols described, 498
conLrols overview, 494
creaLing pages, 522
displaying during debugging
sessions, 25
Lags, 50
viewing or Web pages, 500, 522
visualizers, 220
Hungarian Naming
ConvenLion, 80
HyperLink conLrol, 56, 522
hyperlinks, adding, 56-7
l
l8M exLended characLer seL, 880
icons
pin, 25
shorLcuL, 6
lDF
changing compiler seLLings or,
29-80, 84
componenL Lray, 98
Wizard, 445
NavigaLor, 22-28
overview, 4
running commands rom
Command Window in, 226
running visual 8asic rom, 58
Loolbars available in, 8
l . . . 1hen decision sLrucLures
condiLional expressions using,
6-62
in Checkbox conLrols, 80
logic errors in, 2
536 Image property
shorL-circuiLing, 69-7, 79
synLax, 79
lmage properLy, 49
images, seLLing background, 89
immed command, using Lo swiLch Lo
lmmediaLe window, 228
lmmediaLe window
modiying variables wiLh, 222-28
opening, 226
swiLching Lo Command window,
228, 226
lmporL and FxporL SeLLings
command (1ools menu),
22, 29-80
lmporLs sLaLemenL
maLh meLhods, 52
reerencing class libraries, 54-55,
57, 248
index posiLion, o objecLs, 298
inheriLance, 90, 898-94
lnheriLance Picker dialog box,
894, 896
inheriLed orms, cusLomizing,
897-99, 42
inheriLing
base classes in new classes, 48
dialog boxes, 894-97
orms' inLeraces and
uncLionaliLies, 42
lnheriLs keyword, 48
lnheriLs sLaLemenL, 400, 408-
lnpuL 8ox program, 8-82
lnpuL ConLrols program, 78-79
lnpuL Mask dialog box,
64-65, 458
inpuL, conLrolling user, 64-67
lnpuL8ox uncLion, 8-82
lnserL SnippeL command,
208-08, 86
lnserL SLandard lLems buLLon, 08
inserLing code snippeLs, 208-08
inserLion poinL, in LexL boxes, 44
lnL uncLion, 57
lnLeger daLa Lype, 86-87, 82
inLeger division (\), 47-48
lnLellisense, 58, 7
lnLerneL addresses, Lracking by
using new collecLions, 805-06
lnLerneL Fxplorer
disabling securiLy warnings, 507
LiLle bar, 59-22
inLraneL securiLy seLLings, 507
ls keyword, 78
J
JoinL PhoLographic FxperLs Croup
ormaL. See .
K
keys, primary, 470
keywords. See clsc
keywords
in variable names, 80
lnLellisense and, 58
L
Label conLrol
adding objecLs, 02-08
creaLing, 865-66
using wiLh Web pages, 502
labels
adding, 48-44, 02-08
changing properLy seLLings, 6
descripLive properLies, seLLing,
48-49
number properLies, seLLing,
47-48
Language-lnLegraLed uery (LlN),
442, 462
L8ound uncLion, 280
LeL properLy, 880
less Lhan operaLor (<), 6, 88
less Lhan or equal Lo operaLor (<_),
6, 88
leLLers, converLing Lo numbers, 840
lighLweighL views, 27
line conLinuaLion characLer (_),
75, 87
lines
creaLing on orms, 890
enLering, 04
processing in LexL boxes, 882
linking, Lo Web pages, 522
LinkLabel conLrol (1oolbox), 9
links, changing color o, 92-98
LinkvisiLed properLy, 98
LlN (Language-lnLegraLed uery),
442, 462
LisL 8ox conLrol, 74
LisL 8ox program
older locaLion, 88
running, 88
lisL boxes
adding iLems Lo, 85, 95
creaLing, 85-87, 95
drop-down, creaLing, 85
in visual SLudio, 7
lnserL SnippeL, 204
LisL8ox conLrol, 84
LocaLion properLy
described, 880
overview, 88-82
LocaLion LexL box, 40
logic errors
idenLiying, 2
logical operaLors, 67-69
Long daLa Lype, 86-87, 82
loops
avoiding endless, 98
creaLing, 8-82
creaLing complex, 85-86
seLLing run Lime periods or, 208
lower and upper bounds, speciying
in public arrays, 295
Lucky Seven game program
adding addiLional orms,
852-56
adding Help orms, 852-56
closing, 64
closing wiLhouL saving, 252
creaLing, 88-44
older locaLion, 59
properLies o, in Lable, 5
reloading, 68-64
running, 58-59, 857-58
user inLerace conLenLs, 88
M
macros, compaLibiliLy beLween
Word versions, 809-0, 82
manipulaLion, sLring, 826-27
Mask properLy, 64
Masked1exL8ox conLrol, 64,
458-60
masks
ormaLLing daLabase inormaLion
wiLh, 458-6
maLhemaLical (or ariLhmeLic)
operaLors, 46, 48
maLhemaLical (or ariLhmeLic)
operaLors, 50, 47
maximizing orms aL run Lime, 874
MaximumSize properLy, 864
MaxLengLh properLy, 85
Me keyword, 855
Me objecL, 878
MeasureSLring meLhod, 424
memory managemenL, 25, 276
menu bar, 8
Menu Designer
adding access keys, 98-00
changing order o commands, 02
objects 537
menu iLems. See clsc menus
adding access keys, 00
adding access keys Lo, 9
adding Lo menu commands,
98-99
changing order o, 02, 9
creaLing, 9
deleLing, 02
guidelines or, 00
naming, 04
shorLcuL keys, assigning, 02,
7-9
Menu program
older locaLion, 05, 4
menus and dialog boxes in, 4
running, 05-06, 5-7
menus. See clsc menu iLems
evenL procedures, ediLing, 02-05
running, 88
MenuSLrip conLrol (1oolbox)
displaying objecLs, 98
overview, 97
shorLcuL keys, assigning, 7-8
message boxes. See clsc dialog
boxes
creaLing, 74-75
displaying, 285
displaying inormaLion on
orms, 88
Message8ox class, 84
meLhods
calling, 57
creaLing in classes, 405-06, 42
Craphics.DrawSLring, 420-28
maLh, 52
PrinL, 48, 487
ShowDialog, 2
MicrosoL Access. See Access
MicrosoL lnLellisense, 58, 7
MicrosoL OLF D8, 448
MicrosoL. JeL.OLFD8 error
message, 444
minimizing orms aL run Lime, 874
MinimumSize properLy, 864
MinuLe (daLe) meLhod,
descripLion, 07
misLakes, idenLiying by jagged
lines, 54-55
mnuOpenlLem Click evenL
procedure, 848-44
mnuSaveAslLem_Click evenL
procedure, 888
Mod (remainder division operaLor),
48, 48
modal orms, 857
modeless orms, 852
modules
adding, 252-55
adding exisLing, 270
creaLing, 248-5, 270
overview, 248
removing, 270
removing rom projecLs, 25
renaming, 250, 270
saving, 250-5
MonLh (daLe) meLhod,
descripLion, 07
mouse evenLs, deLecLing, 77-78
moving
objecLs, 42, 64
objecLs in ConLrol
collecLions, 8
objecLs on orms, 880-82
Lool windows, 7-9, 84
Loolbar buLLons, 0
Moving lcon program
animaLing sun icon, 882-85
older locaLion, 885
running, 885-86
MSDN Online Help, 27-28
MSDN, swiLching views in, 27
Msg8ox uncLion
creaLing message boxes, 74-75
displaying conLenLs o variables,
88-85
Xor (logical operaLor)
encrypLion, 840
MulLiline properLy, 88-86
mulLiline LexL boxes, size limiL, 85
mulLiplicaLion operaLor (*),
48, 47
mulLi-LargeLing eaLure, 89
Music 1rivia program
closing, 8
opening, 5-7
running, -8
My namespace
accessing orms using, 856
overview, 84-6
My.CompuLer.FileSysLem objecL
ReadAll1exL meLhod, 85-2
WriLeAll1exL meLhod, 82-28
N
Name properLy, 74-75, 802-04
namespaces, 90
naming
classes, 408
convenLions or variables, 80
daLa, 24
menu iLems, 04
navigaLion conLrols
adding second, 484
adding Lo orms, 466
navigaLion Loolbar, 456-57
New ConnecLion buLLon, 446
New ProjecL command (File Menu)
and Windows lnsLaller, 68
console applicaLions, 878
New ProjecL dialog box, 88-89, 68
New ProjecL link (SLarL Page), 88
New Web SiLe command, 496
NexL keyword, 82, 84
non-modal orms, 852, 857
nonsLandard dialog boxes, 7
NoL (logical operaLor), 67
noL equal Lo operaLor (<>), 6, 88
Now properLy, descripLion, 07
number compuLaLion, random, 57
number sequences, creaLing in
loops, 85-89
numbers, converLing leLLers Lo, 840
numeric values, encrypLing, 840
O
ObjecL daLa Lype, 86
objecL variables
declaring Lo use classes, 42
seLLing properLies or, 48
objecL-orienLed programming
(OOP), 898
objecLs. See clsc
adding, 40-42
aligning Lo hidden, 42
anchoring, 868-7, 874
animaLing, 89
changing properLy seLLings,
4-6, 47
choosing daLabase, 449-50,
469-7
conLrol, 865-66
creaLing based on new classes,
407-08
creaLing sLandard-sized, by
double-clicking, 88
deleLing, 48, 65
docking, 868-7, 874
evenLs supporLed by
visual 8asic, 60
expanding, shrinking aL
run Lime, 89
in collecLions, 297-98
index posiLion o, 298
moving, 64, 8, 89
mulLiline LexL box,
size limiLs o, 85
processing, in collecLions, 8
538
reerencing in collecLions, 298-99
renaming, 79
renaming on Web pages, 522
resizing, 42, 65
selecLing, or reuse. See
lnheriLance Picker dialog box
special LreaLmenL or, in
collecLions, 8
sLarLup, 87-74
swiLching beLween, 47
LexL box, 88
Limer, 200, 208, 882-85
wriLing evenL procedures or on
Web pages, 522
8asic or ApplicaLions
collecLions in, 809
OpaciLy properLy, 888-9
Open buLLon, ediLing evenL
procedures, 2-8
Open dialog box
displaying, 8, 84-5, 845
displaying and selecLing
Open FncrypLed File command, 888
Open ProjecL dialog box, 5-6
Open Web SiLe command, 498
OpenFileDialog conLrol
adding, , 845
managing prinL requesLs wiLh,
424-28
purpose, 0
opening
Code FdiLor, 52, 65
dialog boxes, 2-8
. . . NexL loops,
86-88, 90-9
orms, 0
lmmediaLe window, 226
projecLs, 4-6, 84
projecLs, LroubleshooLing, 7
WaLch windows, 28-9
Web browser, in visual SLudio,
28-24
operaLors
advanced, 47-50
ariLhmeLic (or maLhemaLical),
48, 47
comparison (or relaLional), 6
comparison (or relaLional)
operaLors, 880-8
logical, 67-69
order o precedence, 55-57, 67
shorLcuL, 47
OpLion Compare seLLing, 88
OpLion FxpliciL O sLaLemenL,
26-27
OpLion FxpliciL seLLing, 82
OpLion lner seLLing, 88, 26-27
OpLion SLricL seLLing, 82
OpLions command
(1ools menu), 40
Or (logical operaLor), 67
order o precedence, 55-57, 67
OrFlse operaLor, 69-7
origin, coordinaLe sysLem, 876
OLher Windows menu, 8
OLher Windows submenu, 28
P
Page SeLup dialog box
adding wiLh PageSeLupDialog
conLrol, 480-88
display page seLup
dialog box, 482
LesLing, 484-87
PageSeLupDialog conLrol
adding, 480-88
purpose,
PainL evenL procedure, creaLing
shapes wiLh, 878-80
parenLheses
in Sub procedures, 262
use o, in ormulas, 56-57
PasswordChar properLy, 69, 200
passwords, seLLing Lime limiL or,
200-08
paLh errors, 229
paLh names, absoluLe
and relaLive, 89
Pen objecL, 877
Person Class program
building, 40-02
creaLing classes, 402-08
older locaLion, 407, 40
inheriLing base classes, 408-0
LesLing, 40-
picLure boxes
adding Lo programs,
properLy seLLings, Lable o, 88
seLLing properLies, 49-5
PicLure8ox conLrol, 44, 88
picLures, adding, 44.
See clsc graphics
pin icons, 25
pipe symbol (|), 8
pixels, coordinaLe sysLem, 876
PmL uncLion, overview, 504
PorLable NeLwork Craphics (.png).
See .
posiLioning sLarLup orms on
Windows deskLop, 874
Preserve keyword, 287
Preview DaLa dialog box, 474-75
previewing daLa bound Lo daLa grid
view objecLs, 474-75
primary keys, 470
PrinL Dialogs program
older locaLion, 488
LesLing Page SeLup and PrinL
Preview eaLures, 484-86
PrinL File program
adding PrinL Preview and Page
SeLup, 48-88
building, 424-28
older locaLion, 428
running, 428-80
PrinL Craphics program
older locaLion, 49
running, 49-20
PrinL meLhod, 48, 487
PrinL Preview dialog box, adding
wiLh PrinLPreviewDialog
conLrol, 480-88
PrinL Preview, LesLing, 484-87
PrinL 1exL program
older locaLion, 428
running, 428
PrinLDialog conLrol
managing prinL requesLs wiLh,
424-28
purpose,
PrinLDocumenL class, 45-20
PrinLDocumenL conLrol, 46-9
PrinLDocumenL objecL, 487
prinLing
adding code Lo display PrinL
dialog box, 427-28
creaLing evenL handler, 487
displaying dialog boxes, 487
evenL handlers, calling, 487
graphics rom prinLing evenL
handlers, 487
managing requesLs wiLh conLrols,
424-28, 480-88
mulLipage documenLs, 487
preparing projecLs or, 487
seL deaulL seLLings, 427
LexL rom prinLing evenL
handlers, 487
LexL rom LexL box objecLs, 420
LexL using Craphics.DrawSLring
meLhod, 420-28
using error handlers, 422
PrinLPage, 424
reIatonaI (or comparson) operators 539
PrinLPreviewDialog conLrol
adding, 480-88
purpose,
PrivaLe keyword, 408, 42
procedure sLaLemenLs, in Sub
procedures, 262
procedures. See clsc Sub procedures
click, 56-58
creaLing, 255-56
FuncLion, calling, 258, 27
general-purpose, 256
overview, 58
sharing, 247-48
Process class, 98
Process.SLarL meLhod,
eaLure o, 98
processing elemenLs in arrays, 295
program code
auLomaLic addiLions by
visual 8asic, 55
commenLs in, 86
error messages, 55
execuLing one line o, 225
idenLiying elemenLs by color, 55
opening hidden orms wiLh, 878
wriLing, 65
program crashes, 227
program sLaLemenLs. See clsc code
8asic MaLh program, 45-47
enLering in Code FdiLor, 52-56
execuLing, 208
overview, 58
procedures and, 58
sequencing numbers
by using, 207
seLLing properLies using, 57
synLax in, 58
program sLyle, 54
programming
deensive Lechniques, 248
evenL-driven, 59-60
sLeps or new projecLs, 88
programming languages available
in visual SLudio, 4, 88
programs. See clsc
programs
adding conLrols Lo, 0-
adding new orms Lo, 878
adding Loolbars Lo, 09, 9
closing, 8
closing wiLhouL saving, 25-52
compiling, 84
DaLa 1ypes, 87-4
errors in, creaLing, 245
reloading, 68-64
running, -8, 258-6
saving, 56, 65
skeleLon, 27
sLopping, 72
using sLandard dialog
boxes in, 20
visual 8asic, creaLing wiLh no user
inLerace, 874
progress bar, 290-9, 296
ProjecL LocaLion dialog box, 72
projecL seLLings, checking, 8-88
projecLs. See clsc
creaLing, 40-44, 68
opening, 4-6, 84
opening, LroubleshooLing, 7
programming sLeps or
new, 88
reloading, 65
saving, 72-78
wiLh more Lhan one orm, 40
ProjecLs olders, 6
prompLing user or inormaLion,
8-82
properLies. See clsc properLy
seLLings
adding Lo WaLch window, 226
animaLing objecLs by using,
880-8
8oolean, 5
changing aL run Lime, 7, 95
creaLing, 404-05
creaLing in classes, 42
descripLive label, seLLing, 48-49
or moving objecLs, 880
or picLure boxes, seLLing, 49-5
names o, double-clicking, 5
number label, seLLing, 47-48
overview, 8
seLLing, 84, 45-47
seLLing aL design Lime, 8
seLLing or daLa grid view objecLs,
479-82
seLLing or objecL variables, 48
seLLing, or Web pages, 508
Lables o, reading, 5
viewing, 8
ProperLies window
caLegories in, 4-5
cusLomizing color seLLings
wiLh, 4
displaying, 45
locaLion in lDF, 8
ObjecL lisL, 8
organizaLion o, 4, 46
overview, 8-6
properLy seLLings
changing, 4-6, 45
proLecLing LexL wiLh basic
encrypLion, 886-40
providers, 448
public arrays, 295. See clsc arrays
public uncLions, creaLing, 270
Public keyword, 42, 275
public Sub procedures, 27
public variables
creaLing, 270
declaring in modules, 40,
25, 258-55
orm variables vs., 255
Publish command, 62, 65
Q
uery 8uilder, creaLing SL
sLaLemenLs wiLh, 46-66
uick NoLe program
examining code in, 826
older locaLion, 828
running, 828-25
quoLaLion marks, wiLh LexL
sLrings, 28
k
Radio 8uLLon program
creaLing, 82-88
older locaLion, 84
running, 84
radio buLLons
creaLing, 82-88
Radio8uLLon conLrol, 8-82
random number compuLaLion, 57
Randomize uncLion, 59
Randomize sLaLemenL, 68-64
ReadAll1exL meLhod, 85-2
ReadLine meLhod, 87, 845
ReadOnly properLy, 486-87
Rebuild command, 6, 65
ormaL, 79
records, in daLabases, 442
ReDim Preserve sLaLemenL,
287-88
ReDim sLaLemenL, dimensioning
wiLh variables, 284
redimensioning
arrays, 295
or Lhree-dimensional
arrays, 288
relaLional (or comparison)
operaLors, 6, 880-8
540 reIatonaI databases
relaLional daLabases, 448
relaLive paLh names, 89
in visual SLudio, 60-6
reloading programs, 68-64
reloading projecLs, 68-65
remainder division operaLor (Mod),
48, 48
removing
breakpoinLs, 224-26
columns, 476, 488
renaming
modules, 250, 270
objecLs, 79
objecLs on Web pages, 522
Replace meLhod, 882
resizing
buLLon objecLs, 42
orms, 40
graphics, 49
objecLs, 42, 65
Lool windows, 9, 84
resLoring
orms aL run Lime, 874
hidden windows, 7
ReLurn sLaLemenLs, 257
reversing, order o an
array, 295
Rich1exL8ox conLrol (1oolbox)
managing prinL requesLs wiLh,
424-28
spacing and ormaLLing
opLions o, 85
Rich1exL8ox objecL, loading LexL
Rnd uncLion, 57
rows
changing color o, 48, 489
in daLa Lables, 442
running
programs, -8
visual 8asic rom lDF, 58
WebLink program, 94-95
Windows applicaLions wiLh
Windows Fxplorer, 6
run-Lime errors
correcLion o, 5
deensive programming
Lechniques, 248
deLecLing, processing, 244
prevenLing, 7
program crashes, 227
solving, 2
LesLing or mulLiple, 287-89
Lhrowing, 289
variables Lo Lrack, 240-42
S
Save All buLLon (SLandard Loolbar),
65, 72
Save All command (File menu),
56, 65
Save As dialog box,
displaying, 845
Save DaLa buLLon, uncLion
o, 485
Save New ProjecLs When CreaLed
check box, 8
SaveFileDialog conLrol, 0
saving
delayed, 8, 40
programming environmenL
seLLings, 22
programs, 56, 65
projecLs, 8
user inpuL, 80-82
S8yLe daLa Lype, 86
scope
o arrays, 274
o variables, 28, 89-90
scroll bars
in lisL boxes, 84
in LexL boxes, 88
in Lhe Designer, 40
Scroll8ars properLy, 88
scrolling, asLer, 407
Search CriLeria 8uilder dialog box,
462-68
Second (daLe) meLhod,
descripLion, 07
SelecL Case decision sLrucLures
comparison (or relaLional)
operaLors wiLh, 78-77
evenL procedures, 40
synLax, 7-72, 79
SelecL Case keywords, 72
SelecL Case program
adding mouse evenL handler,
77-78
older locaLion, 76
processing inpuLs rom lisL box,
78-77
running, 76-77
SelecL Resource dialog box, 49
SelecLedlndex properLy,
85-86, 76
SelecLedlndexChanged evenL
procedure, 86. See clsc evenL
procedures
server conLrols
adding Lo Web pages, 50-02
described, 498
overview, 498
servers, 495
SeL8ounds meLhod, 880
seLLing
breakpoinLs, 225
properLies, 84
Lime limiLs, 200-08
seLLings
deaulL prinL seLLings, 427
saving programming
environmenL, 22
shapes
creaLing lines, recLangles, and
ellipses, 878-80
creaLing on orms, 890
sharing, variables and procedures,
247-48
ShellSorL Sub procedures, 882,
885-86
ShorL daLa Lype, 86-87
shorLcuL icons, creaLing, 6
shorLcuL keys
assigning Lo menu iLems, 9
assigning Lo menus, 7-8
hiding, 8
LesLing, 8-9
ShorLcuLKeys properLy, 7, 9
Show meLhod
swiLching beLween orms, 878
Lo open orms, 857
ShowDialog meLhod
displaying Open dialog box, 8
opening dialog boxes, 2-8
swiLching beLween orms, 878
ShowHelp properLy, 4
shrinking objecLs aL run Lime, 89
Sign(n) meLhod, 52
Simonyi, Charles, 80
simulLaneous declaring/ assigning
variables, 90
Sin(n) meLhod, 52
Single daLa Lype, 86
Size sLrucLure, 864
SizeMode properLy (8ehavior
caLegory), 49
sizing
sLarLup orms on deskLop, 874
windows, 9
skeleLon programs, 27
smarL Lag buLLons, 50, 07-08
snapline grids, 42
snippeLs. See code snippeLs
SolidColorOnly properLy, 4
text 54l
SoluLion Fxplorer
displaying, 0
locaLion in lDF, 8
building in, 498
SoluLion Name LexL box, 40
soluLions
always show, 7, 8
overview, 7
SorL Array buLLon, 292-98
SorL 1exL program
examining code in, 884-86
older locaLion, 882
running, 882-84
sorLing
daLa in daLa grid view objecLs,
478-79
records in grids, 489
reversing direcLion o, 489
sLrings, 88
sLrings in LexL boxes, 88-86
LexL, 829-80
Source mode, Design mode,
swiLching beLween, 522
Source Lab, 50
Spin buLLon, wriLing code or, 54-56
SpliL meLhod, 882, 846
SL Server, 448
SL sLaLemenLs
creaLing wiLh uery 8uilder,
462-66
overview, 46-62
SqrL(n) meLhod, 52
square rooLs, calculaLion o, 58-55
SLandard Loolbar
SLarL Debugging command, 58
SLarL Debugging command, , 58
SLarL meLhod, 98-94
SLarL Page
New ProjecL link, 88
opening projecLs rom, 4
sLarLing visual SLudio, 4-5, 84
SLarLPosiLion properLy, 860-62, 874
sLaLemenL synLax, 58, 24
sLaLemenLs. See clsc
execuLing, 208
uncLion, 257
in l . . . 1hen decision sLrucLure,
6-62
sequencing numbers
by using, 207
SLep lnLo buLLon, 26
SLep keyword, 207
SLop Debugging (Debug Loolbar),
closing program wiLh, 72
SLreamReader class
adding LexL Lo addiLional orm,
855-56
overview, 86-7
SLreamWriLer class, 822, 846
SLring class
elemenLs and visual 8asic
equivalenLs, 827-29
lisL o elemenLs in, 846
processing sLrings in, 826-29
sLring concaLenaLion operaLor (&),
75, 47, 49, 84
SLring daLa Lype, 86
sLring variables, 25
SLring.ConcaL meLhod, 827
sLrings
comparing, 88, 829-8
connecLion, 446
manipulaLing and processing,
826-27
sorLing, 88
sLrucLured error handlers,
2, 227, 248
Sub procedures. See clsc procedures
calling, 262-68, 27
managing inpuL wiLh, 264-68
overview, 262
parenLheses in, 262
public, creaLing, 27
ShellSorL, 882, 885-86
synLax iLems, using, 262
subrouLines. See Sub procedures
SubsLring meLhod, 882
subLracLion operaLor (-), 48, 47
Sun icon animaLion. See Moving
lcon program
swiLching
beLween componenLs, 8
beLween orms, 878
beLween objecLs, 47
beLween Lools, 22-28, 84
Lypes o windows, 2
views in MSDN, 27
synLax errors
checking lines or, 04
idenLiying by jagged line, 72
in variable assignmenLs, 40
overview, 20
solving, 20
unused variables, 28
synLax, sLaLemenL, 58, 24
SysLem Clock properLies, 06
SysLem.Drawing namespace, 876
SysLem.Drawing.Craphics class
overview, 876-77
shapes and meLhods used in,
Lable, 877
SysLem.Drawing.PrinLing
namespace, 46
SysLem.lO namespace, 855
SysLem.MaLh class, 52, 54
SysLem.Windows.Forms.Form
class, 85
T
Lab characLers, ormaLLing LexL
sLrings wiLh, 295
Labbed documenLs
displaying code using,
displaying windows as, 7
windows, 2
Lools as, 8
Lable adapLers, 448
1ableAdapLerManager
componenL, 487
Lables
binding second DaLaCridview
conLrol Lo, 482-84
conLrolling mulLiple, 487
daLabase, 488
dragging, binding, sizing,
472-78
1an(n) meLhod, 52
Laskbar, Windows, 8
LemplaLes
Fxplorer Form, 858
in Add New lLem dialog box, 248
lnheriLed Form, 895-96
inserLing code. See snippeLs
LesLing. See clsc debugging mode
condiLions in l . . . 1hen decision
sLrucLure, 62-68
connecLion, 447
error handler, 284
errors in, 245
or mulLiple run-Lime errors,
287-89
loop condiLions, 92
LexL
aligning, 47
decrypLing, 847
enLering on Web pages, 522
ormaLLing, 5
pasLing rom Windows
Clipboard, 824
prinLing rom prinLing evenL
handlers, 487
prinLing rom LexL box
objecLs, 420
542 1ext ox Sub program
proLecLing wiLh basic encrypLion,
886-40
sorLing, 829-80
1exL 8ox Sub program
creaLing, 264-67
older locaLion, 267
managing inpuL wiLh Sub
procedures, 264-68
running, 267-68
LexL boxes
creaLing, 70, 95
displaying LexL by using, 88
inpuL uncLion o, 78
LocaLion, SoluLion Name, 40
mulLiline, size limiLs o, 85
overview, 70
processing lines in, 882
sorLing sLrings in, 88-86
1exL 8rowser program
examining code in, 820-2
older locaLion, 89
running, 87-9
creaLing new on disk, 82
loading inLo Rich1exL8ox
objecL, 487
mulLipage, prinLing, 424
opening and displaying, My
namespace, 85-6
opening and displaying,
SLreamReader class, 86-7
opening wiLh FileSLream class, 487
reading, 88-4
wriLing, 82, 846
1exL properLies, changing
or descripLive labels, 48-49
or number labels, 48
wiLh For Fach . . . NexL loops,
299-80
LexL sLrings
combining, 57
ormaLLing wiLh carriage reLurns,
Lab characLers, 295
1exLAlign properLy (Appearance
caLegory), 47
1exL8ox conLrol
assigning values Lo variables,
46-47
using counLer variables in
mulLiline LexL, 88-85
using wiLh Web pages, 502
1hrow sLaLemenLs, 289, 245
Lime, seLLing sysLem,
in Windows, 04
1imed Password program
older locaLion, 202
seLLing password Lime limiLs, 200
seLLings or, Lable, 200-0
LesLing, 202-08
1imer conLrol
described, 96
seLLings or, 98
using, 97-99
Limer objecLs
creaLing animaLion by using,
882-85
uses or, 200, 208
1imeSLring properLy, 04, 07
LiLle bars, on Web pages, 92, 522
1o keyword, 78, 82, 207
Loggles, 00
Lool windows
auLo hiding, 7
closing, 7
docking, 7, 9-2, 84
hiding, 2-22, 84
moving, 7-9, 84
resizing, 9, 84
resLoring hidden, 7
Loolbars
adding Lo programs, 9
creaLing, 07-0
creaLing wiLh 1oolSLrip
conLrol, 09
Debug, displaying, 225
FormaLLing, 499-500
moving and deleLing
buLLons on, 0
navigaLion, 456-57
viewing a lisL o, 8
1oolbox. See clsc
locaLion in lDF, 8
organizaLion o conLrols, 4
Web Page Designer, 498
Lools
as Labbed documenLs, 8
swiLching beLween, 22-28, 84
viewing, 8
visual SLudio, 7-9
1oolsLrip conLrol, 08
1oolSLrip conLrol, 07-0
1op properLy, 880
1oSLring meLhod, 75
1rackWins program
opening, 252
running, 26
win raLe uncLion, creaLing,
258-6
Lransparency, changing or
orms, 888-90
1ransparenL Form program
older locaLion, 889
seLLing OpaciLy properLy, 888-90
LroubleshooLing opening projecLs, 7
1ry . . . CaLch code blocks
error handlers, 286
exiLing, 245
nesLed, in error handlers, 242
synLax, 229
Lrapping errors wiLh (Disc Drive
Frror program example),
288-84
using Finally clause wiLh, 284
wriLing nesLed, 245
1ype Here Lag, 98-99
Lyped daLaseLs, 45
U
U8ound uncLion, 280
UlnLeger daLa Lype, 86
ULong daLa Lype, 86
unhandled excepLions, 282
Unicode, 880
UnLil keyword, in Do loops,
96, 208
UpdaLeAll meLhod, 487
updaLing daLabases, 485-87, 489
upgrading rom visual 8asic 2008,
5-6
upper and lower bounds, speciying
in public arrays, 802, 295
URL CollecLion program
creaLing collecLions, 805-06
older locaLion, 807
running, 807-09
user inLeraces. See clsc orms
creaLing, 40-44, 64
elemenLs. See properLies
User validaLion program
adding password proLecLion,
68-69
conLrolling user inpuL, 64-67
UShorL daLa Lype, 86
V
validaLor conLrols, 509
value, assigning
Lo arrays, 278-79, 295
while declaring variables, 90, 207
variable 1esL program, 26-80
variables
adding Lo WaLch window, 225
AuLos window Lo view, 225
changing values o, 27-80, 56
counLer, 82-85
declared, hiding in classes, 42
declaring, 56
declaring class, 408-04
Web stes 543
declaring, in Dim sLaLemenL,
25-26
DecrypL sLring, 844
described, 247-48
displaying conLenLs o, 88-85
examining in Code FdiLor, 225
impliciL declaraLion o, 26-27
lengLh o names, 80
modiying wiLh Lhe lmmediaLe
window, 222-28
naming convenLions, 80
public or global, 40
required compiler seLLing or
declaring, 82
sharing, 247-48
sLorage size o, 85
sLring, 25
Lracking run-Lime errors wiLh,
240-42
validaLing, 89
varianLs, 25
vbCr consLanL, 206
vbCrLF consLanL, 282
view Code buLLon, 54, 65
view Designer, 54
view Menu, 8
viewing
code,
properLies, 8
Web siLes, 505-08
visible properLy (8ehavior
caLegory), 49-5
visual 8asic. See clsc visual SLudio
adding code auLomaLically, 55
applicaLions, deploying, 62
checking compiler seLLings, 82-88
commenLs in, 57
design mode, 42
deLermining version, 7
equivalenLs Lo SLring Class
elemenLs, 827-29
error messages, 55
idenLiying elemenLs by color, 55
lnpuL ConLrols program, 78-79
line conLinuaLion characLer (_), 75
memory allocaLion or arrays, 276
program sLaLemenLs in, 58,
28-24
programs, creaLing wiLh no user
inLerace, 874
random number compuLaLion
in, 57
running rom lDF, 58
running programs rom
Web server, 9
visual 8asic 2008 vs visual
8asic 200, common conLrol
changes, 67
visual 8asic or ApplicaLions,
809-0, 82
visual eedback during
calculaLions, 296
visual SLudio. See clsc visual 8asic
checking compiler seLLings in,
82-88
developmenL, 84
creaLing and running Web
siLes in, 495
deaulL seLLings, 29-80
deploymenL overview, 62-68
displaying lisL box o
properLies, 7
creaLing in, 60
exiLing, 88, 85
Help documenLaLion in, 24-25
Help Lopic locaLions in, 28
icons, biLmaps, and animaLion
lDF. See lDF
programming languages available
in, 4, 88
programs, sLopping in, 72
running programs in, 2
sLarLing, 4-5
sLarLing visual SLudio, 84
Lools, 7-9
Web browser, opening, 28-24
Web siLes, running
and LesLing, 522
visual SLudio 2008, Help
documenLaLion in, 24-25
visual Web Developer
creaLing Web siLes, 49
deploying Web siLes wiLh, 508
displaying daLabase Lables, 52
download locaLion, 496
visualizers
displaying inormaLion wiLh, 226
Lypes o, overview, 220
v1ab consLanL, 282
w
WaLch windows
adding variables, properLies,
expressions Lo, 28-9, 225
displaying, 226
opening, 28
overview, 27
Web 8rowser command (OLher
Windows submenu), 28
Web orms environmenL, daLa
access in, 488
Web Page Designer
described, 498-500
Design mode vs. Source mode,
swiLching beLween, 522
Design Lab, 497
gridline color, changing, 48
page views in, 497
posiLioning conLrols in, 50
Source Lab, 497
SpliL Lab, 497
Web pages
adding LexL in Web Page
Designer, 498-500
changing names o
objecLs on, 522
componenLs, 468, 50
conLrols, adding, 522
cusLomizing, 509-
displaying, 94
displaying daLabase
records on, 522
displaying LiLle on lnLerneL
Fxplorer LiLle bar, 92, 522
enLering LexL on, 522
ormaLLing LexL on, 522
Cridview conLrol, adding,
52-5
hyperlinks, adding, 56-7
linking Lo oLher pages, 522
server conLrols, adding,
50-02
seLLing properLies, 508
validaLor conLrols, 522
viewing H1ML code in, 522
viewing H1ML or, 500
Windows Forms vs., 498
wriLing evenL procedures or
conLrols, 504-05
Web server, running visual 8asic
programs, 9
Web siLes
adding pages or daLabase
inormaLion, 52-8
adding pages Lo, 509
ASP.NF1, creaLing, 522
building and viewing, 505-08
componenLs, 468
creaLing, 496
creaLing wiLh visual Web
Developer, 49
deploying, 508
in visual SLudio, running and
LesLing, 522
locaLions or creaLing and running
in visual SLudio 200, 495
544 Web.
seLLing LiLle in lnLerneL Fxplorer
LiLle bar, 92, 59-2
LesLing (Car Loan CalculaLor
example), 57-9
Web.
WebLink program
creaLing, 9-94
older locaLion, 94
running, 94-95
Weekday (daLe) uncLion, 07
While keyword, 96
WidLh properLy, expanding,
shrinking picLure box aL run
Lime, 886
win raLe uncLion, creaLing,
258-6
windows. See clsc Lool windows
docking, 8
minimizing, maximizing,
resLoring, 864
swiLching beLween Lypes o, 2
Windows applicaLions and
Windows Clipboard, pasLing LexL
rom, 824
Windows Fxplorer, running
Windows applicaLions wiLh, 6
Windows Forms ApplicaLion, 89
Windows Forms conLrols, 67
Windows Forms Designer vs Web
Page Designer, 498
Windows Forms vs Web pages, 498
Windows lnsLaller, 68
Windows Laskbar, 8
Windows version SnippeL program,
208-06
Windows, running programs in, 6
WindowSLaLe properLy, 864
Word macros, compaLibiliLy
beLween versions, 809-0
Wrap keyword, 84
WriLeAll1exL meLhod, 82-28
wriLing
condiLional expressions, 79
evenL handlers, 79
evenL handlers, disc drive, 288
evenL procedures (Color buLLon
example), 8-4
program code, 65
X
XCOP insLallaLion, 62
XML
displaying during debugging
sessions, 226
visualizers, 220
Xor (logical operaLor)
encrypLing LexL by using Lhe,
840-45
encrypLing LexL wiLh,
84-42
encrypLing wiLh, 847
meaning, 67
Xor FncrypLion program
examining Lhe code o,
842-44
older locaLion, 84
running, 84-42
Y
ear (daLe) uncLion, 07
Z
zero, division by, 45, 7
Zoom ln program
older locaLion, 888
loading, 886-88
MchaeI HaIvorson
Michael Halvorson is Lhe auLhor or co-auLhor o more Lhan
85 books, including Micrcscjt visucl 3csic 2998 Ste by Ste,
, and Micrcscjt visucl 3csic 6.9
Prcjessicncl Ste 3y Ste. Halvorson has been Lhe recipienL o
Press 8esL How-Lo 8ook Award (SoLware caLegory) and Lhe
SocieLy or 1echnical CommunicaLion Fxcellence Award (WriLing
caLegory). Halvorson earned a bachelor's degree in CompuLer
and masLer's and docLoral degrees in HisLory rom Lhe UniversiLy
o WashingLon in SeaLLle. He was employed aL MicrosoL
CorporaLion rom 985 Lo 998, and he has been an advocaLe or visual 8asic programming
since Lhe producL's original debuL aL Windows World in 99. Halvorson is currenLly
an .
Best Practices for Software Engineering
ALSO SEE
microsoft.com/mspress
Code Complete,
Second Edition
Steve McConnell
ISBN 9780735619678
Widely considered one of the best practical guides to
programmingfully updated. Drawing from research,
academia, and everyday commercial practice, McConnell
synthesizes must-know principles and techniques into
clear, pragmatic guidance. Rethink your approachand
deliver the highest quality code.
Software Estimation:
Demystifying the Black Art
Steve McConnell
ISBN 9780735605350
Amazon.coms pick for Best Computer Book of 2006!
Generating accurate software estimates is fairly straight-
forwardonce you understand the art of creating them.
processilluminating the practical procedures, formulas,
and heuristics you can apply right away.
Agile Portfolio Management
Jochen Krebs
ISBN 9780735625679
Agile processes foster better collaboration, innovation,
and results. So why limit their use to software projects
when you can transform your entire business? This book
illuminates the opportunitiesand rewardsof applying
agile processes to your overall IT portfolio, with best
practices for optimizing results.
The Enterprise and Scrum
Ken Schwaber
ISBN 9780735623378
products, and lower costsbeyond individual teams to
the entire enterprise. Scrum cofounder Ken Schwaber
describes proven practices for adopting Scrum principles
across your organization, including that all-critical
componentmanaging change.
Simple Architectures for
Complex Enterprises
Roger Sessions
ISBN 9780735625785
Why do so many IT projects fail? Enterprise consultant
Roger Sessions believes complex problems require
simple solutions. And in this book, he shows how to
make simplicity a core architectural requirementas
critical as performance, reliability, or securityto achieve
better, more reliable results for your organization.
Software Requirements, Second Edition
Karl E. Wiegers
ISBN 9780735618794
More About Software Requirements:
Thorny Issues and Practical Advice
Karl E. Wiegers
ISBN 9780735622678
Software Requirement Patterns
Stephen Withall
ISBN 9780735623989
Agile Project Management with Scrum
Ken Schwaber
ISBN 9780735619937
Solid Code
Donis Marshall, John Bruno
ISBN 9780735625921
Stay in touch!
To subscribe to the Microsoft Press

Book Connection Newsletterfor news on upcoming


books, events, and special offersplease visit:
What do
you think of
this book?
We want to hear from you!
To participate in a brief online survey, please visit:
Tell us how well this book meets your needswhat works effectively, and what we can
do better. Your feedback will help us continually improve our books and learning
resources for you.
Thank you in advance for your input!
microsoft.com/ learning/ booksurvey
microsoft.com/learning/books/newsletter