Contents in Brief Preface xvii Chapter 1 Introduction to Programming and Visual Basic 1 Chapter 2 Creating Applications with Visual Basic 43 Chapter 7 Multiple Forms, Modules, and Menus
Trang 3Visual Basic ®
2012
S i x t h E d i t i o n
Trang 5Visual Basic ®
2012
S i x t h E d i t i o n
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 TorontoDelhi Mexico City Sa~o Paulo Sydney Hong Kong Seoul Singapore Taipei Tokyo
Trang 6Editorial 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
Trang 7Contents in Brief
Preface xvii
Chapter 1 Introduction to Programming and Visual Basic 1
Chapter 2 Creating Applications with Visual Basic 43
Chapter 7 Multiple Forms, Modules, and Menus 403
Chapter 9 Files, Printing, and Structures 541
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
Trang 9Contents
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
Trang 10TUTORIAL 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 Focusmethod 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
Trang 11TUTORIAL 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
Trang 12TUTORIAL 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
Trang 13TUTORIAL 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
Trang 14TUTORIAL 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
Trang 15TUTORIAL 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
Trang 16Chapter 1 Forms, Controls, and Properties, p 9
Event-Driven Programming, p 10Tutorial 1-4 Walkthrough, p 21Tutorial 1-5 Walkthrough, p 25Tutorial 1-6 Walkthrough, p 34Solving the Sales Tax Problem, p 41
Chapter 2 Tutorial 2-1 Walkthrough, p 46
Tutorial 2-2 Walkthrough, p 48Tutorial 2-3 Walkthrough, p 50Tutorial 2-5 Walkthrough, p 53Tutorial 2-6 Walkthrough, p 57Responding to Events, p 63Tutorial 2-8 Walkthrough, p 64Tutorial 2-9 Walkthrough, p 68Tutorial 2-10 Walkthrough, p 76Using IntelliSense, p 84
The Name and Address Problem, p 107
Chapter 3 Tutorial 3-2 Walkthrough, p 115
Introduction to Variables, p 124Problem Solving with Variables, p 136Converting TextBox Input, p 149Exception Demonstration, p 161Tutorial 3-10 Walkthrough, p 164
Building a Kayak Rental Application, p 195
The Miles per Gallon Calculator Problem, p 202
Chapter 4 The If ThenStatement, p 211
The If Then ElseStatement, p 217Tutorial 4-2 Walkthrough, p 218
Tutorial 4-3 Walkthrough, p 221Tutorial 4-4 Walkthrough, p 227Validating Input with TryParse, p 254
Improving the Kayak Rental Application, p 272
The Roman Numeral Converter Problem, p 277
Chapter 5 The Do WhileLoop, p 296
Tutorial 5-2 Walkthrough, p 297Tutorial 5-3 Walkthrough, p 301The For NextLoop, p 310
Improving the Kayak Rental Application, p 340
The Sum of Numbers Problems, p 346
Trang 17Passing Arguments to Procedures, p 363Functions, p 371
Tutorial 6-5 Walkthrough, p 372Tutorial 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 411Creating 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 477Tutorial 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 549Tutorial 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 614Tutorial 10-4 Walkthrough, p 621
Adding a Database to the Kayak Rental Application, p 669
The Karate Members Grid Problem, p 671The Karate Payments by a Single Member Problem, p 674
Chapter 11 Creating a Simple Web Application, p 682
Tutorial 11-2 Walkthrough, p 692Building a Movie Tracking Application, p 728The Stadium Seating Problem, p 731
Chapter 12 Creating a Class, p 737
Collections, p 753Tutorial 12-2 Walkthrough, p 760Kayak Rentals with Classes, p 783The Motor Class Problem, p 791
Trang 19Preface
Welcome to Starting Out with Visual Basic 2012, Sixth Edition This book is
intended for use in an introductory programming course It is designed for
stu-dents who have no prior programming background, but even experienced stustu-dents 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
Trang 20The 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 additionalfeatures and enhancements Visual Basic versions offered backward compatibility, wherecode written in an older version was compatible with a newer version of the Visual Basicdevelopment 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 systemand provide a secure, managed environment in which programs can execute In addition
to providing a managed environment for applications to run, NET also provided newtechnologies for creating Internet-based programs and programs that provide servicesover the Web Along with the introduction of the NET platform, Microsoft introduced anew version of Visual Basic known as VB NET 2002, which allowed programmers towrite 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 atotally new programming environment, and the Visual Basic language was dramaticallyrevised The changes were substantial enough that programs written in earlier versions ofVisual 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 theresults were not always perfect Although this was frustrating for some Visual Basicdevelopers, Microsoft reasoned the changes were necessary to ensure that Visual Basiccontinued to evolve as a modern, professional programming environment
Microsoft has continued to enhance and improve Visual Basic by regularly releasing newversions The versions, which are named after the year in which they were released, areVisual Basic 2003, Visual Basic 2005, Visual Basic 2008, Visual Basic 2010, and the mostrecent version, Visual Basic 2012
This book is written for Visual Basic 2012 This version of Visual Basic includes severalenhancements 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 notcovered The following list summarizes some of the most significant new features of VB2012:
• Introduction of the Async method modifier and the Await statement, for nous programming
asynchro-• Introduction of iterators, to perform custom iterations over collections, lists, andarrays
• A new call hierarchy window in Visual Studio that allows you to display all calls toand from a selected method, property, or constructor
• Caller information attributes that allow you to obtain information about the caller
Organization of the Text
The text teaches Visual Basic step-by-step Each chapter covers a major set of programmingtopics, 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 existingsequence, there is some flexibility The following diagram suggests possible sequences ofinstruction
Trang 21Chapters 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 ElseIfstatements Logical operators are introduced, and the Select
Casestatement 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
Trang 22that are not associated with a specific form It covers creating a menu system, with mands and submenus that the user may select from.
com-Chapter 8: Arrays and More This chapter discusses both single dimension and
multi-dimensional variable arrays Many array programming techniques are presented, such assumming all the elements in an array, summing all the rows or columns in a two-dimensionalarray, searching an array for a specific value, sorting arrays, and using parallel arrays TheEnabled 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 TheOpenFileDialog, SaveFileDialog, FontDialog, and ColorDialog controls are introduced.The PrintDocument control is discussed, with a special focus on printing reports Thechapter 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 andwrite applications that display, sort, and update database data The Structured QueryLanguage (SQL) is introduced An application that shows how to display database data inlist boxes, text boxes, labels, and combo box is presented The chapter concludes with anoverview 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 WebDeveloper, the student learns how to use Web server controls and Web forms to buildinteractive, 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 mining its classes is discussed, and techniques for creating objects, properties, and methodsare introduced Collections are presented as structures for holding groups of objects The
deter-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 ducing inheritance, and shows how to create a class that is based on an existing class
intro-Appendix A: Advanced User Interface Controls and Techniques Discusses
many of the more advanced controls available in Visual Basic, as well as several helpfulprogramming 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 studentcreates 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 allCheckpoints 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 thatmay be caused by these functions and methods are also listed
Trang 23Appendix 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
Trang 24The 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 testsFor information on how to access these supplements, visit the Pearson EducationInstructor 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, tics, and syntax of programming Through practice exercises and immediate, personalizedfeedback, 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 courseconsists 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 theircode submissions and offers targeted hints that enable students to figure out what wentwrong For instructors, a comprehensive gradebook tracks correct and incorrect answers andstores the code inputted by students for review
seman-For a full demonstration, to see feedback from instructors and students, or to get startedusing 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 Theauthors would like to thank the following faculty reviewers for their helpful suggestionsand 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
Trang 25Achla 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
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
University
Juan Marquez, Mesa Community College Gary Marrer, Glendale Community College Norman McNeal, Dakota County Technical
Robert Nields, Cincinnati State Community and
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
Trang 26About 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 atHaywood 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 byPearson 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 CommunityCollege, 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.
Trang 27Attention 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/
N O T E : 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
Trang 29Through the power of practice and immediate personalized feedback, MyProgrammingLab improves your performance.
get with the programming
Trang 31T O P I C S
Introduction to Programming and Visual Basic
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
Trang 32Computer Systems: Hardware and Software
C O N C E P T: Computer systems consist of similar hardware devices and
hard-ware components This section provides an overview of computer hardware and software organization.
HardwareThe 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 theinstruments in a symphony orchestra, each device plays its own part A typical computersystem consists of the following major components:
1 The central processing unit (CPU)
2 Main memory
3 Secondary storage devices
4 Input devices
5 Output devicesThe 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
Trang 33A 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
Trang 345 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 CDrecorders can also be considered output devices because the CPU sends data to them inorder 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 performgeneral operations that satisfy the needs of the user Word processing, spreadsheet, anddatabase packages are all examples of application software As you work through thisbook, 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
C O N C E P T: 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 instructionsthat 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 aresequentially ordered Step 1 should be performed before Step 2, and so on It is importantthat these instructions are performed in their proper sequence
1.2
Trang 35States 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
Trang 36In 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, thesteps 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 youmight 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 inTable 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’slook at the major programming language elements that you will work with when writing aprogram
Trang 37Keywords (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 taxto hold that value in memory And a program that calculates the distance from
Earth to a star might use a variable named distanceto 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
N O T E : 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.
Trang 38A 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, anystatement that begins with an apostrophe (’) is considered a comment When the VisualBasic 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 wellspent Sometimes you (the programmer) will have to reread and understand your owncode 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 byanother 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 whodevelops 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 typicallynot concerned with the program’s inner workings Users want to make sure that theyknow 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 clickedwith 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’scompanion Website, at www.pearsonhighered.com/gaddisvb
Tutorial 1-1:
Running the Wage Calculator application
text-book’s companion Website, at www.pearsonhighered.com/gaddisvb If you areworking in your school’s computer lab, your instructor will tell you where thefiles are located
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 theprogram running as you continue to read We will perform operations with theprogram in Tutorial 1-2
Trang 39The 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
N O T E : 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
Trang 40A 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 propprop-erty 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 ProgrammingPrograms 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 trols are capable of detecting various events For example, a Button control can detect when
con-it has been clicked and a TextBox control can detect when con-its contents have changed Names are assigned to all of the events that can be detected For instance, when the userclicks a Button control, a Click event occurs When the contents of a TextBox controlchanges, 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
Event-Driven
Programming
VideoNote