Programming
STARTING OUT WITH
Visual Basic® 2012 Sixth Edit ion
This page intentionally left blank
STARTING OUT WITH
Visual Basic® 2012 Sixth Edit ion
Tony Gaddis Haywood Community College
Kip Irvine Florida International University
Boston Columbus Indianapolis New York San Francisco Upper Saddle River Amsterdam Cape Town Dubai London Madrid Milan Munich Paris Montréal Toronto
Delhi Mexico City Sa~o Paulo Sydney Hong Kong Seoul Singapore Taipei Tokyo
Editorial Director, ECS: Marcia Horton Acquisitions Editor: Matt Goldstein Editorial Assistant: Jenah Blitz-Stoehr Director of Marketing: Christy Lesko Marketing Manager: Yezan Alayan Senior Marketing Coordinator: Kathryn Ferranti Director of Production: Erin Gregg Senior Managing Editor: Scott Disanno Senior Production Project Manager: Marilyn Lloyd Manufacturing Buyer: Lisa McDowell Art Director: Anthony Gemmellaro Cover Designer: Joyce Cosentino Wells Manager, Rights and Permissions: Michael Joyce Cover Image: © Vladimir Nenov/Alamy Media Project Manager: Renata Butera Full-Service Project Manager: Jogender Taneja/iEnergizer Aptara®, Inc. Composition: Aptara®, Inc. Printer/Binder: Edwards Brothers, Inc. Cover Printer: Lehigh-Phoenix Color
Credits and acknowledgments borrowed from other sources and reproduced, with permission, in this textbook appear on the Credits page at the end of the text.
Copyright © 2014, 2011, 2010 Pearson Education, Inc., publishing as Addison-Wesley. All rights reserved. Printed in the United States of America. This publication is protected by Copyright, and permission should be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. To obtain permission(s) to use material from this work, please submit a written request to Pearson Education, Inc., Permissions Department, One Lake Street, Upper Saddle River, New Jersey 07458, or you may fax your request to 201-236-3290.
Many of the designations by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed in initial caps or all caps.
The programs and applications presented in this book have been included for their instructional value. They have been tested with care, but are not guaranteed for any particular purpose. The publisher does not offer any warranties or representations, nor does it accept any liabilities with respect to the programs or applications.
Library of Congress Cataloging-in-Publication Data available upon request.
10 9 8 7 6 5 4 3 2 1
ISBN 10: 0-13-312808-3 ISBN 13: 978-0-13-312808-6
v
Contents in Brief
Preface xvii
Chapter 1 Introduction to Programming and Visual Basic 1
Chapter 2 Creating Applications with Visual Basic 43
Chapter 3 Variables and Calculations 111
Chapter 4 Making Decisions 209
Chapter 5 Lists and Loops 285
Chapter 6 Procedures and Functions 355
Chapter 7 Multiple Forms, Modules, and Menus 403
Chapter 8 Arrays and More 469
Chapter 9 Files, Printing, and Structures 541
Chapter 10 Working with Databases 597
Chapter 11 Developing Web Applications 677
Chapter 12 Classes, Collections, and Inheritance 733
Appendix A Advanced User Interface Controls and Techniques 795
Appendix B Windows Presentation Foundation (WPF) 809
Appendix C Converting Mathematical Expressions to Programming Statements 821
Appendix D Answers to Checkpoints 823
Appendix E Glossary 841
Index 853
Credits 883
This page intentionally left blank
vii
Contents
Preface xvii
Chapter 1 Introduction to Programming and Visual Basic 1
1.1 Computer Systems: Hardware and Software . . . . . . . . . . . . . . . . . . . . . . . . 2 1.2 Programs and Programming Languages . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 TUTORIAL 1-1: Running the Wage Calculator application . . . . . . . . . . . . . . . . . . . . . 8 TUTORIAL 1-2: Running an application that demonstrates event handlers . . . . . . . . 11 1.3 More about Controls and Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 TUTORIAL 1-3: Running an application that demonstrates various controls . . . . . . . 12 1.4 The Programming Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 1.5 Visual Studio and Visual Studio Express (the Visual Basic Environment) . . . . 20 TUTORIAL 1-4: Starting Visual Studio and setting up the environment . . . . . . . . . . . 21 TUTORIAL 1-5: Starting a new Visual Basic project . . . . . . . . . . . . . . . . . . . . . . . . . . 25 TUTORIAL 1-6: Becoming familiar with the Visual Studio environment . . . . . . . . . . 34
Summary 36 • Key Terms 37 • Review Questions and Exercises 37 • Programming Challenges 41
Chapter 2 Creating Applications with Visual Basic 43
2.1 Focus on Problem Solving: Building the Directions Application . . . . . . . . . . 43 TUTORIAL 2-1: Beginning the Directions application . . . . . . . . . . . . . . . . . . . . . . . . 46 TUTORIAL 2-2: Adding a Label control to the Directions application . . . . . . . . . . . . 48 TUTORIAL 2-3: Changing the Label’s font size and style . . . . . . . . . . . . . . . . . . . . . . 50 TUTORIAL 2-4: Deleting a control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52 TUTORIAL 2-5: Inserting a PictureBox control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 TUTORIAL 2-6: Running the application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 TUTORIAL 2-7: Opening an existing project and becoming familiar
with the Properties window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 2.2 Focus on Problem Solving: Responding to Events . . . . . . . . . . . . . . . . . . . . 63 TUTORIAL 2-8: Adding a Label control for the written directions . . . . . . . . . . . . . . . 64 TUTORIAL 2-9: Adding the Display Directions button and its Click
event handler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 TUTORIAL 2-10: Adding the Exit button and its Click event handler . . . . . . . . . . . . 76 TUTORIAL 2-11: Adding comments to the Directions project code . . . . . . . . . . . . . . 79 TUTORIAL 2-12: Changing the text colors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 TUTORIAL 2-13: Setting the FormBorderStyle property and locking
the controls in the Directions application . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 2.3 Modifying a Control’s Text Property with Code . . . . . . . . . . . . . . . . . . . . . 85 TUTORIAL 2-14: Examining an application that displays messages
in a Label control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 2.4 The AutoSize, BorderStyle, and TextAlign Properties . . . . . . . . . . . . . . . . . . 88 2.5 Displaying User Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
viii Contents
TUTORIAL 2-15: Displaying message boxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 2.6 Clickable Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 TUTORIAL 2-16: Writing Click event handlers for PictureBox controls . . . . . . . . . . 95 2.7 Using Visual Studio Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 2.8 Debugging Your Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 TUTORIAL 2-17: Locating a compile error in design mode . . . . . . . . . . . . . . . . . . . 100
Summary 102 • Key Terms 103 • Review Questions and Exercises 104 • Programming Challenges 106
Chapter 3 Variables and Calculations 111
3.1 Gathering Text Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111 TUTORIAL 3-1: Using a TextBox control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 TUTORIAL 3-2: Building the Date String application . . . . . . . . . . . . . . . . . . . . . . . 115 TUTORIAL 3-3: Using the Focus method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118 TUTORIAL 3-4: Changing the tab order . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 TUTORIAL 3-5: Setting access keys, accept, and cancel buttons . . . . . . . . . . . . . . . 123 3.2 Variables and Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124 TUTORIAL 3-6: Assigning text to a variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131 3.3 Performing Calculations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136 3.4 Mixing Different Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143 TUTORIAL 3-7: Examining a Simple Calculator application . . . . . . . . . . . . . . . . . . 151 3.5 Formatting Numbers and Dates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154 TUTORIAL 3-8: Examining the Format Demo application . . . . . . . . . . . . . . . . . . . 157 3.6 Class-Level Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 3.7 Exception Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160 TUTORIAL 3-9: Exception Demonstration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161 TUTORIAL 3-10: Salary Calculator project with exception handling . . . . . . . . . . . 164 3.8 Group Boxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170 3.9 The Load Event . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173 3.10 Focus on Program Design and Problem Solving: Building the Room
Charge Calculator Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173 TUTORIAL 3-11: Beginning the Room Charge Calculator application . . . . . . . . . . 179 TUTORIAL 3-12: Changing a label’s colors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184 3.11 More about Debugging: Locating Logic Errors . . . . . . . . . . . . . . . . . . . . . 186 TUTORIAL 3-13: Single-stepping through an application’s code at runtime . . . . . . 186
Summary 192 • Key Terms 195 • Review Questions and Exercises 196 • Programming Challenges 202
Chapter 4 Making Decisions 209
4.1 The Decision Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209 4.2 The If...Then Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211 TUTORIAL 4-1: Examining an application that uses the If...Then statement . . 214 4.3 The If...Then...Else Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . 217 TUTORIAL 4-2: Completing an application that uses
the If...Then...Else statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218 4.4 The If...Then...ElseIf Statement . . . . . . . . . . . . . . . . . . . . . . . . . 220
Contents ix
TUTORIAL 4-3: Completing an application that uses the If...Then...ElseIf statement . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
4.5 Nested If Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227 TUTORIAL 4-4: Completing an application with a nested If statement . . . . . . . . . 227 4.6 Logical Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229 4.7 Comparing, Testing, and Working with Strings . . . . . . . . . . . . . . . . . . . . 235 TUTORIAL 4-5: Examining an application that performs string comparisons . . . . . 238 TUTORIAL 4-6: Completing a string searching application . . . . . . . . . . . . . . . . . . . 243 4.8 The Select Case Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246 TUTORIAL 4-7: Examining Crazy Al’s Sales Commission
Calculator application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249 4.9 Introduction to Input Validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252 TUTORIAL 4-8: Examining an application that uses TryParse
for input validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254 4.10 Focus on GUI Design: Radio Buttons and Check Boxes . . . . . . . . . . . . . . . 257 TUTORIAL 4-9: Completing an application with radio buttons
and check boxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259 4.11 Focus on Program Design and Problem Solving: Building
the Health Club Membership Fee Calculator Application . . . . . . . . . . . . . . . 260 TUTORIAL 4-10: Building the Health Club Membership Fee Calculator
application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
Summary 270 • Key Terms 271 • Review Questions and Exercises 272 • Programming Challenges 277
Chapter 5 Lists and Loops 285
5.1 Input Boxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285 5.2 List Boxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287 TUTORIAL 5-1: Creating list boxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292 5.3 Introduction to Loops: The Do While Loop . . . . . . . . . . . . . . . . . . . . . . 296 TUTORIAL 5-2: Completing an application that uses the Do While loop . . . . . . . 297 TUTORIAL 5-3: Modifying the Do While Demo application to use
a posttest loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301 TUTORIAL 5-4: Using a loop to keep a running total . . . . . . . . . . . . . . . . . . . . . . . 303 TUTORIAL 5-5: Examining an application that uses a user-controlled loop . . . . . . . 305 5.4 The Do Until and For...Next Loops . . . . . . . . . . . . . . . . . . . . . . . . . 307 TUTORIAL 5-6: Examining an application that uses the Do Until loop . . . . . . . . 308 TUTORIAL 5-7: Examining an application that uses the For...Next loop . . . . . . 312 TUTORIAL 5-8: Completing an application that uses the For...Next loop . . . . . 313 5.5 Nested Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317 5.6 Multicolumn List Boxes, Checked List Boxes, and Combo Boxes . . . . . . . . 318 TUTORIAL 5-9: Creating combo boxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322 5.7 Random Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324 TUTORIAL 5-10: Creating the Coin Toss application . . . . . . . . . . . . . . . . . . . . . . . . 326 5.8 Simplifying Code with the With...End With Statement . . . . . . . . . . . 328 5.9 ToolTips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329 TUTORIAL 5-11: Adding ToolTips to an application . . . . . . . . . . . . . . . . . . . . . . . . 330 5.10 Focus on Program Design and Problem Solving: Building
the Vehicle Loan Calculator Application . . . . . . . . . . . . . . . . . . . . . . . . . . . 331
x Contents
TUTORIAL 5-12: Building the Vehicle Loan Calculator application . . . . . . . . . . . . . 334
Summary 339 • Key Terms 340 • Review Questions and Exercises 340 • Programming Challenges 346
Chapter 6 Procedures and Functions 355
6.1 Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356 TUTORIAL 6-1: Examining an application with a procedure . . . . . . . . . . . . . . . . . . 356 TUTORIAL 6-2: Creating and calling procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . 359 6.2 Passing Arguments to Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363 TUTORIAL 6-3: Examining an application that demonstrates passing
an argument to a procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365 TUTORIAL 6-4: Working with ByVal and ByRef . . . . . . . . . . . . . . . . . . . . . . . . . 368 6.3 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371 TUTORIAL 6-5: Sale Price Calculator application . . . . . . . . . . . . . . . . . . . . . . . . . . 372 6.4 More about Debugging: Stepping Into, Over,
and Out of Procedures and Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379 TUTORIAL 6-6: Practicing the Step Into command . . . . . . . . . . . . . . . . . . . . . . . . . 380 TUTORIAL 6-7: Practicing the Step Over command . . . . . . . . . . . . . . . . . . . . . . . . 381 TUTORIAL 6-8: Practicing the Step Out command . . . . . . . . . . . . . . . . . . . . . . . . . 381 6.5 Focus on Program Design and Problem Solving: Building
the Bagel and Coffee Price Calculator Application . . . . . . . . . . . . . . . . . . . . 383 TUTORIAL 6-9: Building the Bagel House application . . . . . . . . . . . . . . . . . . . . . . . 388
Summary 392 • Key Terms 392 • Review Questions and Exercises 393 • Programming Challenges 396
Chapter 7 Multiple Forms, Modules, and Menus 403
7.1 Multiple Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403 TUTORIAL 7-1: Creating an application with two forms . . . . . . . . . . . . . . . . . . . . . 411 TUTORIAL 7-2: Completing an application that displays modal
and modeless forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414 TUTORIAL 7-3: Accessing a control on a different form . . . . . . . . . . . . . . . . . . . . . 420 7.2 Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425 TUTORIAL 7-4: Examining an application that uses a module . . . . . . . . . . . . . . . . 428 7.3 Menus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435 TUTORIAL 7-5: Building a menu . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442 7.4 Focus on Problem Solving: Building the High Adventure Travel
Agency Price Quote Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447 TUTORIAL 7-6: Building the High Adventure Travel Agency Price Quote
application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
Summary 455 • Key Terms 456 • Review Questions and Exercises 456 • Programming Challenges 461
Chapter 8 Arrays and More 469
8.1 Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469 TUTORIAL 8-1: Using an array to hold a list of random lottery numbers . . . . . . . . 474 TUTORIAL 8-2: Using an array to hold a list of names entered by the user . . . . . . . 477
Contents xi
TUTORIAL 8-3: Completing an application that uses array elements in a calculation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 480
8.2 Array Processing Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 484 TUTORIAL 8-4: Using parallel arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488 8.3 Procedures and Functions That Work with Arrays . . . . . . . . . . . . . . . . . . . 494 TUTORIAL 8-5: Examining an application that passes an array
to procedures and functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 496 8.4 Multidimensional Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501 TUTORIAL 8-6: Completing the Seating Chart application . . . . . . . . . . . . . . . . . . . 505 8.5 Focus on GUI Design: The Enabled Property and the Timer Control . . . . .510 TUTORIAL 8-7: The Timer Demo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 511 TUTORIAL 8-8: Creating the Catch Me game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 512 8.6 Focus on GUI Design: Anchoring and Docking Controls . . . . . . . . . . . . . . 515 8.7 Focus on Problem Solving: Building the Demetris Leadership
Center Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 518 TUTORIAL 8-9: Building the Demetris Leadership Center Sales
Reporting application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521 8.8 Using Lists to Hold Information (Optional Topic) . . . . . . . . . . . . . . . . . . . 524 TUTORIAL 8-10: Building a List from User Input . . . . . . . . . . . . . . . . . . . . . . . . . . 526
Summary 529 • Key Terms 530 • Review Questions and Exercises 531 • Programming Challenges 536
Chapter 9 Files, Printing, and Structures 541
9.1 Using Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 541 TUTORIAL 9-1: Completing an application that writes data to a file . . . . . . . . . . . . 546 TUTORIAL 9-2: Completing an application that reads a file . . . . . . . . . . . . . . . . . . 551 TUTORIAL 9-3: Examining an application that detects the end of a file . . . . . . . . . 555 9.2 The OpenFileDialog, SaveFileDialog, FontDialog, and ColorDialog
Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .561 TUTORIAL 9-4: Creating a Simple Text Editor application . . . . . . . . . . . . . . . . . . . 565 9.3 The PrintDocument Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 574 TUTORIAL 9-5: Adding printing capabilities to the Simple Text Editor
application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 575 9.4 Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 580 TUTORIAL 9-6: Examining an application with a structure . . . . . . . . . . . . . . . . . . . 583
Summary 585 • Key Terms 585 • Review Questions and Exercises 586 • Programming Challenges 592
Chapter 10 Working with Databases 597
10.1 Database Management Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 597 10.2 Database Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 598 10.3 DataGridView Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 602 TUTORIAL 10-1: Showing a database table in a DataGridView control . . . . . . . . . . 603 TUTORIAL 10-2: Sorting and updating the SalesStaff table . . . . . . . . . . . . . . . . . . . 611 10.4 Data-Bound Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 614 TUTORIAL 10-3: Binding a DataGridView to the SalesStaff table . . . . . . . . . . . . . . 619 TUTORIAL 10-4: Binding individual controls to the SalesStaff table . . . . . . . . . . . . 621
xii Contents
TUTORIAL 10-5: Displaying the Karate Members table in a ListBox Control . . . . . 625 TUTORIAL 10-6: Inserting Karate member payments . . . . . . . . . . . . . . . . . . . . . . . 628 TUTORIAL 10-7: Adding a total to the Insert Karate Payments application . . . . . . 632 10.5 Structured Query Language (SQL) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .633 TUTORIAL 10-8: Filtering rows in the SalesStaff table . . . . . . . . . . . . . . . . . . . . . . . 641 10.6 Focus on Problem Solving: Karate School Management Application . . . . . . 643 TUTORIAL 10-9: Creating the Karate School Manager startup form . . . . . . . . . . . . 647 TUTORIAL 10-10: Adding the Membership / List All function
to the Karate School Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 647 TUTORIAL 10-11: Adding the Membership / Add New Member function
to the Karate School Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 650 TUTORIAL 10-12: Adding the Membership / Find Member function
to the Karate School Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 652 TUTORIAL 10-13: Adding the Payments / All Members function
to the Karate School Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 654 10.7 Introduction to LINQ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 661 10.8 Creating Your Own Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .662 TUTORIAL 10-14: Creating the Movie database and the Films table . . . . . . . . . . . 663
Summary 667 • Key Terms 668 • Review Questions and Exercises 669 • Programming Challenges 671
Chapter 11 Developing Web Applications 677
11.1 Programming for the Web . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 677 11.2 Creating ASP.NET Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 681 TUTORIAL 11-1: Creating the Click application . . . . . . . . . . . . . . . . . . . . . . . . . . . 685 11.3 Web Server Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 690 TUTORIAL 11-2: Student Picnic application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 692 11.4 Designing Web Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 700 TUTORIAL 11-3: Signing up for a Kayak Tour . . . . . . . . . . . . . . . . . . . . . . . . . . . . 703 11.5 Applications with Multiple Web Pages . . . . . . . . . . . . . . . . . . . . . . . . . . . 707 TUTORIAL 11-4: Adding a description form to the Kayak Tour application . . . . . . 709 11.6 Using Databases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 710 TUTORIAL 11-5: Displaying the Karate Members table in a GridView . . . . . . . . . . 713 TUTORIAL 11-6: Updating the Karate Members table . . . . . . . . . . . . . . . . . . . . . . . 718
Summary 726 • Key Terms 727 • Review Questions and Exercises 728 • Programming Challenges 731
Chapter 12 Classes, Collections, and Inheritance 733
12.1 Classes and Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 733 12.2 Creating a Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 736 TUTORIAL 12-1: Creating the Student Data application . . . . . . . . . . . . . . . . . . . . . 749 12.3 Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 753 12.4 Focus on Problem Solving: Creating the Student Collection Application . . . 760 TUTORIAL 12-2: Completing the Student Collection application . . . . . . . . . . . . . . 760 12.5 The Object Browser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 765 TUTORIAL 12-3: Using the Object Browser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 765 12.6 Introduction to Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 767
Contents xiii
TUTORIAL 12-4: Completing an application that uses inheritance . . . . . . . . . . . . . 774
Summary 781 • Key Terms 782 • Review Questions and Exercises 783 • Programming Challenges 790
Appendix A Advanced User Interface Controls and Techniques . . . . . . 795
Appendix B Windows Presentation Foundation (WPF) . . . . . . . . . . . . . . 809
Appendix C Converting Mathematical Expressions to Programming Statements . . . . . . . . . . . . . . . . . . . . . . . . . 821
Appendix D Answers to Checkpoints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 823
Appendix E Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 841
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 853
Credits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 883
VideoNoteLOCATION OF VIDEONOTES IN THE TEXT
Chapter 1 Forms, Controls, and Properties, p. 9
Event-Driven Programming, p. 10
Tutorial 1-4 Walkthrough, p. 21
Tutorial 1-5 Walkthrough, p. 25
Tutorial 1-6 Walkthrough, p. 34
Solving the Sales Tax Problem, p. 41
Chapter 2 Tutorial 2-1 Walkthrough, p. 46
Tutorial 2-2 Walkthrough, p. 48
Tutorial 2-3 Walkthrough, p. 50
Tutorial 2-5 Walkthrough, p. 53
Tutorial 2-6 Walkthrough, p. 57
Responding to Events, p. 63
Tutorial 2-8 Walkthrough, p. 64
Tutorial 2-9 Walkthrough, p. 68
Tutorial 2-10 Walkthrough, p. 76
Using IntelliSense, p. 84
The Name and Address Problem, p. 107
Chapter 3 Tutorial 3-2 Walkthrough, p. 115
Introduction to Variables, p. 124
Problem Solving with Variables, p. 136
Converting TextBox Input, p. 149
Exception Demonstration, p. 161
Tutorial 3-10 Walkthrough, p. 164
Building a Kayak Rental Application, p. 195
The Miles per Gallon Calculator Problem, p. 202
Chapter 4 The If...Then Statement, p. 211
The If...Then...Else Statement, p. 217
Tutorial 4-2 Walkthrough, p. 218
Tutorial 4-3 Walkthrough, p. 221
Tutorial 4-4 Walkthrough, p. 227
Validating Input with TryParse, p. 254
Improving the Kayak Rental Application, p. 272
The Roman Numeral Converter Problem, p. 277
Chapter 5 The Do While Loop, p. 296
Tutorial 5-2 Walkthrough, p. 297
Tutorial 5-3 Walkthrough, p. 301
The For...Next Loop, p. 310
Improving the Kayak Rental Application, p. 340
The Sum of Numbers Problems, p. 346
Chapter 6 Tutorial 6-2 Walkthrough, p. 359
Passing Arguments to Procedures, p. 363
Functions, p. 371
Tutorial 6-5 Walkthrough, p. 372
Tutorial 6-6 Walkthrough, p. 380
Improving the Kayak Rental Application, p. 393
The Retail Price Calculator Problem, p. 396
Chapter 7 Creating and Displaying a Second Form, p. 405
Tutorial 7-1 Walkthrough, p. 411
Creating a Menu, p. 435
Adding menus and forms to the Kayak Rental Application, p. 456
The Astronomy Helper Problem, p. 466
Chapter 8 Accessing Array Elements with a Loop, p. 472
Tutorial 8-2 Walkthrough, p. 477
Tutorial 8-3 Walkthrough, p. 480
Using Arrays to Look Up Information in the Kayak Rental Application, p. 531
The Lottery Application, p. 539
Chapter 9 Writing Data to a File, p. 543
Reading Data from a File, p. 549
Tutorial 9-3 Walkthrough, p. 556
Files and Colors in the Kayak Rental Application, p. 586
The Random Number File Generator Problem, p. 594
Chapter 10 The DataGridView Control, p. 602
Data-Bound Controls, p. 614
Tutorial 10-4 Walkthrough, p. 621
Adding a Database to the Kayak Rental Application, p. 669
The Karate Members Grid Problem, p. 671
The Karate Payments by a Single Member Problem, p. 674
Chapter 11 Creating a Simple Web Application, p. 682
Tutorial 11-2 Walkthrough, p. 692
Building a Movie Tracking Application, p. 728
The Stadium Seating Problem, p. 731
Chapter 12 Creating a Class, p. 737
Collections, p. 753
Tutorial 12-2 Walkthrough, p. 760
Kayak Rentals with Classes, p. 783
The Motor Class Problem, p. 791
This page intentionally left blank
xvii
Preface
Welcome to Starting Out with Visual Basic 2012, Sixth Edition. This book isintended for use in an introductory programming course. It is designed for stu- dents who have no prior programming background, but even experienced students will benefit from its depth of detail and the chapters covering databases, Web applications, and other advanced topics. The book is written in clear, easy-to-understand language and covers all the necessary topics of an introductory programming course. The text is rich in concise, practical, and real-world example programs, so the student not only learns how to use the various controls, constructs, and features of Visual Basic, but also learns why and when to use them.
Changes in the Sixth Edition • The book is completely updated for Visual Basic 2012—This book is designed for
use with Visual Studio 2012 and Visual Studio Express 2012 for Windows Desktop. • Introduction of the StatusStrip Control for Displaying User Messages—The
StatusStrip control is introduced in Chapter 2 as a means for displaying user mes- sages. In many situations, the StatusStrip control is more effective than a message box because it does not interrupt the user’s workflow.
• A New Sequence of VideoNotes has been added throughout the book—Beginning in Chapter 3, a new sequence of video tutorials that promote an accelerated learning experience are introduced. Each set of tutorials uses topics from the current and pre- vious chapters to build an application that integrates visual design and interaction principles. Students who wish to accelerate their learning may use these videos to summarize and apply essential topics in these chapters.
• A New Tutorial for Creating a Database—A new tutorial has been added to Chap- ter 10 showing the student how to create a database within Visual Studio, and add data to the database.
Visual Studio 2012 Express for Windows Desktop Each new copy of this book comes with Microsoft’s Visual Studio 2012 Express for Win- dows Desktop—a streamlined product that captures the best elements of Visual Studio in an ideal format for learning programming. The Express edition offers an impressive set of tools for developing and debugging Visual Basic Windows Forms applications and Web applications, applications, including those that work with databases and use SQL.
A Look at Visual Basic: Past and Present The first version of Visual Basic was introduced in 1991. Prior to its introduction, writing a GUI interface for an application was no small task. Typically, it required hundreds of lines of C code for even the simplest Hello World program. Additionally, an understand- ing of graphics, memory, and complex system calls was often necessary. Visual Basic was revolutionary because it significantly simplified this process. With Visual Basic, a programmer could visually design an application’s user interface. Visual Basic would then generate the code necessary to display and operate the interface. This allowed the programmer to spend less time writing GUI code and more time writing code to perform meaningful tasks.
xviii Preface
The evolution of Visual Basic from version 1 to version 6 followed a natural progression. Each new release was an improved version of the previous release, providing additional features and enhancements. Visual Basic versions offered backward compatibility, where code written in an older version was compatible with a newer version of the Visual Basic development environment.
In 2002, Microsoft released a new object-oriented software platform known as .NET. The .NET platform consists of several layers of software that sit above the operating system and provide a secure, managed environment in which programs can execute. In addition to providing a managed environment for applications to run, .NET also provided new technologies for creating Internet-based programs and programs that provide services over the Web. Along with the introduction of the .NET platform, Microsoft introduced a new version of Visual Basic known as VB .NET 2002, which allowed programmers to write desktop applications or Web applications for the .NET platform.
VB .NET was not merely a new and improved version of VB 6, however. VB .NET was a totally new programming environment, and the Visual Basic language was dramatically revised. The changes were substantial enough that programs written in earlier versions of Visual Basic were not compatible with VB .NET. Microsoft provided a utility that could be used to convert older Visual Basic applications to the new VB .NET syntax, but the results were not always perfect. Although this was frustrating for some Visual Basic developers, Microsoft reasoned the changes were necessary to ensure that Visual Basic continued to evolve as a modern, professional programming environment.
Microsoft has continued to enhance and improve Visual Basic by regularly releasing new versions. The versions, which are named after the year in which they were released, are Visual Basic 2003, Visual Basic 2005, Visual Basic 2008, Visual Basic 2010, and the most recent version, Visual Basic 2012.
This book is written for Visual Basic 2012. This version of Visual Basic includes several enhancements that make Visual Basic even more powerful as a professional program- ming system. Many of the new features are beyond the scope of this book, and are not covered. The following list summarizes some of the most significant new features of VB 2012:
• Introduction of the Async method modifier and the Await statement, for asynchro- nous programming.
• Introduction of iterators, to perform custom iterations over collections, lists, and arrays.
• A new call hierarchy window in Visual Studio that allows you to display all calls to and from a selected method, property, or constructor.
• Caller information attributes that allow you to obtain information about the caller of a method.
• You can now use the Global keyword in a Namespace statement, to define a name- space out of the project’s root namespace.
• By default, arguments are passed by value, and the ByVal modifier for a parameter is no longer required.
Organization of the Text The text teaches Visual Basic step-by-step. Each chapter covers a major set of programming topics, introduces controls and GUI elements, and builds knowledge as the student pro- gresses through the book. Although the chapters can be easily taught in their existing sequence, there is some flexibility. The following diagram suggests possible sequences of instruction.
Preface xix
Chapters 1 through 7 cover the fundamentals of program design, flow control, modular programming, and the most important Visual Basic controls. The instructor may then continue in any order with Chapters 8, 9, 10, or 12. Part of Chapter 11 relies on database concepts, so it should be covered after Chapter 10.
Brief Overview of Each Chapter
Chapter 1: Introduction to Programming and Visual Basic. This chapter provides an introduction to programming, the programming process, and Visual Basic. GUI programming and the event-driven model are explained. The components of programs, such as keywords, variables, operators, and punctuation are covered, and tools such as flowcharts and pseudocode are presented. The student gets started using the Visual Basic environment in a hands-on tutorial.
Chapter 2: Creating Applications with Visual Basic. The student starts by creat- ing a simple application that displays a graphic image. In the tutorials that follow, the stu- dent adds controls, modifies properties, and enables the application to respond to events. An introduction to the Visual Basic Help system, with a tutorial on debugging, is given.
Chapter 3: Variables and Calculations. Variables, constants, and the Visual Basic data types are introduced. The student learns to gather input and create simple arithmetic statements. The intricacies of GUI design are introduced as the student learns about grouping controls with group boxes, assigning keyboard access keys, and setting the tab order. The student is introduced to exceptions and learns to write simple exception han- dlers. Debugging techniques for locating logic errors are covered.
Chapter 4: Making Decisions. The student learns about relational operators and how to control the flow of a program with the If...Then, If...Then...Else, and If...Then...ElseIf statements. Logical operators are introduced, and the Select Case statement is covered. Important applications of these constructs are discussed, such as testing numeric values, strings, and determining if a value lies within a range, and vali- dating user input. Several string-handling functions and string methods are discussed. Radio buttons and check boxes are also introduced.
Chapter 5: Lists and Loops. This chapter begins by showing the student how to use input boxes as a quick and simple way to gather input. Next, list boxes and combo boxes are introduced. The chapter covers repetition control structures: the Do While, Do Until, and For...Next loops. Counters, accumulators, running totals, and other loop- related topics are discussed. The student also learns how to generate random numbers.
Chapter 6: Procedures and Functions. The student learns how and why to modu- larize programs with general-purpose procedures and functions. Arguments, parameters, and return values are discussed. Debugging techniques for stepping into and over proce- dures are introduced.
Chapter 7: Multiple Forms, Modules, and Menus. This chapter shows how to add multiple forms to a project and how to create a module to hold procedures and functions
Chapter 11
Chapters 1–7
Chapter 8 Chapter 9 Chapter 10 Chapter 12
xx Preface
that are not associated with a specific form. It covers creating a menu system, with com- mands and submenus that the user may select from.
Chapter 8: Arrays and More. This chapter discusses both single dimension and multi- dimensional variable arrays. Many array programming techniques are presented, such as summing all the elements in an array, summing all the rows or columns in a two-dimensional array, searching an array for a specific value, sorting arrays, and using parallel arrays. The Enabled property, timer controls, and control anchoring and docking are also covered.
Chapter 9: Files, Printing, and Structures. This chapter begins by discussing how to save data to sequential text files and then read the data back into an application. The OpenFileDialog, SaveFileDialog, FontDialog, and ColorDialog controls are introduced. The PrintDocument control is discussed, with a special focus on printing reports. The chapter shows the student how to create user-defined data types with structures.
Chapter 10: Working with Databases. This chapter introduces basic database con- cepts. The student learns how to display a database table in a DataGridView control and write applications that display, sort, and update database data. The Structured Query Language (SQL) is introduced. An application that shows how to display database data in list boxes, text boxes, labels, and combo box is presented. The chapter concludes with an overview of Language Integrated Query (LINQ).
Chapter 11: Developing Web Applications. This chapter shows the student how to create ASP.NET applications that run on Web Browsers such as Internet Explorer, Chrome, Firefox, and Safari. Using Microsoft Visual Studio, or Microsoft Visual Web Developer, the student learns how to use Web server controls and Web forms to build interactive, database-driven Web applications.
Chapter 12: Classes, Collections, and Inheritance. This chapter introduces classes as a tool for creating abstract data types. The process of analyzing a problem and deter- mining its classes is discussed, and techniques for creating objects, properties, and methods are introduced. Collections are presented as structures for holding groups of objects. The Object Browser, which allows the student to see information about the classes, properties, methods, and events available to a project, is also covered. The chapter concludes by intro- ducing inheritance, and shows how to create a class that is based on an existing class.
Appendix A: Advanced User Interface Controls and Techniques. Discusses many of the more advanced controls available in Visual Basic, as well as several helpful programming techniques. This appendix also provides a summary of common user inter- face design guidelines.
Appendix B: Windows Presentation Foundation (WPF). Introduces the student to the Windows Presentation Framework (WPF), and includes a tutorial in which the student creates a simple WPF application.
Appendix C: Converting Mathematical Expressions to Programming Statements. Shows the student how to convert a mathematical expression into a Visual Basic programming statement.
Appendix D: Answers to Checkpoints. Students may test their progress by com- paring their answers to Checkpoints with the answers provided. The answers to all Checkpoints are included.
Appendix E: Glossary. Provides a glossary of the key terms presented in the text.
The following appendixes are located on the Student CD-ROM:
Appendix F: Visual Basic 2012 Function and Method Reference. Provides a reference for the functions and methods that are covered in the text. The exceptions that may be caused by these functions and methods are also listed.
Preface xxi
Appendix G: Binary and Random-Access Files. Describes programming techniques for creating and working with binary and random-access data files.
The following appendix is available on the Companion Website for this book at http://www.pearsonhighered.com/gaddisvb/.
Features of the Text
Concept Statements. Each major section of the text starts with a concept statement. This statement concisely summarizes the meaning of the section.
Tutorials. Each chapter has several hands-on tutorials that reinforce the chapter’s topics. Many of these tutorials involve the student in writing applications that can be applied to real-world problems.
VideoNotes. A series of online videos, developed specifically for this book, are available for viewing at http://www.pearsonhighered.com/gaddisvb/. Icons appear throughout the text alerting the student to videos about specific topics.
Checkpoints. Checkpoints are questions placed at intervals throughout each chapter. They are designed to query the student’s knowledge immediately after learning a new topic. Answers to all the Checkpoints are provided in Appendix D.
Notes. Notes are short explanations of interesting or often misunderstood points relevant to the topic being discussed.
Tips. Tips advise the student on the best techniques for approaching different program- ming problems and appear regularly throughout the text.
Warnings. Warnings caution the student about certain Visual Basic features, programming techniques, or practices that can lead to malfunctioning programs or lost data.
Review Questions and Exercises. In the tradition of all Gaddis texts, each chapter presents a thorough and diverse set of review questions and exercises. These include tra- ditional fill-in-the-blank, true or false, multiple choice, and short answer questions. There are also unique tools for assessing a student’s knowledge. For example, Find the Error questions ask the student to identify syntax or logic errors in brief code segments. Algorithm Workbench questions ask the student to design code segments to satisfy a given problem. There are also What Do You Think? questions that require the student to think critically and contemplate the topics presented in the chapter.
Programming Challenges. Each chapter offers a pool of programming exercises designed to solidify the student’s knowledge of the topics at hand. In most cases, the assignments present real-world problems to be solved. When applicable, these exercises also include input validation rules.
Supplements Student The following supplementary material is bundled with the book:
• Source code and files required for the chapter tutorials are available at the book’s companion website: www.pearsonhighered.com/gaddisvb. The website also con- tains Appendix F, Visual Basic 2012 Function and Method Reference, and Appendix G, Binary and Random-Access Files.
• Microsoft Visual Studio 2012 Express for Windows Desktop
VideoNote
http://www.pearsonhighered.com/gaddisvb/
http://www.pearsonhighered.com/gaddisvb/
www.pearsonhighered.com/gaddisvb
xxii Preface
Instructor The following supplements are available to qualified instructors:
• Answers to all Review Questions in the text • Solutions for all Programming Challenges in the text • PowerPoint presentation slides for every chapter • Test bank • Test generation software that allows instructors to create customized tests
For information on how to access these supplements, visit the Pearson Education Instructor Resource Center at http://www.pearsonhighered.com/irc/ or send e-mail to computing@aw.com.
Online Practice and Assessment with MyProgrammingLab MyProgrammingLab is a web-based service that helps students fully grasp the logic, seman- tics, and syntax of programming. Through practice exercises and immediate, personalized feedback, MyProgrammingLab improves the programming competence of beginning stu- dents who often struggle with the basic concepts and paradigms of popular high-level pro- gramming languages. A self-study and homework tool, a MyProgrammingLab course consists of hundreds of small practice exercises organized around the structure of this text- book. For students, the system automatically detects errors in the logic and syntax of their code submissions and offers targeted hints that enable students to figure out what went wrong. For instructors, a comprehensive gradebook tracks correct and incorrect answers and stores the code inputted by students for review.
For a full demonstration, to see feedback from instructors and students, or to get started using MyProgrammingLab in your course, visit MyProgrammingLab.com.
Web Resources Self-assessment quizzes, PowerPoint slides, source code files, and glossary flashcards are avail- able on the Companion Website for Starting Out with Visual Basic 2012 at http://www. pearsonhighered.com/gaddisvb/.
Acknowledgments There were many helping hands in the development and publication of this text. The authors would like to thank the following faculty reviewers for their helpful suggestions and expertise during the production of this edition:
Paul Bladek, Edmonds Community College Arthur E. Carter, Radford University Jesse Cecil, College of the Siskiyous Sallie Dodson, Radford University Jackie Horton, University of Vermont Darrel Karbginsky, Chemeketa Community
College Frank J. Kreimendahl, University of New
Hampshire Jing Liu, Southeastern Louisiana University Solomon Negash, Kennesaw State University
Robert Nields, Cincinnati State Technical and Community College
Alison Pechenick, University of Vermont Richard Pelletier, San Diego City College Pete Sanderson, Otterbein University Gurmukh Singh, SUNY Fredonia Judith A. Stafford, Tufts University Doug Waterman, Fox Valley Technical College Erik Wynters, Bloomsburg University of
Pennsylvania
http://www.pearsonhighered.com/irc/
http://www.pearsonhighered.com/gaddisvb/
http://www.pearsonhighered.com/gaddisvb/
Preface xxiii
Achla Agarwal, Bossier Parrish Community College
Ronald Bass, Austin Community College Ronald Beauchemin, Springfield Technical
Community College Zachory T. Beers, Microsoft Corporation Robert M. Benavides, Collin County Community
College District Douglas Bock, Southern Illinois University at
Edwardsville Skip Bottom, J. Sargeant Reynolds Community
College Harold Broberg, Indiana Purdue University Nancy Burns, Professor of Computer Science,
Chipola College Mara Casado, State College of Florida,
Manatee-Sarasota Joni Catanzaro, Louisiana State University Dr. Robert Coil, Cincinnati State Community and
Technical College Carol A. DesJardins, St. Clair County Community
College William J. Dorin, Indiana University Robert Ekblaw, SUNY Albany Rose M. Endres, City College of San Francisco Jean Evans, Brevard Community College Mark Fienup, University of Northern Iowa Pierre M. Fiorini, PhD, University of Southern
Maine Arlene Flerchinger, Chattanooga State Technical
Community College Lawrence Fudella, Erie Community College Gail M. Gehrig, Florida Community College at
Jacksonville Jayanta Ghosh, Florida Community College Iskandar Hack, Indiana University—Purdue
University at Fort Wayne Tom Higginbotham, Southeastern Louisiana
University Dennis Higgins, SUNY Oneonta David M. Himes, Oklahoma State University,
Okmulgee Greg Hodge, Northwestern Michigan College Corinne Hoisington, Central Virginia Community
College
May-Chuen Hsieh, Southwest Tennessee Community College
Lee A. Hunt, Collin County Community College Herb Kronholm, Mid-State Technical College Phil Larschan, Tulsa Community College Art Lee, Lord Fairfax Community College Joo Eng Lee-Partridge, Central Connecticut State
University Juan Marquez, Mesa Community College Gary Marrer, Glendale Community College Norman McNeal, Dakota County Technical
College George McOuat, Hawaii Pacific University Joseph Merrell Sylvia Miner, Florida International University Billy Morgan, Holmes Community College Joan P. Mosey, Point Park College Robert Nields, Cincinnati State Community and
Technical College Gregory M. Ogle Christopher J. Olson, Dakota State University Merrill B. Parker, Chattanooga State Technical
Community College Rembert N. Parker, Anderson University Carol M. Peterson, South Plains Community
College Anita Philipp, Oklahoma City Community
College T. N. Rajashekhara, Camden County College Mark Reis, University of Virginia Malu Roldan, San Jose State Judy Scholl, Austin Community College Gurmukh Singh, SUNY at Fredonia Anne Spalding, Mesa State College Angeline Surber, Mesa Community College Robert L. Terrell, Walters State Community
College Margaret Warrick, Allan Hancock College Elaine Yale Weltz, Seattle Pacific University Floyd Jay Winters, Program Director,
Computer Science, College of Florida, Manatee-Sarasota
Catherine Wyman, DeVry Institute, Phoenix
Sheri L. York, Ball State University
The authors would like to thank their families for their tremendous support throughout this project. We would also like to thank everyone at Pearson Addison-Wesley who was part of our editorial, production, and marketing team. We are fortunate to have Matt Goldstein as our editor for this book. He and Jenah Blitz-Stoehr, editorial assistant, guided us through the delicate process of revising the book. The production team, led by Marilyn Lloyd, did a tremendous job to make this book a reality. We are also fortunate to work with Yez Alayan, Marketing Manager, and Kathryn Ferranti, Marketing Coordinator. They do a great job getting this book out to the academic community. You are all great people to work with!
Reviewers of the Previous Editions
xxiv Preface
About the Authors Tony Gaddis is the principal author of the Starting Out with series of textbooks. Tony has nearly two decades of experience teaching computer science courses, primarily at Haywood Community College in North Carolina. He is a highly acclaimed instructor who was previously selected as North Carolina’s Community College Teacher of the Year, and has received the Teaching Excellence award from the National Institute for Staff and Organizational Development. Besides Visual Basic books, the Starting Out with series includes introductory books on programming logic and design, Alice, the C++ programming language, Java™, Python, and Microsoft® C#®, all published by Pearson Addison-Wesley.
Kip Irvine holds M.S. (computer science) and D.M.A. (music composition) degrees from the University of Miami. He was formerly on the faculty at Miami-Dade Community College, and is presently a member of the School of Computing and Information Sciences at Florida International University. His published textbooks include COBOL for the IBM Personal Computer, Assembly Language for Intel-Based Computers, C++ and Object-Oriented Programming, and Advanced Visual Basic .NET.
xxv
Attention Students
Installing Visual Basic To complete the tutorials and programming problems in this book, you need to install Visual Basic 2012 on your computer. When purchased new, this textbook is packaged with a Microsoft DVD that contains Visual Studio 2012 Express for Windows Desktop. Install this on your computer before starting any of the book’s tutorials.
If you plan to work through Chapter 11, you will also need to install Visual Web Devel- oper 2012 Express, which is available on the accompanying Microsoft DVD.
If your book does not have the accompanying Microsoft DVD, you can download both Visual Studio 2012 Express for Windows Destktop and Visual Web Developer 2012 Express from the following Web site:
http://www.microsoft.com/express/Downloads/
NOTE: If you are working in your school’s computer lab, there is a good chance that Microsoft Visual Studio has been installed, rather than Visual Studio Express. If this is the case, your instructor will show you how to start Visual Studio. The tutorials in this book can be completed with either Visual Studio 2012 or Visual Studio 2012 Express for Windows Desktop.
Installing the Student Sample Program Files The Student Sample Program files that accompany this book are available for download from the book's companion Web site at:
http://www.pearsonhighered.com/gaddisvb
These files are required for many of the book’s tutorials. Simply download the Student Sample Program files to a location on your hard drive where you can easily access them.
http://www.microsoft.com/express/Downloads/
http://www.pearsonhighered.com/gaddisvb
This page intentionally left blank
Through the power of practice and immediate personalized
feedback, MyProgrammingLab improves your performance.
Learn more at www.myprogramminglab.com
get with the programming
MyProgrammingLab™
www.myprogramminglab.com
This page intentionally left blank
1
TOPICS
Introduction to Programming and Visual Basic
C H
A P
T E
R
Microsoft Visual Basic is a powerful software development system for creating applica- tions that run on the Windows operating system. With Visual Basic, you can do the following:
• Create applications with graphical windows, dialog boxes, and menus • Create applications that work with databases • Create Web applications and applications that use Internet technologies • Create applications that display graphics
Visual Basic, which is commonly referred to as VB, is a favorite tool among professional programmers. It provides tools to visually design an application’s appearance, a modern programming language, and access to the latest Microsoft technologies. Powerful appli- cations can be created with Visual Basic in a relatively short period of time.
Before plunging into learning Visual Basic, we will review the fundamentals of computer hardware and software, and then become familiar with the Visual Studio programming environment.
1
1.1 Computer Systems: Hardware and Software
1.2 Programs and Programming Languages
1.3 More about Controls and Programming
1.4 The Programming Process
1.5 Visual Studio and Visual Studio Express (the Visual Basic Environment)
2 Chapter 1 Introduction to Programming and Visual Basic
Computer Systems: Hardware and Software
CONCEPT: Computer systems consist of similar hardware devices and hard- ware components. This section provides an overview of computer hardware and software organization.
Hardware The term hardware refers to a computer’s physical components. A computer, as we gener- ally think of it, is not an individual device, but rather a system of devices. Like the instruments in a symphony orchestra, each device plays its own part. A typical computer system consists of the following major components:
1. The central processing unit (CPU) 2. Main memory 3. Secondary storage devices 4. Input devices 5. Output devices
The organization of a computer system is shown in Figure 1-1.
1.1
Input Devices
Output Devices
Secondary Storage Devices
Central Processing Unit
Main Memory (RAM)
Figure 1-1 The organization of a computer system
1. The CPU
When a computer is performing the tasks that a program tells it to do, we say that the computer is running or executing the program. The central processing unit, or CPU, is the part of a computer that actually runs programs. The CPU is the most important component in a computer because without it, the computer could not run software.
1.1 Computer Systems: Hardware and Software 3
A program is a set of instructions that a computer’s CPU follows to perform a task. The program’s instructions are stored in the computer’s memory, and the CPU’s job is to fetch those instructions, one by one, and carry out the operations that they command. In mem- ory, the instructions are stored as a series of binary numbers. A binary number is a se- quence of 1s and 0s, such as
11011011
This number has no apparent meaning to people, but to the computer it might be an instruction to multiply two numbers or read another value from memory.
2. Main Memory
You can think of main memory as the computer’s work area. This is where the computer stores a program while the program is running, as well as the data that the program is working with. For example, suppose you are using a word processing program to write an essay for one of your classes. While you do this, both the word processing program and the essay are stored in main memory.
Main memory is commonly known as random-access memory, or RAM. It is called this because the CPU is able to quickly access data stored at any random location in RAM. RAM is usually a volatile type of memory that is used only for temporary storage while a program is running. When the computer is turned off, the contents of RAM are erased. Inside your computer, RAM is stored in microchips.
3. Secondary Storage
The most common type of secondary storage device is the disk drive. A disk drive stores data by magnetically encoding it onto a circular disk. Most computers have a disk drive mounted inside their case. External disk drives, which connect to one of the computer’s communication ports, are also available. External disk drives can be used to create backup copies of important data or to move data to another computer.
In addition to external disk drives, many types of devices have been created for copying data, and for moving it to other computers. For many years floppy disk drives were pop- ular. A floppy disk drive records data onto a small floppy disk, which can be removed from the drive. The use of floppy disk drives has declined dramatically in recent years, in favor of superior devices such as USB drives. USB drives are small devices that plug into the computer’s USB (universal serial bus) port, and appear to the system as a disk drive. USB drives, which use flash memory to store data, are inexpensive, reliable, and small enough to be carried in your pocket.
Optical devices such as the CD (compact disc) and the DVD (digital versatile disc) are also popular for data storage. Data is not recorded magnetically on an optical disc, but is en- coded as a series of pits on the disc surface. CD and DVD drives use a laser to detect the pits and thus read the encoded data. Optical discs hold large amounts of data, and be- cause recordable CD and DVD drives are now commonplace, they are good mediums for creating backup copies of data.
4. Input Devices
Input is any data the computer collects from the outside world. The device that collects the data and sends it to the computer is called an input device. Common input devices are the keyboard, mouse, scanner, and digital camera. Disk drives and CD drives can also be con- sidered input devices because programs and data are retrieved from them and loaded into the computer’s memory.
4 Chapter 1 Introduction to Programming and Visual Basic
5. Output Devices
Output is any data the computer sends to the outside world. It might be a sales report, a list of names, a graphic image, or a sound. The data is sent to an output device, which formats and presents it. Common output devices are monitors and printers. Disk drives and CD recorders can also be considered output devices because the CPU sends data to them in order to be saved.
Software Software refers to the programs that run on a computer. There are two general categories of software: operating systems and application software. An operating system or OS is a set of programs that manages the computer’s hardware devices and controls their processes. Windows, Mac OS, and Linux are all operating systems.
Application software refers to programs that make the computer useful to the user. These programs, which are generally called applications, solve specific problems or perform general operations that satisfy the needs of the user. Word processing, spreadsheet, and database packages are all examples of application software. As you work through this book, you will develop application software using Visual Basic.
Checkpoint
1.1 List the five major hardware components of a computer system.
1.2 What is main memory? What is its purpose?
1.3 Explain why computers have both main memory and secondary storage.
1.4 What are the two general categories of software?
Programs and Programming Languages
CONCEPT: A program is a set of instructions a computer follows in order to perform a task. A programming language is a special language used to write computer programs.
What Is a Program? Computers are designed to follow instructions. A computer program is a set of instructions that enables the computer to solve a problem or perform a task. For example, suppose we want the computer to calculate someone’s gross pay—a Wage Calculator application. Figure 1-2 shows a list of things the computer should do.
Collectively, the instructions in Figure 1-2 are called an algorithm. An algorithm is a set of well-defined steps for performing a task or solving a problem. Notice these steps are sequentially ordered. Step 1 should be performed before Step 2, and so on. It is important that these instructions are performed in their proper sequence.
1.2
1.2 Programs and Programming Languages 5
States and Transitions
It is helpful to think of a running computer program as a combination of states and transi- tions. Each state is represented by a snapshot (like a picture) of the computer’s memory. Using the Wage Calculator application example from Figure 1-2, the following is a memory snapshot taken when the program starts:
In Step 3, the number of hours worked by the user is stored in memory. Suppose the user enters the value 20. A new program state is created:
In Step 6, the hourly pay rate entered by the user is stored in memory. Suppose the user enters the value 25. The following memory snapshot shows the new program state:
Figure 1-2 Program steps—Wage Calculator application
1. Display a message on the screen: How many hours did you work?
2. Allow the user to enter the number of hours worked.
3. Once the user enters a number, store it in memory.
4. Display a message on the screen: How much do you get paid per hour?
5. Allow the user to enter an hourly pay rate.
6. Once the user enters a number, store it in memory.
7. Once both the number of hours worked and the hourly pay rate are entered, multiply the two numbers and store the result in memory as the gross pay.
8. Display a message on the screen that shows the gross pay. The message must include the result of the calculation performed in Step 7.
6 Chapter 1 Introduction to Programming and Visual Basic
In Step 7, the application calculates the amount of money earned, saving it in memory. The following memory snapshot shows the new program state:
The memory snapshot produced by Step 7 represents the final program state.
Programming Languages
In order for a computer to perform instructions such as the wage calculator algorithm, the steps must be converted to a format the computer can process. As mentioned earlier, a pro- gram is stored in memory as a series of binary numbers. These numbers are known as machine language instructions. The CPU processes only instructions written in machine language. Our Wage Calculator application might look like the following at the moment when it is executed by the computer:
10101101110101000111100001101110100011110001110011010101110 etc.
The CPU interprets these binary or machine language numbers as commands. As you might imagine, the process of encoding an algorithm in machine language is tedious and difficult. Programming languages, which use words instead of numbers, were invented to ease this task. Programmers can write their applications in programming language state- ments, and then use special software called a compiler to convert the program into machine language. Names of some popular recent programming languages are shown in Table 1-1. This list is only a small sample—there are thousands of programming languages.
Table 1-1 Popular programming languages
Language Description
Visual Basic, C# Popular programming languages for building Windows and Web applications.
C, C++ Powerful advanced programming languages that emphasize flexibility and fast running times. C++ is also object-oriented.
Java Flexible and powerful programming language that runs on many different computer systems. Often used to teach object-oriented programming.
Python Simple, yet powerful programming language used for graphics and small applications.
PHP Programming language used for creating interactive Web sites.
JavaScript Scripting language used in Web applications that provides rich user interfaces for Web browsers.
What Is a Program Made Of? All programming languages, including Visual Basic, have certain elements in common. Let’s look at the major programming language elements that you will work with when writing a program.
1.2 Programs and Programming Languages 7
Keywords (Reserved Words)
Each high-level language has its own set of words that the programmer must learn in order to use the language. The words that make up a high-level programming language are known as keywords or reserved words. Each keyword has a specific meaning and cannot be used for any other purpose. As you work through this book you will learn many of the Visual Basic keywords and how to use them in a program.
Operators
In addition to keywords, programming languages have operators that perform various op- erations on data. For example, all programming languages have math operators that per- form arithmetic. In Visual Basic, as well as most other languages, the � sign is an operator that adds two numbers. The following would add 12 and 75:
12 + 75
Variables
Programs use variables to store data in memory. A variable is a storage location in memory that is represented by a name. When a value is stored in a variable, it is stored in the com- puter’s memory.
Programmers make up the names for all the variables that they use in a program. You will learn specific rules and guidelines for naming variables in Chapter 3, but for now just re- member that a variable’s name is a single word that indicates what the variable is used for. For example, a program that calculates the sales tax on a purchase might use a variable named tax to hold that value in memory. And a program that calculates the distance from Earth to a star might use a variable named distance to hold that value in memory. When a program stores a value in a variable, the value is actually stored in memory at the loca- tion represented by the variable.
Syntax
In addition to keywords and operators, each language also has its own syntax, which is a set of rules that must be strictly followed when writing a program. The syntax rules dictate how keywords, operators, and various punctuation characters must be used in a program. When you are learning a programming language, you must learn the syntax rules for that particular language.
NOTE: Human languages also have syntax rules. Do you remember when you took your first English class, and you learned all those rules about infinitives, indirect objects, clauses, and so forth? You were learning the syntax of the English language.
Although people commonly violate the syntax rules of their native language when speaking and writing, other people usually understand what they mean. Unfortunately, program compilers do not have this ability. If even a single syntax error appears in a program, the program cannot be compiled or executed.
Statements
The individual instructions that you write in a program are called statements. A program- ming statement can consist of keywords, operators, punctuation, and other allowable pro- gramming elements, arranged in the proper sequence to perform an operation. The statements that are written in a program are commonly called source code, or simply code.
8 Chapter 1 Introduction to Programming and Visual Basic
Procedures
A procedure is a set of programming statements that exist within a program for the purpose of performing a specific task. The program executes the procedure when the task needs to be performed.
Comments (Remarks)
Not everything that the programmer writes in a program is meant to be executed by the computer. Some parts of a program are comments, or remarks, that help the human reader of a program understand the purposes of the program statements. In Visual Basic, any statement that begins with an apostrophe (’) is considered a comment. When the Visual Basic compiler sees a statement that begins with an apostrophe, it recognizes it as a com- ment and it skips over it.
You should always add descriptive comments to your code. The extra time it takes is well spent. Sometimes you (the programmer) will have to reread and understand your own code. Comments are a great way to remind you of what you were thinking when you cre- ated the program. In addition, you may have to modify or maintain code written by another programmer and you will appreciate the time spent to write comments!
Graphical User Interfaces When a computer program is needed to perform a task, the programmer is the person who develops the algorithm, and writes the programming statements that perform the algo- rithm’s steps. Once the program is complete, it is made available to those who need to use it. The people who use the program are known as users.
Although the programmer works directly with a program’s statements, users are typically not concerned with the program’s inner workings. Users want to make sure that they know how to operate the program when it is running, and that the program works as it should. The part of a program that users interact with is known as the user interface. On modern operating systems such as Windows, most of the programs that people use have a graphical user interface, or GUI (pronounced gooey). A graphical user interface typically consists of one or more windows that appear on the computer screen. A window is a rec- tangular area that contains other visual elements such as text, buttons that can be clicked with the mouse, boxes that accept keyboard input, and so forth. Let’s look at an example. Follow the steps in Tutorial 1-1 to run a program that you can download from the book’s companion Website, at www.pearsonhighered.com/gaddisvb.
Tutorial 1-1:
Running the Wage Calculator application
Step 1: Make sure you have downloaded the student sample programs from the text- book’s companion Website, at www.pearsonhighered.com/gaddisvb. If you are working in your school’s computer lab, your instructor will tell you where the files are located.
Step 2: Go to the folder containing the student sample programs for Chapter 1. Double- click the file Wage Calculator.exe (the .exe filename extension may not be visi- ble). The program’s window should display as shown in Figure 1-3. Leave the program running as you continue to read. We will perform operations with the program in Tutorial 1-2.
www.pearsonhighered.com/gaddisvb.
www.pearsonhighered.com/gaddisvb
1.2 Programs and Programming Languages 9
The program that you executed in Tutorial 1-1 calculates an employee’s gross pay. Notice that inside the program’s window (shown in Figure 1-3) there are boxes for entering the number of hours worked and the hourly pay rate. There is also a button that calculates the gross pay when it is clicked with the mouse, and a button that closes the program (stops its execution). All of these elements are part of the program’s GUI, and anyone operating the program will interact with these elements.
In addition to being a programming language, Visual Basic is also a programming envi- ronment that provides tools for creating an application’s graphical user interface. With Visual Basic you can design the appearance of an application’s GUI and write the code that makes the application work.
Objects and Controls
As a student studying Visual Basic, you will frequently encounter two terms: object and control. An object is an item in a program that contains data and has the ability to perform operations. The data that an object contains is referred to as properties, or attributes. The operations that an object can perform are called methods. (Recall that earlier we men- tioned that a procedure is a set of programming statements that exist within a program for the purpose of performing a specific task. A method is a special type of procedure that belongs to an object.)
In the beginning of your studies you will learn how to use many different objects that are provided by Visual Basic to perform various operations in your programs. In Chapter 12, you will learn to define your own objects.
A control is a specific type of object that usually appears in a program’s graphical user in- terface. For example, each of the elements that appear in the user interface in Figure 1-3 is a control. The window that contains the other elements is known as a Form control. The small boxes that accept keyboard input are known as TextBox controls. The areas that simply display text are known as Label controls. The buttons that perform operations when clicked with the mouse are known as Button controls. Figure 1-4 points out each of these controls in the user interface.
Figure 1-3 A graphical user interface
NOTE: Visual Basic is an object-oriented programming (OOP) language. A typical VB application uses numerous objects (such as GUI controls) that work together.
Forms, Controls, and Properties
VideoNote
10 Chapter 1 Introduction to Programming and Visual Basic
Properties
A GUI control’s visual appearance is determined by the control’s properties. A property is simply a piece of data that determines some characteristic of the control. For example, many controls have a Text property that determines the text that is displayed by the con- trol. If you look at Figure 1-4, near the top of the form you see a Label control that displays the text Number of Hours Worked. That Label control’s Text property is set to the value Number of Hours Worked. Just below that Label is another Label control, and its Text property is set to the value Hourly Pay Rate.
Button controls also have a Text property. In Figure 1-4, the leftmost button’s Text prop- erty is set to the value Calculate Gross Pay, and the rightmost button’s Text property is set to the value Close. Forms have a Text property too, which determines the text that is dis- played in the title bar at the top of the form. In Figure 1-4, the form’s Text property is set to Wage Calculator. Part of the process of creating a Visual Basic application is deciding what values to store in each object’s properties.
Event-Driven Programming Programs that operate in a GUI environment must be event-driven. An event is an action that takes place within a program, such as the clicking of a control. All Visual Basic con- trols are capable of detecting various events. For example, a Button control can detect when it has been clicked and a TextBox control can detect when its contents have changed.
Names are assigned to all of the events that can be detected. For instance, when the user clicks a Button control, a Click event occurs. When the contents of a TextBox control changes, a TextChanged event occurs. If you wish for a control to respond to a specific event, you must write a set of programming statements known as an event handler. An event handler is a special type of procedure that executes when a specific event occurs. (Event handlers are also known as event procedures.) If an event occurs, and there is no event handler to respond to that event, the event is ignored.
Part of the Visual Basic programming process is designing and writing event handlers. Tutorial 1-2 demonstrates an event handler using the Wage Calculator application you executed in Tutorial 1-1.
Figure 1-4 Types of controls
Label
Label
Label
Label
Button Button
TextBox
TextBox
Form
Event-Driven Programming
VideoNote
1.3 More about Controls and Programming 11
Tutorial 1-2: Running an application that demonstrates event handlers
Step 1: With the Wage Calculator application from Tutorial 1-1 still running, enter the value 10 in the first TextBox control. This is the number of hours worked.
Step 2: Press the t key. Notice that the cursor moves to the next TextBox control. Enter the value 15. This is the hourly pay rate. The window should look like that shown in Figure 1-5.
Step 3: Click the Calculate Gross Pay button. Notice that in response to the mouse click, the application multiplies the values you entered in the TextBox controls and displays the result in a Label control. This action is performed by an event handler that responds to the button being clicked. The window should look like that shown in Figure 1-6.
Figure 1-6 Gross pay calculated
Step 4: Next, click the Close button. The application responds to this event by termi- nating. This is because an event handler closes the application when the but- ton is clicked.
This simple application demonstrates the essence of event-driven programming. In the next section, we examine the controls and event handlers more closely.
Figure 1-5 Text boxes filled in on the Wage Calculator form
More about Controls and Programming
CONCEPT: As a Visual Basic programmer, you must design and create an application’s GUI elements (forms and other controls) and the programming statements that respond to and/or perform actions (event handlers).
While creating a Visual Basic application, you will spend much of your time doing three things: creating the controls that appear in the application’s user interface, setting the prop- erties of the controls, and writing programming language statements that respond to events and perform other operations. In this section, we take a closer look at these aspects of Visual Basic programming.
1.3
12 Chapter 1 Introduction to Programming and Visual Basic
Table 1-2 Visual Basic controls
Control Type Description
Button A rectangular button-shaped object that performs an action when clicked with the mouse
CheckBox A box that is checked or unchecked when clicked with the mouse
ComboBox A control that is the combination of a ListBox and a TextBox
Form A window, onto which other controls may be placed
GroupBox A rectangular border that functions as a container for other controls
HScrollBar A horizontal scroll bar that, when moved with the mouse, increases or decreases a value
Label A box that displays text that cannot be changed or entered by the user
ListBox A box containing a list of items
PictureBox A control that displays a graphic image
RadioButton A round button that is either selected or deselected when clicked with the mouse
TextBox A rectangular area in which the user can enter text, or the program can display text
VScrollBar A vertical scroll bar that, when moved with the mouse, increases or decreases a value
Visual Basic Controls In the previous section, you saw examples of several GUI elements, or controls. Visual Basic provides a wide assortment of controls for gathering input, displaying informa- tion, selecting values, showing graphics, and more. Table 1-2 lists some of the commonly used controls.
If you have any experience using Microsoft Windows, you are already familiar with most of the controls listed in Table 1-2. The student sample programs (available at www.pearsonhighered.com/gaddisvb) contains a simple demonstration program in Tutorial 1-3 that shows you how a few of them work.
Tutorial 1-3: Running an application that demonstrates various controls
Step 1: Make sure you have downloaded the student sample programs from the text- book’s companion Website, at www.pearsonhighered.com/gaddisvb.
Step 2: Navigate to the the Chap1 folder.
Step 3: Double-click the file Controls Demo.exe. (The .exe extension may not be visible on your system.)
Step 4: Once the program loads and executes, the window shown in Figure 1-7 should appear on the screen.
www.pearsonhighered.com/gaddisvb
www.pearsonhighered.com/gaddisvb
1.3 More about Controls and Programming 13
The Name Property The appearance of a control is determined by its properties. Some properties, however, establish nonvisual characteristics. An example is the control’s Name property. When the
Step 5: The program presents several Visual Basic controls. Experiment with each one, noticing the following actions, which are performed by event handlers:
• When you click the small down arrow ( ) in the ComboBox control, you see a list of pets. When you select one, the name of the pet appears below the combo box.
• When you click the CheckBox control, its text changes to indicate that the check box is checked or unchecked.
• When you click an item in the ListBox control, the name of that item appears below the list box.
• When you select one of the RadioButton controls, the text below them changes to indicate which one you selected. You may only select one at a time.
• You move the horizontal scroll bar (HScrollBar) and the vertical scroll bar (VScrollBar) by doing the following: • Clicking either of the small arrows at each end of the bar • Clicking inside the bar on either side of the slider • Clicking on the slider and while holding down the mouse button, moving
the mouse to the right or left for the horizontal scroll bar, or up or down for the vertical scroll bar.
When you move either of the scroll bars, the text below it changes to a num- ber. Moving the scroll bar in one direction increases the number, and moving it in the other direction decreases the number.
Step 6: Click the Close button to end the application.
Figure 1-7 Control demonstration screen
14 Chapter 1 Introduction to Programming and Visual Basic
Figure 1-8 Wage Calculator controls
Table 1-3 Wage Calculator controls
Control Name Control Type Description
Form1 Form The window that holds all of the application’s other controls Label1 Label Displays the message Number of Hours Worked Label2 Label Displays the message Hourly Pay Rate Label3 Label Displays the message Gross Pay Earned txtHoursWorked TextBox Allows the user to enter the number of hours worked txtPayRate TextBox Allows the user to enter the hourly pay rate lblGrossPay Label Displays the gross pay, after the btnCalcGrossPay button
has been clicked btnCalcGrossPay Button When clicked, multiplies the number of hours worked by the
hourly pay rate btnClose Button When clicked, terminates the application
programmer wishes to manipulate or access a control in a programming statement, he or she must refer to the control by its name.
When you create a control in Visual Basic, it automatically receives a default name. The first Label control created in an application receives the default name Label1. The second Label control created receives the default name Label2, and the default names continue in this fashion. The first TextBox control created in an application is automatically named TextBox1. As you can imagine, the names for each subsequent TextBox control are TextBox2, TextBox3, and so on. You can change the control’s default name to something more descriptive.
Table 1-3 lists all the controls, by name, in the Wage Calculator application (Section 1.2), and Figure 1-8 shows where each is located.
Label1
Label3
Label2
lblGrossPay
btnCalcGrossPay btnClose
txtHoursWorked
txtPayRate
Form1
Control Naming Rules and Conventions Four controls shown in Figure 1-8 (Form1, Label1, Label2, and Label3) still have their default names. The other five controls have programmer-defined names because those controls play an active role in the application’s event handlers, and their names appear in the application’s programming statements. Any control whose name appears in a programming statement should have a descriptive, programmer-defined name.
1.3 More about Controls and Programming 15
NOTE: Some programmers prefer to give all the controls in their application mean- ingful names, including ones whose names do not appear in programming statements.
Although you have a great deal of flexibility in naming controls, you must follow these mandatory rules:
• The first character of a control name must be a letter or an underscore character ( _ ). • After the first character, the remaining characters may be letters, digits, or underscore
( _ ) characters.
It’s important to remember that control names must be one word. They cannot contain spaces. Punctuation marks and other special symbols are also prohibited in control names.
In addition to these mandatory rules, there are three conventions that you should follow when naming controls:
1. The first three letters of the name should be a lowercase prefix indicating the con- trol’s type. In the Wage Calculator application, programmer-defined names use the following standard three-letter prefixes: • lbl indicates a Label control. • txt indicates a TextBox control. • btn indicates a Button control. There are standard prefixes for other controls as well. They are discussed in Chapter 2.
2. The first letter after the prefix should be uppercase. In addition, if the name consists of multiple words, the first letter of each word should be capitalized. This makes the name more readable. For example, txtHoursWorked is easier to read than txthoursworked.
3. The part of the control name that appears after the three-letter prefix should de- scribe the control’s purpose in the application. This makes the control name very helpful to anyone reading the application’s programming statements. For example, it is evident that the btnCalcGrossPay control is a button that calculates the gross pay.
These are not mandatory rules, but they are standard conventions that many Visual Basic programmers follow. You should use these guidelines when naming the controls in your applications as well. Table 1-4 describes several fictitious controls and suggests appropriate programmer-defined names for them.
Table 1-4 Programmer-defined control name examples
Control Description Suggested Name
A text box in which the user enters his or her age txtAge
A button that, when clicked, calculates the total of an order btnCalcTotal
A label that is used to display the distance from one city to another lblDistance
A text box in which the user enters his or her last name txtLastName
A button that, when clicked, adds a series of numbers btnAddNumbers
16 Chapter 1 Introduction to Programming and Visual Basic
Checkpoint
1.5 What is an algorithm?
1.6 Why were computer programming languages invented?
1.7 What is an object? What is a control?
1.8 What does event-driven mean?
1.9 What is a property?
1.10 Why should the programmer change the name of a control from its default name?
1.11 If a control has the programmer-defined name txtRadius, what type of control is it?
1.12 What is the default name given to the first TextBox control created in an application?
1.13 Is txtFirst+LastName an acceptable control name? Why or why not?
The Programming Process
CONCEPT: The programming process consists of several steps, which include designing, creating, testing, and debugging activities.
Imagine building a bridge without a plan. How could it be any easier to create a complex computer program without designing its appearance and behavior? In this section, we in- troduce some of the most important knowledge you will gain from this book—how to begin creating a computer application. Regardless of which programming language you use in the future, good program design principles always apply.
Steps for Developing a Visual Basic Application 1. Clearly define what the application is to do. 2. Visualize the application running on the computer and design its user interface. 3. Determine the controls needed. 4. Define the values of each control’s relevant properties. 5. Determine the event handlers and other code needed for each control. 6. Create a flowchart or pseudocode version of the code. 7. Check the flowchart or pseudocode for errors. 8. Start Visual Studio and create the forms and other controls identified in Step 3. 9. Use the flowcharts or pseudocode from Step 6 to write the actual code.
10. Attempt to run the application. Correct any syntax errors found and repeat this step as many times as necessary.
11. Once all syntax errors are corrected, run the program with test data for input. Cor- rect any runtime errors. Repeat this step as many times as necessary.
These steps emphasize the importance of planning. Just as there are good ways and bad ways to paint a house, there are good ways and bad ways to write a program. A good pro- gram always begins with planning.
1.4
1.4 The Programming Process 17
With the Wage Calculator application as our example, let’s look at each of these steps in greater detail.
1. Clearly define what the application is to do.
This step requires that you identify the purpose of the application, the information to be input, the processing to take place, and the desired output. For example, the requirements for the Wage Calculator application are as follows:
Purpose: To calculate the user’s gross pay Input: Number of hours worked, hourly pay rate Process: Multiply number of hours worked by hourly pay rate. The result is the
user’s gross pay Output: Display a message indicating the user’s gross pay
2. Visualize the application running on the computer and design its user interface.
Before you create an application on the computer, first you should create it in your mind. Step 2 is the visualization of the program. Try to imagine what the computer screen will look like while the application is running. Then, sketch the form or forms in the applica- tion. For instance, Figure 1-9 shows a sketch of the form presented by the Wage Calculator application.
Figure 1-9 Sketch of the Wage Calculator form
Number of Hours Worked
Hourly Pay Rate
Gross Pay Earned: $0.00