Microsoft Visual Basic 2010 Step by Step eBook

Microsoft Visual Basic 2010 Step by Step eBook
●●●●●●●●●●●
How to access
your CD files
The print edition of this book includes a CD. To access the
CD files, go to http://aka.ms/626690/files, and look for the
Downloads tab.
Note: Use a desktop web browser, as files may not be
accessible from all ereader devices.
Questions? Please contact: mspinput@microsoft.com Microsoft Press
PUBLISHED BY
Microsoft Press
A Division of Microsoft Corporation
One Microsoft Way
Redmond, Washington 98052-6399
Copyright © 2010 by Michael Halvorson
All rights reserved. No part of the contents of this book may be reproduced or transmitted in any form or by any means
without the written permission of the publisher.
Library of Congress Control Number: 2010924441
ISBN: 978-0-7356-2669-0
Printed and bound in the United States of America.
4 5 6 7 8 9 10 11 12 QG 7 6 5 4 3 2
Distributed in Canada by H.B. Fenn and Company Ltd.
A CIP catalogue record for this book is available from the British Library.
Microsoft Press books are available through booksellers and distributors worldwide. For further information about
international editions, contact your local Microsoft Corporation office or contact Microsoft Press International directly
at fax (425) 936-7329. Visit our Web site at www.microsoft.com/mspress. Send comments to mspinput@microsoft.com.
Microsoft, Microsoft Press, Access, ActiveX, Arc, Azure, DataTips, Excel, Expression, Halo, IntelliSense, Internet Explorer,
MS, MSDN, MS-DOS, PowerPoint, SharePoint, Silverlight, SQL Server, Visual Basic, Visual C#, Visual C++, Visual
InterDev, Visual Studio, Windows, Windows Azure, Windows Server, Windows Vista and Zoo Tycoon are either registered
trademarks or trademarks of Microsoft Corporation in the United States and/or other countries. Other product and company
names mentioned herein may be the trademarks of their respective owners.
The example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted
herein are fictitious. No association with any real company, organization, product, domain name, e-mail address, logo,
person, place, or event is intended or should be inferred.
This book expresses the author’s views and opinions. The information contained in this book is provided without any express,
statutory, or implied warranties. Neither the authors, Microsoft Corporation, nor its resellers, or distributors will be held
liable for any damages caused or alleged to be caused either directly or indirectly by this book.
Acquisitions Editor: Ben Ryan
Developmental Editor: Devon Musgrave
Project Editor: Valerie Woolley
Editorial Production: Christian Holdener, S4Carlisle Publishing Services
Technical Reviewer: Technical Review services provided by Content Master, a member of CM Group, Ltd.
Cover: Tom Draper Design
Body Part No. X16-88509
[2012-03-16]
For Henry
Contents at a Glance
Part I
1 Exploring the Visual Studio Integrated Development
Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2 Writing Your First Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
3 Working with Toolbox Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
4 Working with Menus, Toolbars, and Dialog Boxes . . . . . . . . . . . . 97
Part II
Getting Started with Microsoft Visual Basic 2010
Programming Fundamentals
5 Visual Basic Variables and Formulas,
and the .NET Framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
6 Using Decision Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
7 Using Loops and Timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
8 Debugging Visual Basic Programs . . . . . . . . . . . . . . . . . . . . . . . . 209
9 Trapping Errors by Using Structured Error Handling . . . . . . . . . 227
10 Creating Modules and Procedures . . . . . . . . . . . . . . . . . . . . . . . . 247
11 Using Arrays to Manage Numeric and String Data . . . . . . . . . . . 273
12 Working with Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
13 Exploring Text Files and String Processing . . . . . . . . . . . . . . . . . . 313
Part III Designing
14
15
16
17
the User Interface
Managing Windows Forms and Controls at Run Time . . . . . . . .
Adding Graphics and Animation Effects . . . . . . . . . . . . . . . . . . .
Inheriting Forms and Creating Base Classes . . . . . . . . . . . . . . . .
Working with Printers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Part IV Database
351
375
393
415
and Web Programming
18 Getting Started with ADO.NET . . . . . . . . . . . . . . . . . . . . . . . . . . . 441
19 Data Presentation Using the DataGridView Control . . . . . . . . . 467
20 Creating Web Sites and Web Pages by Using Visual
Web Developer and ASP.NET . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491
v
Table of Contents
Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii
Part I
Getting Started with Microsoft Visual Basic 2010
1 Exploring the Visual Studio Integrated Development
Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
The Visual Studio Development Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
The Visual Studio Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
The Designer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Running a Visual Basic Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
The Properties Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Moving and Resizing the Programming Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Moving and Resizing Tool Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Docking Tool Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Hiding Tool Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Switching Among Open Files and Tools
by Using the IDE Navigator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Opening a Web Browser Within Visual Studio . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
Getting Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Managing Help Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Using F1 Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
Customizing IDE Settings to Match
Step-by-Step Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Setting the IDE for Visual Basic Development . . . . . . . . . . . . . . . . . . . . . . 29
Checking Project and Compiler Settings . . . . . . . . . . . . . . . . . . . . . . . . . . 31
One Step Further: Exiting Visual Studio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Chapter 1 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
What do you think of this book? We want to hear from you!
Microsoft is interested in hearing your feedback so we can continually improve our books and learning
resources for you. To participate in a brief online survey, please visit:
www.microsoft.com/learning/booksurvey/
vii
viii
Table of Contents
2 Writing Your First Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
Lucky Seven: Your First
Visual Basic Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
Programming Steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
Creating the User Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
Setting the Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
The Picture Box Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
Writing the Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
A Look at the Button1_Click
Procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
Running Visual Basic Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
Sample Projects on Disk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
Building an Executable File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
Deploying Your Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
One Step Further: Adding to a Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
Chapter 2 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
3 Working with Toolbox Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
The Basic Use of Controls: The Hello
World Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
Using the DateTimePicker Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
The Birthday Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
Controls for Gathering Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
Using Group Boxes and Radio Buttons . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
Processing Input with List Boxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
A Word About Terminology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
One Step Further: Using the LinkLabel Control . . . . . . . . . . . . . . . . . . . . . . . . . . 91
Chapter 3 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
4 Working with Menus, Toolbars, and Dialog Boxes . . . . . . . . . . . . 97
Adding Menus by Using the MenuStrip Control . . . . . . . . . . . . . . . . . . . . . . . . . 97
Adding Access Keys to Menu Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
Processing Menu Choices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
Adding Toolbars with the ToolStrip Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
Using Dialog Box Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
Event Procedures That Manage Common
Dialog Boxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
One Step Further: Assigning Shortcut Keys to Menus . . . . . . . . . . . . . . . . . . . 117
Chapter 4 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
Table of Contents
Part II
Programming Fundamentals
5 Visual Basic Variables and Formulas,
and the .NET Framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
The Anatomy of a Visual Basic Program Statement . . . . . . . . . . . . . . . . . . . . . 123
Using Variables to Store Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
Setting Aside Space for Variables: The Dim Statement . . . . . . . . . . . . . 124
Implicit Variable Declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
Using Variables in a Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
Using a Variable to Store Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
Using a Variable for Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
Working with Specific Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
Constants: Variables That Don’t Change . . . . . . . . . . . . . . . . . . . . . . . . . . 142
Working with Visual Basic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
Basic Math: The +, –, *, and / Operators . . . . . . . . . . . . . . . . . . . . . . . . . . 144
Using Advanced Operators: \, Mod, ^, and & . . . . . . . . . . . . . . . . . . . . . 147
Working with Math Methods in the .NET Framework . . . . . . . . . . . . . . . . . . . 152
One Step Further: Establishing Order of Precedence . . . . . . . . . . . . . . . . . . . . 155
Using Parentheses in a Formula . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
Chapter 5 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
6 Using Decision Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
Event-Driven Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
Using Conditional Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
If . . . Then Decision Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
Testing Several Conditions in an If . . . Then
Decision Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
Using Logical Operators in Conditional Expressions . . . . . . . . . . . . . . . 167
Short-Circuiting by Using AndAlso and OrElse . . . . . . . . . . . . . . . . . . . . 169
Select Case Decision Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
Using Comparison Operators with a Select
Case Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
One Step Further: Detecting Mouse Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
Chapter 6 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
7 Using Loops and Timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
Writing For . . . Next Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
Using a Counter Variable in a Multiline TextBox Control . . . . . . . . . . . . . . . . . 183
Creating Complex For . . . Next Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
Using a Counter That Has Greater Scope . . . . . . . . . . . . . . . . . . . . . . . . . 189
ix
x
Table of Contents
Writing Do Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
Avoiding an Endless Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
The Timer Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
Creating a Digital Clock by Using a Timer Control . . . . . . . . . . . . . . . . . . . . . . 197
Using a Timer Object to Set a Time Limit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
One Step Further: Inserting Code Snippets . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
Chapter 7 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
8 Debugging Visual Basic Programs . . . . . . . . . . . . . . . . . . . . . . . . 209
Finding and Correcting Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
Three Types of Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
Identifying Logic Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
Debugging 101: Using Debugging Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
Tracking Variables by Using a Watch Window . . . . . . . . . . . . . . . . . . . . . . . . . . 217
Visualizers: Debugging Tools That Display Data . . . . . . . . . . . . . . . . . . . . . . . . 220
Using the Immediate and Command Windows . . . . . . . . . . . . . . . . . . . . . . . . . 221
Switching to the Command Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
One Step Further: Removing Breakpoints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
Chapter 8 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
9 Trapping Errors by Using Structured Error Handling . . . . . . . . . 227
Processing Errors by Using the Try . . . Catch Statement . . . . . . . . . . . . . . . . . . 227
When to Use Error Handlers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
Setting the Trap: The Try . . . Catch Code Block . . . . . . . . . . . . . . . . . . . . 229
Path and Disc Drive Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
Writing a Disc Drive Error Handler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
Using the Finally Clause to Perform Cleanup Tasks . . . . . . . . . . . . . . . . . . . . . . 234
More Complex Try . . . Catch Error Handlers . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
The Exception Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
Specifying a Retry Period . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
Using Nested Try . . . Catch Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242
Comparing Error Handlers with Defensive
Programming Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242
One Step Further: The Exit Try Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
Chapter 9 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244
10 Creating Modules and Procedures . . . . . . . . . . . . . . . . . . . . . . . . 247
Working with Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247
Creating a Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248
Working with Public Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251
Table of Contents
Creating Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
Writing Function Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
Function Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
Calling a Function Procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
Using a Function to Perform a Calculation . . . . . . . . . . . . . . . . . . . . . . . . 258
Writing Sub Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
Sub Procedure Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
Calling a Sub Procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
Using a Sub Procedure to Manage Input . . . . . . . . . . . . . . . . . . . . . . . . . 264
One Step Further: Passing Arguments by Value
and by Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268
Chapter 10 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
11 Using Arrays to Manage Numeric and String Data . . . . . . . . . . . 273
Working with Arrays of Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
Creating an Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274
Declaring a Fixed-Size Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
Setting Aside Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
Working with Array Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
Declaring an Array and Assigning It Initial Values . . . . . . . . . . . . . . . . . . 278
Creating a Fixed-Size Array to Hold Temperatures . . . . . . . . . . . . . . . . . 279
Creating a Dynamic Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283
Preserving Array Contents by Using ReDim Preserve . . . . . . . . . . . . . . . . . . . . 287
Using ReDim for Three-Dimensional Arrays . . . . . . . . . . . . . . . . . . . . . . 288
One Step Further: Processing Large Arrays
by Using Methods in the Array Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288
The Array Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288
Chapter 11 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
12 Working with Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
Working with Object Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
Referencing Objects in a Collection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
Writing For Each . . . Next Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
Experimenting with Objects in the Controls Collection . . . . . . . . . . . . . 299
Using the Name Property in a For Each . . . Next Loop . . . . . . . . . . . . . . 302
Creating Your Own Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
Declaring New Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
One Step Further: VBA Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309
Entering the Word Macro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310
Chapter 12 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
xi
xii
Table of Contents
13 Exploring Text Files and String Processing . . . . . . . . . . . . . . . . . . 313
Reading Text Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
The My Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314
The StreamReader Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
Using the ReadAllText Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
Writing Text Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321
The WriteAllText Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321
The StreamWriter Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322
Using the WriteAllText Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323
Processing Strings with the String Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326
Sorting Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329
Working with ASCII Codes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
Sorting Strings in a Text Box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331
Examining the Sort Text Program Code . . . . . . . . . . . . . . . . . . . . . . . . . . 334
Protecting Text with Basic Encryption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
One Step Further: Using the Xor Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340
Examining the Encryption Program Code . . . . . . . . . . . . . . . . . . . . . . . . 342
Chapter 13 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345
Part III Designing
the User Interface
14 Managing Windows Forms and Controls at Run Time . . . . . . . . 351
Adding New Forms to a Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351
How Forms Are Used . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352
Working with Multiple Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352
Using the DialogResult Property in the Calling Form . . . . . . . . . . . . . . . 358
Positioning Forms on the Windows Desktop . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
Minimizing, Maximizing, and Restoring Windows . . . . . . . . . . . . . . . . . 364
Adding Controls to a Form at Run Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
Organizing Controls on a Form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
One Step Further: Specifying the Startup Object . . . . . . . . . . . . . . . . . . . . . . . 371
Chapter 14 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373
15 Adding Graphics and Animation Effects . . . . . . . . . . . . . . . . . . . 375
Adding Artwork by Using
the System.Drawing Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
Using a Form’s Coordinate System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
The System.Drawing.Graphics Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
Using the Form’s Paint Event . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378
Table of Contents
Adding Animation to Your Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 380
Moving Objects on the Form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 380
The Location Property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381
Creating Animation by Using a Timer Object . . . . . . . . . . . . . . . . . . . . . 382
Expanding and Shrinking Objects While a Program Is Running . . . . . . . . . . . 386
One Step Further: Changing Form Transparency . . . . . . . . . . . . . . . . . . . . . . . 388
Chapter 15 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 390
16 Inheriting Forms and Creating Base Classes . . . . . . . . . . . . . . . . 393
Inheriting a Form by Using the Inheritance Picker . . . . . . . . . . . . . . . . . . . . . . 393
Creating Your Own Base Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399
Adding a New Class to Your Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401
One Step Further: Inheriting a Base Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408
Chapter 16 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412
17 Working with Printers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415
Using the PrintDocument Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415
Printing Text from a Text Box Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420
Printing Multipage Text Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424
One Step Further: Adding Print Preview and Page Setup Dialog Boxes . . . . 430
Chapter 17 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437
Part IV Database
and Web Programming
18 Getting Started with ADO.NET . . . . . . . . . . . . . . . . . . . . . . . . . . . 441
Database Programming with ADO.NET . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441
Database Terminology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442
Working with an Access Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444
The Data Sources Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452
Using Bound Controls to Display
Database Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 458
One Step Further: SQL Statements, LINQ,
and Filtering Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461
Chapter 18 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466
19 Data Presentation Using the DataGridView Control . . . . . . . . . 467
Using DataGridView to Display Database Records . . . . . . . . . . . . . . . . . . . . . . 467
Formatting DataGridView Cells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 479
Adding a Second Data Grid View Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 482
One Step Further: Updating the Original Database . . . . . . . . . . . . . . . . . . . . . 485
Chapter 19 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488
xiii
xiv
Table of Contents
20 Creating Web Sites and Web Pages by Using Visual
Web Developer and ASP.NET . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491
Inside ASP.NET . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491
Web Pages vs. Windows Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493
Server Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493
HTML Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494
Building a Web Site by Using Visual
Web Developer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495
Considering Software Requirements
for ASP.NET Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495
Using the Web Page Designer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 498
Adding Server Controls to a Web Site . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501
Writing Event Procedures for Web Page Controls . . . . . . . . . . . . . . . . . 504
Customizing the Web Site Template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 509
Displaying Database Records on a Web Page . . . . . . . . . . . . . . . . . . . . . . . . . . 512
One Step Further: Setting Web Site Titles
in Internet Explorer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519
Chapter 20 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 522
Appendix: Where to Go for More Information . . . . . . . . . . . . . . . . . . . . . . . . 523
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 529
What do you think of this book? We want to hear from you!
Microsoft is interested in hearing your feedback so we can continually improve our books and learning
resources for you. To participate in a brief online survey, please visit:
www.microsoft.com/learning/booksurvey/
Acknowledgments
Writing a computer programming book is fascinating because the whole process ­begins well
before the software is actually finished. Authors meet with software developers and ­computer
book publishers, explore product specifications and early releases of the ­software, review
the comments and suggestions that readers of previous editions have ­offered, ­develop
a ­writing plan and schedule, and begin testing their ideas with beta­­versions of the product.
This ­iterative process produces important insights and continues (with mounting fervor) until
the software is complete and the final books are shipped to the printer.
Microsoft Press is a fantastic place to write a computer programming book. At each stage in
the publishing process, talented team members work together to cultivate valuable technical
contacts and resources, build visionary product deployment strategies, explore the hidden
benefits of emerging technologies, and pick the right words and images to describe them.
Microsoft Visual Basic 2010 Step by Step, now in its eighth edition, has benefited significantly
from this dynamic and innovative publishing environment over the years.
I gratefully acknowledge the support and assistance of the following people who helped
to plan, edit, test, produce, and market our book this time (in the order that I worked with
them): Ben Ryan, Devon Musgrave, Valerie Woolley, Susan McClung, and Christian Holdener.
In particular, Valerie Woolley enthusiastically kept my writing on schedule and insured that
our book would fit well in the Step by Step series that Microsoft Press is so well known for. I
am also very grateful to the Microsoft Visual Studio 2010 ­development team for providing me
with beta and release candidate software to work with.
As always, I offer my deepest gratitude and affection to my family for their continued
­support of my writing projects and various academic pursuits.
xv
Introduction
Microsoft Visual Basic 2010 is an important upgrade and enhancement of the popular Visual
Basic programming language and compiler, a technology that enjoys an installed base of
millions of programmers worldwide. Visual Basic 2010 is not a stand-alone product but
a key component of Microsoft Visual Studio 2010—a comprehensive development system
that allows you to create powerful applications for Windows, the Web, handheld devices,
and a host of other environments. Whether you purchase one of the commercial editions of
Visual Studio 2010 (described later in this Introduction) or you download Visual Basic 2010
Express for a free test-drive of the software, you are in for an exciting experience. The latest
features of Visual Basic will increase your productivity and programming prowess, especially
if you enjoy using and integrating information from databases, entertainment media, Web
pages, and Web sites. In addition, an important benefit of learning Visual Basic and the Visual
Studio Integrated Development Environment (IDE) is that you can use many of the same
tools to write programs for Microsoft Visual C++ 2010, Microsoft Visual C# 2010, Microsoft
Visual Web Developer 2010, and other popular products.
Microsoft Visual Basic 2010 Step by Step is a comprehensive introduction to Visual Basic
programming using the Visual Basic 2010 software. I’ve designed this practical, hands-on
tutorial with a variety of skill levels in mind and by following the premise that programmers
learn by doing. In my opinion, the best way to master a complex technology like Visual Basic
is to learn essential programming techniques through carefully prepared tutorials that can
be completed on your own schedule and at your own pace. And although I have significant
experience with college teaching and corporate project management, this book is not
a dry textbook or an “A to Z” programmer’s reference. Instead, it is a practical hands-on
programming tutorial that puts you in charge of your learning, developmental milestones,
and achievements. By using this book, programmers who are new to this topic will learn
Visual Basic software development fundamentals in the context of useful, real-world
applications; and experienced Visual Basic programmers can quickly master the essential
tools and techniques offered in the Visual Basic 2010 upgrade.
Complementing this comprehensive approach is the book’s structure—4 topically organized
parts, 20 chapters, and 56 step-by-step exercises and sample programs. By using this book,
you’ll quickly learn how to create professional-quality Visual Basic 2010 applications for the
Windows operating system and a variety of Web browsers. You’ll also have fun!
xvii
xviii
Introduction
Visual Basic Versions
So how did we get here, anyway? Between 1991 and 1998, Microsoft released six versions
of Visual Basic (versions 1.0 through 6.0), which revolutionized software development for
Windows by introducing event-driven programming to a wide audience based on the
QuickBasic programming language and an IDE. After a significant period of additional
development and innovation, Microsoft released Visual Basic .NET 2002, an object-oriented
programming language closely related to Visual Basic but implemented on the Microsoft
.NET Framework, a comprehensive library of coded solutions intended to be used by most
new applications that run on the Windows platform. As improved versions of Visual Basic
came out in 2003, 2005, and 2008, Visual Basic became a component within the Visual
Studio suite, and significant support was added to the product for database, Internet,
and team development projects, as well as continued improvements to the .NET Framework.
Visual Basic 2010 is now so tightly integrated with Visual Studio that it is available only
as a component in the Visual Studio 2010 programming suite, which includes Visual C#,
Visual C++, Visual Web Developer, and other Microsoft .NET development tools. Since
2005, both Visual Basic and Visual Studio have been marketed without the “.NET” moniker,
although they are still based on the .NET Framework technology.
Visual Studio 2010 is distributed in several different product configurations, including
Professional, Premium, Ultimate, and Express. I’ve written this book to be compatible
with all editions of Visual Basic 2010 and Visual Studio 2010, but especially with the tools
and techniques available in Visual Studio 2010 Professional and Visual Basic 2010 Express.
Although Visual Basic 2010 is similar in many ways to Visual Basic 2008, there are many
important differences and improvements, so I recommend that you complete the exercises
in this book using the Visual Basic 2010 software.
Note The Visual Studio 2010 software is not included with this book. The CD distributed with
most versions of this book contains practice files, sample databases, and other useful information
that requires the Visual Studio 2010 software (sold separately) for use. If you don’t have Visual
Studio, you can download Visual Basic 2010 Express for free, and it contains an amazing palette
of features, though obviously not all the features of Visual Studio Professional, Premium, or
Ultimate. As you complete the exercises in this book, I will note from time to time which features
are unavailable to you if you are using Visual Basic 2010 Express. Also note that if you are using
Visual Basic 2010 Express and you want to complete Chapter 20, “Creating Web Sites and Web
Pages by Using Visual Web Developer and ASP.NET,” you will need to download Visual Web
Developer 2010 Express to complete the exercises. Visual Web Developer is included in Visual
Studio Professional, Premium, and Ultimate, but not Visual Basic Express.
Introduction
xix
Downloading Visual Basic 2010 Express
As noted previously, if you don’t have Visual Studio 2010 Professional, Visual Studio 2010
Premium, or Visual Studio 2010 Ultimate, you can complete most of the exercises in this
book by downloading Visual Basic 2010 Express from the Web for free. This will give you
an opportunity to learn Visual Basic programming and see for yourself if you want to
upgrade to a full release of the Visual Studio software.
To download Visual Basic 2010 Express, complete the following steps:
1. Open a Web browser (such as Internet Explorer), and go to http://www.microsoft.com/
express.
2. Follow the instructions on the screen to download Visual Basic 2010 Express.
On the Express Web site, you will also see an Express product feature chart that compares
the Express product to the full versions of Visual Studio. Although there are some key
differences between the full versions and Visual Basic 2010 Express, many of these
differences have no effect on how you learn the essential techniques and features of
Visual Basic programming. After you experiment with the Express product, you can decide
whether you want to upgrade to one of the full versions of Visual Studio or not. Now, let’s
get started learning about Visual Basic and how this programming course works!
Finding Your Best Starting Point in This Book
This book is designed to help you build skills in a number of essential areas. You can use it if
you’re new to programming, switching from another programming language, or upgrading
from Visual Basic 2008. Use the following table to find your best starting point in this book.
If you are . . .
Follow these steps
New to
programming
1. Install the practice files as described in the section “Installing and Using the
Practice Files,” later in this Introduction.
2. Learn basic skills for using Visual Basic 2010 by working sequentially from
Chapter 1 through Chapter 17.
3. Complete Part IV, “Database and Web Programming,” as your level of
interest or experience dictates.
Upgrading from
Visual Basic 2005
or 2008
1. Install the practice files as described in “Installing and Using the
Practice Files.”
2. Complete Chapters 1 through 4, skim Chapters 5 through 17, and complete
Chapters 18 through 20.
xx
Introduction
If you are . . .
Follow these steps
Upgrading from
Visual Basic 6.0
1. Install the practice files as described in the section “Installing and Using the
Practice Files.”
2. Read Chapters 1 through 4 carefully to learn the new features of the Visual
Studio 2010 development environment.
3. Skim Chapters 5 through 13 to review the fundamentals of event-driven
programming, using variables, and writing decision structures. Give special
attention to Chapters 5, 6, 9, and 12.
4. Work sequentially from Chapters 14 through 20 to learn the new Visual
Basic 2010 features related to user interface design, database programming,
and Web programming.
Referencing
this book after
working through
the chapters
1. Use the index to locate information about specific topics, and use the table
of contents to locate information about general topics.
2. Read the Quick Reference at the end of each chapter for a brief review of
the major tasks in the chapter. The Quick Reference topics are listed in the
same order as they’re presented in the chapter.
Hardware and Software Requirements
You’ll need the following hardware and software to complete the exercises in this book:
n
Windows 7, Windows Vista, Windows XP, Windows Server 2003, or Windows
Server 2008
n
Visual Studio 2010 (Professional, Premium, or Ultimate) or Visual Basic 2010 Express
n
1.6 GHz processor
n
1 GB RAM
n
3 GB of available hard drive space
n
5400 RPM hard disk drive
n
DirectX 9–capable video card that runs at a display resolution of 1024 × 768 or higher
n
DVD drive
You also need to have Administrator-level access to your computer.
Note This book and the practice files were tested using Visual Studio 2010 Professional and
Visual Basic 2010 Express on Windows 7. You might notice a few differences if you’re using
other editions of Visual Studio 2010. In particular, if you’re using Visual Basic 2010 Express, a few
features will be unavailable to you. In addition, all the screen shots in this book were captured
using Windows 7. If you are using another version of Windows or Windows Server, you’ll notice
a few differences in some of the screen shots.
Introduction
xxi
Prerelease Software
This book was reviewed and tested against the Release Candidate of Visual
Studio 2010. The Release Candidate was the last preview before the final release of
Visual Studio 2010. This book is expected to be fully compatible with the final release of
Visual Studio 2010 and Visual Basic 2010. If there are any changes or corrections for this
book, they will be collected and added to an easy-to-access Microsoft Knowledge Base
article on the Web. See “Support for This Book,” later in this Introduction.
Digital Content for Digital Book Readers: If you bought a digital-only edition of this book, you can
enjoy select content from the print edition’s companion CD.
Visit http://www.microsoftpressstore.com/title/9780735626690 to get your downloadable content. This content
is always up-to-date and available to all readers.
Installing and Using the Practice Files
The CD inside this book contains the practice files that you’ll use as you perform the exercises
in the book. For example, when you’re learning how to display database tables on a form
by using the DataGridView control, you’ll open one of the practice files—an academic
database named Faculty2010.accdb—and then use Visual Studio database programming
tools to access the database. By using the practice files, you won’t waste time creating files
that aren’t relevant to the exercise. Instead, you can concentrate on learning how to master
Visual Basic 2010 programming techniques. With the files and the step-by-step instructions
in the chapters, you’ll also learn by doing, which is an easy and effective way to acquire and
remember new skills.
Important Before you break the seal on the CD, be sure that this book matches your version
of the software. This book is designed for use with Visual Studio 2010 and the Visual Basic 2010
programming language. To find out what software you’re running, you can check the product
package, or you can start the software, open a project, and then click About Microsoft Visual
Studio on the Help menu at the top of the screen.
Installing the Practice Files
Installing the practice files on your hard disk requires approximately 10 megabytes (MB) of
disk space. Follow these steps to install the practice files on your computer’s hard disk drive
so that you can use them with the exercises in this book.
1. Remove the CD from the package inside this book and insert it into your CD drive.
Note An End-User License Agreement (EULA) should open automatically. If this
agreement does not appear, you can double-click StartCD.exe on the CD. If you have
Windows 7 or Windows Vista, click Computer on the Start menu, double-click the icon for
your CD drive, and then double-click StartCD.exe.
xxii
Introduction
2. Review the EULA. If you accept the terms, select the Accept option, and then click Next.
A menu appears with options related to the book.
3. Click Practice Files.
4. Follow the on-screen instructions.
Note For best results when using the practice files with this book, accept the preselected
installation location, which by default is C:\Vb10sbs. If you change the installation location,
you’ll need to adjust the paths in several practice files manually to locate essential
components, such as artwork and database files, when you use them. Trust me—it is good
to use the default installation location.
5. When the files have been installed, remove the CD from your drive and replace it in the
package inside the back cover of your book.
If you accepted the default settings, a folder named C:\Vb10sbs has been created on
your hard disk drive, and the practice files have been placed in that folder. You’ll find
one folder in C:\Vb10sbs for each chapter in the book. (Some of the files represent
completed projects, and others will require that you enter some program code.)
If you have trouble running any of the practice files, refer to the text in the book that
­describes those files.
Using the Practice Files
Each chapter in this book explains when and how to use the practice files for that chapter.
When it’s time to use a practice file, the book includes instructions for opening the file.
The chapters are built around scenarios that simulate real programming projects so that you
can easily apply the skills you learn to your own work.
Note Visual Basic 2010 features a new file format for its projects and solutions. Accordingly, you
won’t be able to open the practice files for this book if you’re using an older version of the Visual
Basic or Visual Studio software. To see what version of Visual Basic or Visual Studio you’re using,
click the About command on the Help menu.
Visual Studio is extremely customizable and can be configured to open and save projects
and solutions in different ways. The instructions in this book generally rely on the default
setting for Visual Studio. For more information about how settings within the development
environment affect how you write programs and use the practice files, see the section
“Customizing IDE Settings to Match Step-by-Step Exercises” in Chapter 1, “Exploring the
Visual Studio Integrated Development Environment.”
Introduction
xxiii
For those of you who like to know all the details, here’s a list of the Visual Basic projects
­included on the CD. Each project is located in its own folder and has several support files.
Look at all the things you will be doing!
Project
Description
Chapter 1
MusicTrivia
A simple trivia program that welcomes you to the programming course
and displays a digital photo.
Chapter 2
Lucky7
Your first program—a game that simulates a Las Vegas Lucky Seven slot
­machine.
Chapter 3
Birthday
Uses the DateTimePicker control to pick a date.
CheckBox
Demonstrates the CheckBox control and its properties.
Hello
A Hello World program that demonstrates the Label and TextBox controls.
List Box
Demonstrates the ListBox control for gathering input.
Radio Button
Demonstrates the RadioButton control for gathering input.
WebLink
Demonstrates the LinkLabel control that opens a Web browser in your Visual
Basic application.
Chapter 4
Menu
Demonstrates how to use Visual Studio dialog box controls, toolbars,
and menus.
Chapter 5
Advanced Math
Advanced use of operators for integer division, remainder division,
­exponentiation, and string concatenation.
Basic Math
Basic use of operators for addition, subtraction, multiplication, and division.
Constant Tester
Uses a constant to hold a fixed mathematical entity.
Data Types
Demonstrates Visual Basic fundamental data types and their use with variables.
Framework Math
Demonstrates the .NET Framework classes with mathematical methods.
Input Box
Receives input with the InputBox function.
Variable Test
Declares and uses variables to store information.
Chapter 6
Select Case
Uses a Select . . . Case decision structure and a ListBox control to display
a welcome message in several languages.
User Validation
Uses the If . . . Then . . . Else decision structure and a MaskedTextBox control to
­manage a logon process.
Chapter 7
Celsius
Conversion
Converts temperatures from Fahrenheit to Celsius by using a Do loop.
Digital Clock
A simple digital clock program that demonstrates the Timer control.
xxiv
Introduction
Project
Description
For Loop
Demonstrates using a For . . . Next loop to display text in a TextBox control,
and using the Chr function to create a wrap character.
For Loop Icons
Uses a global counter variable in an event procedure as an alternative to loops.
This program also displays images by using a PictureBox control.
Timed Password
Demonstrates how to use a Timer control to create a logon program with
a password time-out feature.
Windows Version
Snippet
Shows how to use the Insert Snippet command to display the current version of
Windows running on a user’s computer.
Chapter 8
Debug Test
A simulated debugging problem, designed to be solved using the Visual Studio
debugging tools.
Chapter 9
Disc Drive Error
Crashes when a CD or DVD drive is used incorrectly. This project is used as the
basis of a Visual Basic error handler.
Disc Drive
Handler
Completed error handler for loading files that demonstrates the Try . . . Catch
syntax.
Chapter 10
Text Box Sub
A general-purpose Sub procedure that adds items to a list box.
Track Wins
A clean version of the Lucky7 slot machine project from Chapter 2, which you
enhance by using public variables and a function that computes the game’s
win rate.
Chapter 11
Array Class Sorts
Shows how to create and manipulate large integer arrays. Demonstrates the
Array.Sort and Array.Reverse methods and how to use a ProgressBar control to
give the user visual feedback during long sorts.
Dynamic Array
Computes the average temperature for any number of days by using
a dynamic array.
Fixed Array
Computes the average weekly temperature by using a fixed-length array.
Chapter 12
Controls
Collection
Uses a For Each . . . Next loop and the Visual Studio Controls collection to move
objects on a form.
URL Collection
Demonstrates a user-defined collection containing a list of Uniform Resource
Locators (URLs), or Web addresses, recently visited by the user.
Chapter 13
Encrypt Text
Demonstrates the Chr, Asc, Length, Substring, and FileExists methods, as well
as a simple encryption scheme to jumble the text in files. Teaches useful
­text-processing techniques.
Quick Note
A simple note-taking utility that demonstrates the Clock.LocalTime property;
the WriteAllText method; and the TextBox, MenuStrip, and SaveFileDialog
­controls.
Introduction
Project
xxv
Description
Sort Text
A text file editor with a menu bar that demonstrates how to manage Open,
Close, Save As, Insert Date, Sort Text, and Exit commands in a program.
Contains a ShellSort module for sorting arrays that can be added to other
­programming projects.
Text Browser
Displays the contents of a text file in a Visual Basic program. Demonstrates
menu and dialog box commands, a Try . . . Catch error handler, the ReadAllText
method, and serves as a foundation for the other programs in this chapter.
Xor Encryption
Explores the StreamWriter class and the OpenTextFileWriter and ReadAllText
methods for file management, as well as using the Xor operator to encrypt files
with a hidden code that is entered by the user.
Chapter 14
Add Controls
Demonstrates how controls are added to a Windows Form at run time by using
program code (not the Designer).
Anchor and Dock
Uses the Anchor and Dock properties of a form to align objects at run time.
Desktop Bounds
Uses the StartPosition and DesktopBounds properties to position a Windows
Form at run time. Also demonstrates the FormBorderStyle property, Rectangle
structure, and ShowDialog method.
Lucky Seven Help The enhanced Lucky7 program (Track Wins) from Chapter 10, which you enhance
again through the addition of a second form to display Help information.
Chapter 15
Draw Shapes
Demonstrates a few of the useful graphics methods in the System.Drawing
namespace, including DrawEllipse, FillRectangle, and DrawCurve.
Moving Icon
Animates an icon on the form, moving it from the top of the form to the
­bottom each time that you click the Move Down button.
Transparent Form Demonstrates how to change the transparency of a form by using the Me
­object and the Opacity property.
Zoom In
Simulates zooming in, or magnifying, a picture box object on a form
(in this case, a high-resolution image of the planet Earth).
Chapter 16
Form Inheritance
Uses the Visual Studio Inheritance Picker to create a form that inherits its
­characteristics and functionality from another form.
Person Class
Demonstrates how to create new classes, properties, and methods in a Visual
Basic project. The new Person class is an employee record with first name, last
name, and date of birth fields, and it contains a method that computes the
­current age of an employee.
Chapter 17
Print Dialogs
Demonstrates how to create Print Preview and Page Setup dialog boxes.
Print File
Handles more sophisticated printing tasks, including printing a multipage text
file with wrapping lines. Includes lots of code to use in your own projects.
Print Graphics
Prints graphics from within a Visual Basic program by using an error handler,
the Print method, and the DrawImage method.
Print Text
Demonstrates how simple text is printed in a Visual Basic program.
xxvi
Introduction
Project
Description
Chapter 18
ADO Faculty
Form
Demonstrates how ADO.NET is used to establish a connection to a Microsoft
Access 2007 database and display information from it.
Chapter 19
DataGridView
Sample
Shows how the DataGridView control is used to display multiple tables of
data on a form. Also demonstrates how navigation bars, datasets, and table
­adapters are interconnected and bound to objects on a form.
Chapter 20
Chap20
Demonstrates using Visual Web Developer and ASP.NET 4 to create a car loan
calculator that runs in a Web browser, offers Help information, and displays
faculty database records.
Uninstalling the Practice Files
Use the following steps to remove the practice files added to your hard disk drive by the
Visual Basic 2010 Step by Step installation program. After uninstalling the practice files, you
can delete manually any Visual Basic project files that you have created on your own, should
you choose to do so.
If you are running the Windows 7 or Windows Vista operating system:
1. In Control Panel, in the Programs category, click Uninstall A Program.
2. Select VB 2010 SBS in the list of programs, and then click Uninstall.
3. Follow the on-screen instructions to remove the practice files.
If you are running the Windows XP operating system:
1. In Control Panel, open Add Or Remove Programs.
2. In the Currently Installed Programs list, click VB 2010 SBS. Then click Remove.
3. Follow the on-screen instructions to remove the practice files.
Conventions and Features in This Book
Before you start the exercises in this book, you can save time by understanding how
I provide instructions and the elements I use to communicate information about Visual Basic
programming. The following lists identify stylistic conventions and discuss helpful features
of the book.
Introduction
xxvii
Conventions
n
The names of all program elements—controls, objects, methods, functions, properties,
and so on—appear in italic.
n
Hands-on exercises for you to follow are given in numbered lists of steps (1, 2,
and so on). A round bullet (•) indicates an exercise that has only one step.
n
Text that you need to type appears in bold.
n
As you work through steps, you’ll occasionally see tables with lists of properties that
you’ll set in Visual Studio. Text properties appear within quotes, but you don’t need to
type the quotes.
n
A plus sign (+) between two key names means that you must press those keys at the
same time. For example, “Press Alt+Tab” means that you hold down the Alt key while
you press Tab.
n
Readeraids labeled Note, Tip, and Important provide additional information or alternative
methods for a step. You should read these before continuing with the exercise.
Other Features
n
You can learn special programming techniques, background information, or features
related to the information being discussed by reading the sidebars that appear
throughout the chapters. These sidebars often highlight difficult terminology or
suggest future areas for exploration.
n
You can learn about options or techniques that build on what you learned in a chapter
by trying the One Step Further exercise at the end of that chapter.
n
You can get a quick reminder of how to perform the tasks you learned by reading the
Quick Reference table at the end of a chapter. These handy tables are also designed
to be used as a topical reference after you complete the book and you need a quick
reminder about how to perform a programming task.
Helpful Support Links
You are invited to check out the following links that provide support for the Visual Studio
2010 software and this book’s contents.
xxviii
Introduction
Visual Studio 2010 Software Support
For questions about the Visual Studio 2010 software, I recommend two Microsoft Web sites:
n
http://msdn.microsoft.com/vbasic/ (the Microsoft Visual Basic Developer Center
home page)
n
http://www.microsoft.com/communities/ (the home of technical communities related to
Microsoft software products and technologies)
Both Web sites give you access to professional Visual Basic developers, Microsoft e
­ mployees,
Visual Basic blogs, newsgroups, webcasts, technical chats, and interesting user groups.
For additional information about these and other electronic and printed resources, see the
Appendix, “Where to Go for More Information.”
Support for This Book
Every effort has been made to ensure the accuracy of this book and the contents of the
companion CD. As corrections or changes are collected, they will be added to a Microsoft
Knowledge Base article. Microsoft Press provides support for books and companion CDs
at the following Web site:
http://www.microsoft.com/learning/support/books/
If you have comments, questions, or ideas regarding the book or the companion CD,
or questions that are not answered by visiting the sites previously mentioned, please send
them to Microsoft Press via an e-mail message to mspinput@microsoft.com.
Please note that Microsoft software product support is not offered through these addresses,
nor does the author of this book offer direct product support.
We Want to Hear from You
We welcome your feedback about this book. Please share your comments and ideas through
the following short survey:
http://www.microsoft.com/learning/booksurvey
Your participation helps Microsoft Press create books that better meet your needs and your
standards.
Note We hope that you will give us detailed feedback in our survey. If you have questions about
our publishing program, upcoming titles, or Microsoft Press in general, we encourage you to
interact with us using Twitter at http://twitter.com/MicrosoftPress. For support issues, use only the
e-mail address shown previously.
Chapter 2
Writing Your First Program
After completing this chapter, you will be able to:
n
Create the user interface for a new program.
n
Set the properties for each object in your user interface.
n
Write program code.
n
Save and run the program.
n
Build an executable file.
As you learned in Chapter 1, “Exploring the Visual Studio Integrated Development
Environment,” the Microsoft Visual Studio 2010 Integrated Development Environment (IDE)
contains s­ everal powerful tools to help you run and manage your programs. Visual Studio
also contains e
­ verything you need to build your own applications for Windows and the Web
from the ground up.
In this chapter, you’ll learn how to create a simple but attractive user interface with the
­controls in the Visual Studio Toolbox. Next you’ll learn how to customize the operation
of these controls with property settings. Then you’ll see how to identify just what your
­program should do by writing program code. Finally, you’ll learn how to save and run your
new ­program (a Las Vegas–style slot machine) and how to compile it as an executable file.
Lucky Seven: Your First Visual Basic Program
The Windows-based application you’re going to construct is Lucky Seven, a game program
that simulates a lucky number slot machine. Lucky Seven has a simple user interface and can
be created and compiled in just a few minutes using Microsoft Visual Basic. Here’s what your
program will look like when it’s finished:
37
38
Part I Getting Started with Microsoft Visual Basic 2010
Programming Steps
The Lucky Seven user interface contains two buttons, three lucky number boxes, a digital
photo depicting your winnings, and the label “Lucky Seven.” I produced these elements
by creating seven objects on the Lucky Seven form and then changing several properties
for each object. After I designed the interface, I added program code for the Spin and End
­buttons to process the user’s button clicks and produce the random numbers. To re-create
Lucky Seven, you’ll follow three essential programming steps in Visual Basic: Create the user
interface, set the properties, and write the program code. Table 2-1 shows the ­process for
Lucky Seven.
TABLE 2-1 Building
the Lucky Seven Program
Programming Step
Number of Items
1. Create the user interface.
7 objects
2. Set the properties.
13 properties
3. Write the program code.
2 objects
Creating the User Interface
In this exercise, you’ll start building Lucky Seven by first creating a new project and then
­using controls in the Toolbox to construct the user interface.
Create a new project
1. Start Visual Studio 2010.
2. On the Visual Studio File menu, click New Project.
Tip You can also start a new programming project by clicking the blue New Project link
on the Start Page.
The New Project dialog box opens, as shown on the following page.
The New Project dialog box provides access to the major project types available for
writing Windows and Web applications. If you indicated during setup that you are
a Visual Basic programmer, Visual Basic is your primary development option (as shown
here), but the other languages in Visual Studio (Visual C#, Visual C++, and Visual F#)
are always available through this dialog box. Although you will select a basic Windows
Chapter 2 Writing Your First Program
39
application project in this exercise, this dialog box is also the gateway to other types
of development projects, such as a Web application, console application, Microsoft
Office add-in, Windows Azure Cloud Service, Silverlight application, or Visual Studio
­deployment project.
Near the top of the New Project dialog box, you will notice a drop-down list box.
This feature allows you to specify the version of the Microsoft .NET Framework that
your application will target. This feature is sometimes called multi-targeting, meaning
that through it, you can select the target environment that your program will run on.
For example, if you retain the default selection of .NET Framework 4, any computer that
your application will run on must have .NET Framework 4 installed. (Not to worry—the
.NET Framework is usually installed as part of the operating system installation, or when
you install a new Visual Basic program that you have written.) Unless you have a ­specific
need, you can just leave this drop-down list at its default setting of .NET Framework 4.
Visual Basic 2010 Express does not include this drop-down list. You’ll learn more about
the .NET Framework in Chapter 5, “Visual Basic Variables and Formulas, and the .NET
Framework.”
3. Click the Windows Forms Application icon in the central Templates area of the dialog
box, if it is not already selected.
Visual Studio prepares the development environment for Visual Basic Windows
­application programming.
40
Part I Getting Started with Microsoft Visual Basic 2010
4. In the Name text box, type MyLucky7.
Visual Studio assigns the name MyLucky7 to your project. (You’ll specify a folder
­location for the project later.) I’m recommending the “My” prefix here so you
don’t confuse your new application with the Lucky7 project I’ve created for you
on disk.
Tip If your New Project dialog box contains Location and Solution Name text boxes,
you need to specify a folder location and solution name for your new programming
project now. The presence of these text boxes is controlled by a check box in the Project
And Solutions category of the Options dialog box, but it is not the default setting. (You
­display this dialog box by clicking the Options command on the Tools menu.) Throughout
this book, you will be instructed to save your projects (or discard them) after you have
completed the programming exercise. For more information about this “delayed saving”
feature and default settings, see the section entitled “Customizing IDE Settings to Match
Step-by-Step Exercises” in Chapter 1.
5. Click OK to create the new project in Visual Studio.
Visual Studio cleans the slate for a new programming project and displays the blank
Windows form that you will use to build your user interface.
Now you’ll enlarge the form and create the two buttons in the interface.
Create the user interface
1. Point to the lower-right corner of the form until the mouse pointer changes to
a ­resizing pointer, and then drag to increase the size of the form to make room for
the objects in your program.
As you resize the form, scroll bars might appear in the Designer to give you access to
the entire form you’re creating. Depending on your screen resolution and the Visual
Studio tools you have open, you might not be able to see the entire form at once.
Don’t worry about this—your form can be small, or it can fill the entire screen because
the scroll bars give you access to the entire form.
Size your form so that it is about the size of the form shown on the following page. If
you want to match my example exactly, you can use the width and height dimensions
(485 ­pixels × 278 pixels) shown in the lower-right corner of the screen.
To see the entire form without obstruction, you can resize or close the other
­programming tools, as you learned in Chapter 1. (Return to Chapter 1 if you have
­questions about resizing windows or tools.)
Now you’ll practice adding a button object on the form.
Chapter 2 Writing Your First Program
41
2. Click the Toolbox tab to display the Toolbox window in the IDE.
The Toolbox contains all the controls that you’ll use to build Visual Basic programs in
this book. The controls suitable for creating a Windows application are visible now
because you selected the Windows Application project type earlier. Controls are
­organized by type, and by default the Common Controls category is visible. (If the
Toolbox is not visible now, click Toolbox on the View menu to display it.)
3. Double-click the Button control in the Toolbox, and then move the mouse pointer away
from the Toolbox.
Visual Studio creates a default-sized button object on the form and hides the Toolbox,
as shown here:
42
Part I Getting Started with Microsoft Visual Basic 2010
The button is named Button1 because it is the first button in the program. (You should make
a mental note of this button name—you’ll see it again when you write your program code.)
The new button object is selected and enclosed by resize handles. When Visual Basic is in
­design mode (that is, whenever the Visual Studio IDE is active), you can move objects on the
form by dragging them with the mouse, and you can resize them by using the resize handles.
While a program is running, however, the user can’t move user interface (UI) elements unless
you’ve changed a property in the program to allow this. You’ll practice moving and resizing
the button now.
Move and resize a button
1. Point to the button so that the pointer changes to a four-headed arrow, and then drag
the button down and to the right.
The button moves across the surface of the form. If you move the object near the edge
of the form or another object (if other objects are present), it automatically aligns ­itself
to a hidden grid when it is an inch or so away. A little blue “snapline” also appears to
help you gauge the distance of this object from the edge of the form or the other
­object. The grid is not displayed on the form by default, but you can use the snapline
to judge distances with almost the same effect.
2. Position the mouse pointer on the lower-right corner of the button.
When the mouse pointer rests on a resize handle of a selected object, it
­becomes a ­resizing pointer. You can use the resizing pointer to change the size
of an object.
3. Enlarge the button by dragging the pointer down and to the right.
When you release the mouse button, the button changes size and snaps to the grid.
4. Use the resizing pointer to return the button to its original size.
Now you’ll add a second button to the form, below the first button.
Add a second button
1. Click the Toolbox tab to display the Toolbox.
2. Click the Button control in the Toolbox (single-click this time), and then move the
mouse pointer over the form.
The mouse pointer changes to crosshairs and a button icon. The crosshairs are
­designed to help you draw the rectangular shape of the button on the form, and you
can use this method as an alternative to double-clicking to create a control of the
­default size.
3. Click and drag the pointer down and to the right. Release the mouse button to
­complete the button, and watch it snap to the form.
Chapter 2 Writing Your First Program
43
4. Resize the button object so that it is the same size as the first button, and then move it
below the first button on the form. (Use the snapline feature to help you.)
Tip At any time, you can delete an object and start over again by selecting the object
on the form and then pressing DELETE. Feel free to create and delete objects to practice
­creating your user interface.
Now you’ll add the labels used to display the numbers in the program. A label is a special
user interface element designed to display text, numbers, or symbols when a program runs.
When the user clicks the Lucky Seven program’s Spin button, three random numbers appear
in the label boxes. If one of the numbers is a 7, the user wins.
Add the number labels
1. Double-click the Label control in the Toolbox.
Visual Studio creates a label object on the form. The label object is just large enough
to hold the text contained in the object (it is rather small now), but it can be resized.
2. Drag the Label1 object to the right of the two button objects.
Your form looks something like this:
3. Double-click the Label control in the Toolbox to create a second label object.
This label object will be named Label2 in the program.
4. Double-click the Label control again to create a third label object.
5. Move the second and third label objects to the right of the first one on the form.
Allow plenty of space between the three labels because you will use them to display
large numbers when the program runs.
Now you’ll use the Label control to add a descriptive label to your form. This will be
the fourth and final label in the program.
6. Double-click the Label control in the Toolbox.
44
Part I Getting Started with Microsoft Visual Basic 2010
7. Drag the Label4 object below the two command buttons.
When you’ve finished, your four labels should look like those in the following
screen shot. (You can move your label objects if they don’t look quite right.)
Now you’ll add a picture box to the form to graphically display the payout you’ll receive
when you draw a 7 and hit the jackpot. A picture box is designed to display bitmaps, icons,
digital photos, and other artwork in a program. One of the best uses for a picture box is to
display a JPEG image file.
Add a picture
1. Click the PictureBox control in the Toolbox.
2. Using the control’s drawing pointer, create a large rectangular box below the second
and third labels on the form.
Leave a little space below the labels for their size to grow as I mentioned earlier.
When you’ve finished, your picture box object looks similar to this:
This object will be named PictureBox1 in your program; you’ll use this name later in
the program code.
Now you’re ready to customize your interface by setting a few properties.
Chapter 2 Writing Your First Program
45
Setting the Properties
As you discovered in Chapter 1, you can change properties by selecting objects on the form
and changing their settings in the Properties window. You’ll start by changing the property
settings for the two buttons.
Set the button properties
1. Click the first button (Button1) on the form.
The button is selected and is surrounded by resize handles.
2. Click the Properties window title bar.
Tip If the Properties window isn’t visible, click the Properties Window command on the
View menu, or press F4.
3. At the top of the Properties window, click the Categorized button.
For information about categorized properties, see the section entitled “The Properties
Window” in Chapter 1.
4. Resize the Properties window (if necessary) so that there is plenty of room to see the
property names and their current settings.
Once you get used to setting properties, you will probably use the Properties w
­ indow
without enlarging it, but making it bigger helps when you first try to use it. The
Properties window in the following screen shot is a good size for setting properties:
46
Part I Getting Started with Microsoft Visual Basic 2010
The Properties window lists the settings for the first button. These include settings
for the background color, text, font height, and width of the button. Because there are
so many properties, Visual Studio organizes them into categories and displays them
in outline view. If you want to see the properties in a category, click the arrow sign (>)
next to the category title.
5. If it is not already visible, scroll in the Properties window until you see the Text property
located in the Appearance category.
6. Double-click the Text property in the first column of the Properties window.
The current Text setting (“Button1”) is highlighted in the Properties window.
7. Type Spin, and then press ENTER.
The Text property changes to “Spin” in the Properties window and on the button
on the form. Now you’ll change the Text property of the second button to “End.”
(You’ll select the second button in a new way this time.)
8. Open the Object list at the top of the Properties window.
A list of the interface objects in your program appears as follows:
9. Click Button2 System.Windows.Forms.Button (the second button) in the list box.
The property settings for the second button appear in the Properties window, and
Visual Studio highlights Button2 on the form.
10. Double-click the current Text property (“Button2”), type End, and then press ENTER.
The text of the second button changes to “End.”
Chapter 2 Writing Your First Program
47
Tip Using the Object list is a handy way to switch between objects in your program.
You can also switch between objects on the form by clicking each object.
Now you’ll set the properties for the labels in the program. The first three labels will hold
the random numbers generated by the program and will have identical property settings.
(You’ll set most of them as a group.) The descriptive label settings will be slightly different.
Set the number label properties
1. Click the first number label (Label1), hold down the SHIFT key, click the second
and third number labels, and then release the SHIFT key. (If the Properties window is
in the way, move it to a new place.)
A selection rectangle and resize handles appear around each label you click. You’ll
change the TextAlign, BorderStyle, and Font properties now so that the numbers that
will appear in the labels will be centered, boxed, and identical in font and font size.
(All these properties are located in the Appearance category of the Properties window.)
You’ll also set the AutoSize property to False so that you can change the size of the
­labels according to your precise specifications. (The AutoSize property is located in the
Layout category.)
Tip When more than one object is selected, only those properties that can be changed
for the group are displayed in the Properties window.
2. Click the AutoSize property in the Properties window, and then click the arrow that
­appears in the second column.
3. Set the AutoSize property to False so that you can size the labels manually.
4. Click the TextAlign property, and then click the arrow that appears in the second
column.
A graphical assortment of alignment options appears in the list box; you can use
these settings to align text anywhere within the borders of the label object.
5. Click the center option (MiddleCenter).
The TextAlign property for each of the selected labels changes to MiddleCenter.
6. Click the BorderStyle property, and then click the arrow that appears in the second
column.
The valid property settings (None, FixedSingle, and Fixed3D) appear in the list box.
7. Click FixedSingle in the list box to add a thin border around each label.
48
Part I Getting Started with Microsoft Visual Basic 2010
8. Click the Font property, and then click the ellipsis button (the button with three dots
that’s located next to the current font setting).
The Font dialog box opens.
9. Change the font to Times New Roman, the font style to Bold, and the font size to 24,
and then click OK.
The label text appears in the font, style, and size you specified.
Now you’ll set the text for the three labels to the number 0—a good “placeholder” for
the numbers that will eventually fill these boxes in your game. (Because the program
produces the actual numbers, you could also delete the text, but putting a placeholder
here gives you something to base the size of the labels on.)
10. Click a blank area on the form to remove the selection from the three labels, and then
click the first label.
11. Double-click the Text property, type 0, and then press ENTER.
The text of the Label1 object is set to 0. You’ll use program code to set this property
to a random “slot machine” number later in this chapter.
12. Change the text in the second and third labels on the form to 0 also.
13. Move and resize the labels now so that they are appropriately spaced.
Your form looks something like this:
Now you’ll change the Text, Font, and ForeColor properties of the fourth label.
Set the descriptive label properties
1. Click the fourth label object (Label4) on the form.
2. Change the Text property in the Properties window to Lucky Seven.
3. Click the Font property, and then click the ellipsis button.
4. Use the Font dialog box to change the font to Arial, the font style to Bold, and the font
size to 18. Then click OK.
The font in the Label4 object is updated, and the label is resized automatically to hold
the larger font size because the object’s AutoSize property is set to True.
Chapter 2 Writing Your First Program
49
5. Click the ForeColor property in the Properties window, and then click the arrow in
the second column.
Visual Studio displays a list box with Custom, Web, and System tabs for setting the
foreground colors (the color of text) of the label object. The Custom tab offers many of
the colors available in your system. The Web tab sets colors for Web pages and lets you
pick colors using their common names. The System tab displays the current colors used
for user interface elements in your system.
6. Click the purple color on the Custom tab.
The text in the label box changes to purple.
Now you’re ready to set the properties for the last object.
The Picture Box Properties
When the person playing your game hits the jackpot (that is, when at least one 7 appears in
the number labels on the form), the picture box object will contain a picture in JPEG format
of a person dispensing money. (I am supplying you with this digitized image, but you can
substitute your own if you like.) You need to set the SizeMode property to accurately size the
picture and set the Image property to specify the name of the JPEG file that you will load
into the picture box. You also need to set the Visible property, which specifies the picture
state at the beginning of the program.
Set the picture box properties
1. Click the picture box object on the form.
2. Click the SizeMode property in the Properties window (listed in the Behavior ­category),
click the arrow in the second column, and then click StretchImage.
Setting SizeMode to StretchImage before you open a graphic causes Visual Studio to
resize the graphic to the exact dimensions of the picture box. (Typically, you set this
property before you set the Image property.)
3. Click the Image property in the Properties window, and then click the ellipsis button
in the second column.
The Select Resource dialog box opens.
4. Click the Local Resource radio button, and then click the Import button.
5. In the Open dialog box, navigate to the C:\Vb10sbs\Chap02 folder.
This folder contains the digital photo PayCoins.jpg.
6. Select PayCoins.jpg, and then click Open.
An screen shot of one person paying another appears in the Select Resource
­dialog box. (The letter “W” represents winning.)
50
Part I Getting Started with Microsoft Visual Basic 2010
7. Click OK.
The PayCoins photo is loaded into the picture box. Because the photo is relatively small
(24 KB), it opens quickly on the form.
8. Resize the picture box object now to fix any distortion problems that you see in the
image.
I sized my picture box object to be 144 pixels wide by 146 pixels high. You can match
this size by using the width and height dimensions located on the lower-right side
of the Visual Studio IDE. (The dimensions of the selected object are given on the
­lower-right side, and the location on the form of the object’s upper-left corner is given
to the left of the dimensions.)
This particular image displays best when the picture box object retains a square shape.
Note As you look at the picture box object, you might notice a tiny shortcut arrow called
a smart tag near its upper-right corner. This smart tag is a button that you can click to
quickly change a few common picture box settings and open the Select Resource dialog
box. (You’ll see the smart tag again in Chapter 4, “Working with Menus, Toolbars, and
Dialog Boxes,” when you use the ToolStrip control.)
Now you’ll change the Visible property to False so that the image will be invisible when
the program starts.
9. Click the Visible property in the Behavior category of the Properties window, and then
click the arrow in the second column.
The valid settings for the Visible property appear in a list box.
10. Click False to make the picture invisible when the program starts.
Chapter 2 Writing Your First Program
51
Setting the Visible property to False affects the picture box when the program runs, but
not now, while you’re designing it. Your completed form looks similar to this:
Tip You can also double-click property names that have True and False settings (so-called
Boolean properties), to toggle back and forth between True and False. Default Boolean
properties are shown in regular type, and changed settings appear in bold.
11. You are finished setting properties for now, so if your Properties window is fl
­ oating,
hold down the CTRL key and double-click its title bar to return it to the docked
position.
Reading Properties in Tables
In this chapter, you’ve set the properties for the Lucky Seven program step by step.
In future chapters, the instructions to set properties will be presented in table format
unless a setting is especially tricky. Table 2-2 lists the properties you’ve set so far in the
Lucky Seven program, as they’d look later in the book. Settings you need to type in are
shown in quotation marks. You shouldn’t type the quotation marks.
TABLE 2-2 Lucky
Seven Properties
Object
Property
Setting
Button1
Text
“Spin”
Button2
Text
“End”
Label1, Label2, Label3
AutoSize
BorderStyle
Font
Text
TextAlign
False
FixedSingle
Times New Roman, Bold, 24-point
“0”
MiddleCenter
Label4
Text
Font
ForeColor
“Lucky Seven”
Arial, Bold, 18-point
Purple
PictureBox1
Image
SizeMode
Visible
“C:\Vb10sbs\Chap02\Paycoins.jpg”
StretchImage
False
52
Part I Getting Started with Microsoft Visual Basic 2010
Writing the Code
Now you’re ready to write the code for the Lucky Seven program. Because most of the
­objects you’ve created already “know” how to work when the program runs, they’re ready
to receive input from the user and process it. The inherent functionality of objects is one
of the great strengths of Visual Studio and Visual Basic—after objects are placed on a form
and their properties are set, they’re ready to run without any additional programming.
However, the “meat” of the Lucky Seven game—the code that actually calculates random
numbers, displays them in boxes, and detects a jackpot—is still missing from the program.
This computing logic can be built into the application only by using program statements—
code that clearly spells out what the program should do at each step of the way. Because
the Spin and End buttons drive the program, you’ll associate the code for the game with
those buttons. You enter and edit Visual Basic program statements in the Code Editor.
In the following steps, you’ll enter the program code for Lucky Seven in the Code Editor.
Use the Code Editor
1. Double-click the End button on the form.
The Code Editor appears as a tabbed document window in the center of the Visual
Studio IDE, as shown here:
Chapter 2 Writing Your First Program
53
Inside the Code Editor are program statements associated with the current form.
Program statements that are used together to perform some action are typically
grouped in a programming construct called a procedure. A common type of p
­ rocedure
is a Sub procedure, sometimes called a subroutine. Sub procedures include a Sub
­keyword in the first line and end with End Sub. (I’ll talk about the Public and Private
keywords later.) Procedures are typically executed when certain events occur, such as
when a button is clicked. When a procedure is associated with a particular object and
an event, it is called an event handler or an event procedure.
When you double-clicked the End button (Button2), Visual Studio automatically added
the first and last lines of the Button2_Click event procedure, as the following code
shows. (The first line was wrapped to stay within the book margins.) You may notice
other bits of code in the Code Editor (words like Public and Class), which Visual Studio
has added to define important characteristics of the form, but I won’t emphasize
them here.
Private Sub Button2_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button2.Click
End Sub
The body of a procedure fits between these lines and is executed whenever a user
activates the interface element associated with the procedure. In this case, the event
is a mouse click, but as you’ll see later in the book, it could also be a different type
of event.
2. Type End, and then press the ENTER key.
When you type the statement, Visual Studio recognizes End as a unique reserved word
or keyword and displays it in a list box with Common and All tabs. Microsoft calls this
auto-extend feature IntelliSense because it tries to intelligently help you write code,
and you can browse through various Visual Basic keywords and objects alphabetically.
(In this way, the language is partially discoverable through the IDE itself.)
After you press the ENTER key, the letters in End turn blue and are indented, i­ndicating
that Visual Basic recognizes End as one of several hundred unique keywords within
the Visual Basic language. You use the End keyword to stop your program and
­remove it from the screen. In this case, End is also a complete program statement,
a ­self-contained instruction executed by the Visual Basic compiler, the part of Visual
Studio that ­processes or parses each line of Visual Basic source code, combining the
result with o
­ ther resources to create an executable file. Program statements are a little
like c­ omplete sentences in a human language—statements can be of varying lengths
but must follow the grammatical “rules” of the compiler. In Visual Studio, ­program
­statements can be composed of keywords, properties, object names, variables,
­numbers, special symbols, and other values. You’ll learn more about how program
statements are constructed in Chapter 5.
As you enter program statements and make other edits, the Code Editor handles many
of the formatting details for you, including adjusting indentation and ­spacing and
54
Part I Getting Started with Microsoft Visual Basic 2010
­ dding any necessary parentheses. The exact spelling, order, and spacing of items within
a
program statements is referred to as statement syntax. In the early days of ­compilers,
programmers were almost totally responsible for getting the precise syntax for each
program statement correct on their own, but now sophisticated development tools such
as Visual Studio help immensely with the construction of accurate program statements.
When you pressed the ENTER key, the End statement was indented to set it apart
from the Private Sub and End Sub statements. This indenting scheme is one of the
­programming conventions you’ll see throughout this book to keep your programs clear
and readable. The group of conventions regarding how code is organized in a program
is often referred to as program style.
Now that you’ve written the code associated with the End button, you’ll write code for the
Spin button. These program statements will be a little more extensive and will give you
a chance to learn more about statement syntax and program style. You’ll study many of the
program statements later in this book, so you don’t need to know everything about them
now. Just focus on the general structure of the code and on typing the program statements
exactly as they are printed.
Write code for the Spin button
1. At the top of the Solution Explorer window, click the View Designer button in the
Solution Explorer window to display your form again.
Note When the Code Editor is visible, you won’t be able to see the form you’re working
on. The View Designer button is one mechanism you can use to display it again. (If more
than one form is loaded in Solution Explorer, click the form that you want to display first.)
You can also click the Form1.vb [Design] tab at the top edge of the Code Editor. To display
the Code Editor again, click the View Code button in Solution Explorer.
2. Double-click the Spin button.
After a few moments, the Code Editor appears, and an event procedure associated with
the Button1 button appears near the Button2 event procedure.
Although you changed the text of this button to “Spin,” its name in the program is
still Button1. (The name and the text of an interface element can be different to suit
the needs of the programmer.) Each object can have several procedures associated
with it, one for each event it recognizes. The click event is the one you’re interested
in now ­because users will click the Spin and End buttons when they run the program.
3. Type the following program lines between the Private Sub and End Sub statements.
Press ENTER after each line, press TAB to indent, and take care to type the program
statements exactly as they appear here. (The Code Editor will scroll to the left as you
enter the longer lines.) If you make a mistake (usually identified by a jagged underline),
delete the incorrect statements and try again.
Chapter 2 Writing Your First Program
Tip As you enter the program code, Visual Basic formats the text and displays different
parts of the program in color to help you identify the various elements. When you begin
to type a property, Visual Basic also displays the available properties for the object you’re
using in a list box, so you can double-click the property or keep typing to enter it yourself.
If Visual Basic displays an error message, you might have misspelled a program statement.
Check the line against the text in this book, make the necessary correction, and continue
typing. (You can also delete a line and type it from scratch.) In addition, Visual Basic might
add necessary code automatically. For example, when you type the following code, Visual
Basic automatically adds the End If line. Readers of previous editions of this book have
found this first typing exercise to be the toughest part of this chapter—“But Mr. Halvorson,
I know I typed it just as you wrote it!”—so please give this program code your closest
­attention. I promise you, it works!
PictureBox1.Visible = False ' hide picture
Label1.Text = CStr(Int(Rnd() * 10)) ' pick numbers
Label2.Text = CStr(Int(Rnd() * 10))
Label3.Text = CStr(Int(Rnd() * 10))
' if any number is 7 display picture and beep
If (Label1.Text = "7") Or (Label2.Text = "7") _
Or (Label3.Text = "7") Then
PictureBox1.Visible = True
Beep()
End If
When you’ve finished, the Code Editor looks as shown in the following screen shot:
55
56
Part I Getting Started with Microsoft Visual Basic 2010
4. Click the Save All command on the File menu to save your additions to the program.
The Save All command saves everything in your project—the project file, the form
file, any code modules, and other related components in your application. Since
this is the first time that you have saved your project, the Save Project dialog box
opens, prompting you for the name and location of the project. (If your copy of
Visual Studio is configured to prompt you for a location when you first create your
­project, you won’t see the Save Project dialog box now—Visual Studio just saves
your changes.)
5. Browse and select a location for your files.
I recommend that you use the C:\Vb10sbs\Chap02 folder (the location of the book’s
sample files), but the location is up to you. Since you used the “My” prefix when you
originally opened your project, this version won’t overwrite the Lucky7 practice file that
I built for you on disk.
6. Clear the Create Directory For Solution check box.
When this check box is selected, it creates a second folder for your program’s solution
files, which is not necessary for solutions that contain only one project (the situation for
most programs in this book).
7. Click Save to save your files.
Note If you want to save just the item you are currently working on (the form, the code
module, or something else), you can use the Save command on the File menu. If you want
to save the current item with a different name, you can use the Save As command.
A Look at the Button1_Click Procedure
The Button1_Click procedure is executed when the user clicks the Spin button on the form.
The procedure uses some pretty complicated statements, and because I haven’t formally
­introduced them yet, it might look a little confusing. However, if you take a closer look,
you’ll probably see a few things that look familiar. Taking a peek at the contents of these
­procedures will give you a feel for the type of program code you’ll be creating later in
this book. (If you’d rather not stop for this preview, feel free to skip to the next section,
“Running Visual Basic Applications.”)
The Button1_Click procedure performs three tasks:
n
It hides the digital photo.
n
It creates three random numbers for the number labels.
n
It displays the photo when the number 7 appears.
Chapter 2 Writing Your First Program
57
Let’s look at each of these steps individually.
Hiding the photo is accomplished with the following line:
PictureBox1.Visible = False
' hide picture
This line is made up of two parts: a program statement and a comment.
The PictureBox1.Visible = False program statement sets the Visible property of the picture
box object (PictureBox1) to False (one of two possible settings). You might remember that
you set this property to False once before by using the Properties window. You’re d
­ oing
it again now in the program code because the first task is a spin and you need to clear
away a photo that might have been displayed in a previous game. Because the property
will be changed at run time and not at design time, you must set the property by using
­program code. This is a handy feature of Visual Basic, and I’ll talk about it more in Chapter 3,
“Working with Toolbox Controls.”
The second part of the first line (the part displayed in green type on your screen) is called
a comment. Comments are explanatory notes included in program code following a single
quotation mark (‘). Programmers use comments to describe how important statements work
in a program. These notes aren’t processed by Visual Basic when the program runs; they ­exist
only to document what the program does. You’ll want to use comments often when you
write Visual Basic programs to leave an easy-to-understand record of what you’re doing.
The next three lines handle the random number computations. Does this concept sound
strange? You can actually make Visual Basic generate unpredictable numbers within ­specific
guidelines—in other words, you can create random numbers for lottery contests, dice
games, or other statistical patterns. The Rnd function in each line creates a random number
­between 0 and 1 (a number with a decimal point and several decimal places), and the Int
function returns the integer portion of the result of multiplying the random number by 10.
This ­computation creates random numbers between 0 and 9 in the program—just what you
need for this particular slot machine application.
Label1.Text = CStr(Int(Rnd() * 10))
' pick numbers
You then need to jump through a little hoop in your code. You need to copy these ­random
­numbers into the three label boxes on the form, but first the numbers need to be ­converted to
text with the CStr (convert to string) function. Notice how CStr, Int, and Rnd are all ­connected in
the program statement—they work collectively to produce a result like a ­mathematical formula.
After the computation and conversion, the values are assigned to the Text properties of the
first three labels on the form, and the assignment causes the ­numbers to be displayed in bold,
24-point, Times New Roman font in the three number labels.
The last group of statements in the program checks whether any of the random numbers is 7.
If one or more of them is, the program displays the graphical depiction of a payout, and a
beep announces the winnings.
58
Part I Getting Started with Microsoft Visual Basic 2010
' if any number is 7 display picture and beep
If (Label1.Text = "7") Or (Label2.Text = "7") _
Or (Label3.Text = "7") Then
PictureBox1.Visible = True
Beep()
End If
Each time the user clicks the Spin button, the Button1_Click procedure is executed, or called,
and the program statements in the procedure are run again.
Running Visual Basic Applications
Congratulations! You’re ready to run your first real program. To run a Visual Basic program
from the development environment, you can do any of the following:
n
Click Start Debugging on the Debug menu.
n
Click the Start Debugging button on the Standard toolbar.
n
Press F5.
Try running your Lucky Seven program now. If Visual Basic displays an error message, you might
have a typing mistake or two in your program code. Try to fix it by comparing the printed version
in this book with the one you typed, or load Lucky7 from your hard disk and run it.
Run the Lucky Seven program
1. Click the Start Debugging button on the Standard toolbar.
The Lucky Seven program compiles and runs in the IDE. After a few seconds, the user
interface appears, just as you designed it.
2. Click the Spin button.
The program picks three random numbers and displays them in the labels on the form,
as follows:
Chapter 2 Writing Your First Program
59
Because a 7 appears in the first label box, the digital photo depicting the payoff
­appears, and the computer beeps. You win! (The sound you hear depends on your
Default Beep setting in the Sound Control Panel. To make this game sound really cool,
change the Default Beep sound to something more dynamic.)
3. Click the Spin button 15 or 16 more times, watching the results of the spins in the
­number boxes.
About half the time you spin, you hit the jackpot—pretty easy odds. (The actual odds
are about 2.8 times out of 10; you’re just lucky at first.) Later on, you might want to
make the game tougher by displaying the photo only when two or three 7s appear,
or by creating a running total of winnings.
4. When you’ve finished experimenting with your new creation, click the End button.
The program stops, and the development environment reappears on your screen.
Tip If you run this program again, you might notice that Lucky Seven displays exactly the
same sequence of random numbers. There is nothing wrong here—the Visual Basic Rnd
function was designed to display a repeating sequence of numbers at first so that you can
properly test your code using output that can be reproduced again and again. To ­create
truly “random” numbers, use the Randomize function in your code, as shown in the
­exercise at the end of this chapter. The .NET Framework, which you’ll learn to use later, also
supplies random number functions.
Sample Projects on Disk
If you didn’t build the MyLucky7 project from scratch (or if you did build the project and want to
compare what you created to what I built for you as I wrote the chapter), take a moment to open
and run the completed Lucky7 project, which is located in the C:\Vb10sbs\Chap02\Lucky7 folder
on your hard disk (the default location for the practice files for this chapter). If you need a refresher
course on opening projects, see the detailed instructions in Chapter 1. If you are asked if you want
to save changes to the MyLucky7 project, be sure to click Save.
This book is a step-by-step tutorial, so you will benefit most from building the projects on your
own and experimenting with them. But after you have completed the projects, it is often a
good idea to compare what you have with the practice file “solution” that I provide, especially
if you run into trouble. To make this easy, I will give you the name of the solution files on disk
before you run the completed program in most of the step-by-step exercises.
After you have compared the MyLucky7 project to the Lucky7 solution files on disk, reopen
MyLucky7 and prepare to compile it as an executable file. If you didn’t create MyLucky7, use
my solution file to complete the exercise.
60
Part I Getting Started with Microsoft Visual Basic 2010
Building an Executable File
Your last task in this chapter is to complete the development process and create an
­application for Windows, or an executable file. (Had you created a different project type,
of course, such as a Web application, the result of your development efforts would have
been a different type of file—but we’ll discuss this later.) Windows applications created with
Visual Studio have the file name extension .exe and can be run on any system that contains
Windows and the necessary support files. (Visual Basic installs these support files—including
the .NET Framework files—automatically.) If you plan to distribute your applications, see the
section entitled “Deploying Your Application” later in the chapter.
At this point, you need to know that Visual Studio can create two types of executable files
for your Windows application project: a debug build and a release build.
Debug builds are created automatically by Visual Studio when you create and test
your ­program. They are stored in a folder called Bin\Debug within your project folder.
The ­debug executable file contains debugging information that makes the program run
slightly slower.
Release builds are optimized executable files stored in the Bin\Release folder within your
project. To customize the settings for your release build, you click the [ProjectName]
Properties command on the Project menu, and then click the Compile tab, where you see
a list of compilation options that looks like this:
Chapter 2 Writing Your First Program
61
Try creating a release build named MyLucky7.exe now.
Create an executable file
1. On the Build menu, click the Build MyLucky7 command.
The Build command creates a Bin\Release folder in which to store your project (if the
folder doesn’t already exist) and compiles the source code in your project. The ­result
is an executable file of the Application type named MyLucky7.exe. To save you
time, Visual Studio often creates temporary executable files while you develop your
­application; however, it’s always a good idea to recompile your application manually
with the Build or Rebuild command when you reach an important milestone.
Try running this program outside the Visual Studio IDE now from the Windows
Start menu.
2. On the Windows taskbar, click Start.
The next command depends on the version of Windows you’re using.
3. If you have Windows 7 or Windows Vista, type run in the Search text box and press
ENTER to open the Run dialog box. If you have Windows XP or earlier, click the Run
command to open the Run dialog box.
4. Click Browse and then navigate to the C:\Vb10sbs\Chap02\Mylucky7\Bin\Release folder.
5. Click the MyLucky7.exe application icon, click Open, and then click OK.
The Lucky Seven program loads and runs in Windows. Because this is a simple test
­application and it does not possess a formal publisher certificate that emphasizes its
reliability or authenticity, you may see the following message: “The publisher could not
be verified. Are you sure you want to run this software?” If this happens to you, click
Yes to run the program anyway. (Creating such certificates is beyond the scope of this
chapter, but this program is quite safe.)
6. Click Spin a few times to verify the operation of the game, and then click End.
Tip You can also run Windows applications, including compiled Visual Basic programs, by
opening Windows Explorer and double-clicking the executable file. To create a shortcut
icon for MyLucky7.exe on the Windows desktop, right-click the Windows desktop, point to
New, and then click Shortcut. When you’re prompted for the location of your ­application
file, click Browse, and select the MyLucky7.exe executable file. Click the OK, Next, and
Finish buttons. Windows places an icon on the desktop that you can double-click to run
your program.
7. On the File menu, click Exit to close Visual Studio and the MyLucky7 project.
The Visual Studio development environment closes.
62
Part I Getting Started with Microsoft Visual Basic 2010
Deploying Your Application
Visual Studio helps you distribute your Visual Basic applications by providing several options
for deployment—that is, for installing the application on one or more computer systems.
Since the release of Visual Studio in 2002, Visual Basic applications have been compiled as
assemblies—deployment units consisting of one or more files necessary for the program
to run. Assemblies contain four elements: Microsoft intermediate language (MSIL) code,
­metadata, a manifest, and supporting files and resources. Visual Studio 2010 continues to
offer this same basic deployment architecture, with some noteworthy improvements for
­different platforms and application types.
How do assemblies actually work? First, assemblies are so comprehensive and ­self-describing
that Visual Studio applications don’t actually need to be formally registered with the
­operating system to run. This means that theoretically a Visual Basic 2010 application can be
installed by simply copying the assembly for the program to a second computer that has the
correct version of the .NET Framework installed—a process called XCOPY installation, after
the MS-DOS XCOPY command that copies a complete directory (folder) structure from one
location to another. In practice, however, it isn’t practical to deploy Visual Basic applications
by using a copy procedure such as XCOPY (via the command prompt) or Windows Explorer.
For commercial applications, an installation program with a graphical user interface is ­usually
preferred, and it’s often desirable to register the program with the operating system so
that it can be uninstalled later by using Control Panel. In addition, it is often useful to take
­advantage of the Web for an application’s initial deployment and to have an application
check the Web periodically for updates.
Although the advanced options related to deployment and security go beyond the scope of
this book, you should be familiar with your deployment options. To manage the deployment
process, Visual Studio 2010 supports two deployment technologies, ClickOnce and Windows
Installer.
Essentially, ClickOnce is a robust Web-based publishing technology that allows you to control
how applications are made available to users via the Internet, although ClickOnce installations
can also be distributed via CD-ROM. With ClickOnce, you can create an installation service
for Windows applications, Office solutions, or console applications that users can access on
their own with minimal interaction. With ClickOnce, you can specify prerequisites, such as
a ­particular version of the .NET Framework, and you can easily publish updates on a Web page
or a network file share to make improvements to your program. You can get started with
ClickOnce at any time by using the Publish command on the Build menu. And you can ­control
how ClickOnce works by setting properties using the Properties command on the Project
menu. (Click the Publish tab in the Project Designer for specific features.)
Chapter 2 Writing Your First Program
63
Windows Installer is a more classic installation process. In Visual Studio, you add a setup or
a Windows Installer project to your solution, which automatically creates a setup p
­ rogram
for the application. The installer package is distributed to your users, and ­individual ­users
run the setup file and work through a wizard to install the application. The setup project
can be ­customized to allow for different methods of installation, such as from CD-ROMs
or Web servers. You can get started with Windows Installer by using the New Project
­command on the File menu to create a custom setup project. (Select the Setup And
Deployment\Visual Studio Installer option under Other Project Types to see the list of
­available setup projects.)
Whether you choose ClickOnce or Windows Installer, you’ll find that Visual Studio 2010
has brought many improvements to the installation process, and these technologies will
directly benefit you and your customers. For additional information, see the online Help
­documentation related to the installation option that you want to use.
One Step Further: Adding to a Program
You can restart Visual Studio at any time and work on a programming project you’ve stored
on disk. You’ll restart Visual Studio now and add a Randomize statement to the Lucky Seven
program.
Reload Lucky Seven
1. On the Windows taskbar, click Start, click All Programs, click Microsoft Visual Studio
2010, and then click the Microsoft Visual Studio 2010 program icon (or the Microsoft
Visual Basic 2010 Express program icon, if you’re using Visual Basic 2010 Express).
A list of the projects that you’ve most recently worked on appears on the Visual Studio
Start Page in the Recent Project pane. Because you just finished working with Lucky
Seven, the MyLucky7 project should be first on the list.
2. Click the MyLucky7 link to open the Lucky Seven project.
The Lucky Seven program opens, and the MyLucky7 form appears. (If you don’t see
the form, click Form1.vb in Solution Explorer, and then click the View Designer button.)
Now you’ll add the Randomize statement to the Form_Load procedure, a ­special
­procedure that is associated with the form and that is executed each time the
­program is started.
3. Double-click the form (not one of the objects) to display the Form_Load procedure.
The Form_Load procedure appears in the Code Editor, as shown here:
64
Part I Getting Started with Microsoft Visual Basic 2010
4. Type Randomize, and then press ENTER.
The Randomize statement is added to the program and will be executed each time
the program starts. Randomize uses the system clock to create a truly random
­starting point, or seed, for the Rnd statement used in the Button1_Click procedure.
As I ­mentioned earlier, without the Randomize statement, the Lucky Seven program
produces the same string of random spins every time you restart the program. With
Randomize in place, the program spins randomly every time it runs, and the numbers
don’t follow a recognizable pattern.
5. Run the new version of Lucky Seven, and then save the project. If you plan to use the
new version a lot, you might want to create a new .exe file, too.
6. When you’re finished, click Close Project on the File menu.
The files associated with the Lucky Seven program are closed.
Chapter 2 Quick Reference
To
Do This
Create a user
interface
Use Toolbox controls to place objects on your form, and then set the
necessary properties. Resize the form and the objects as appropriate.
Move an object
Point to the object, and when a four-headed arrow appears, drag the
object.
Chapter 2 Writing Your First Program
65
To
Do This
Resize an object
Click the object to select it, and then drag the resize handle attached to the
part of the object you want to resize.
Delete an object
Click the object, and then press DELETE.
Open the Code Editor
Double-click an object on the form (or the form itself).
or
Select a form or a module in Solution Explorer, and then click the View
Code button.
Write program code
Type Visual Basic program statements associated with objects in the Code
Editor.
Save a program
On the File menu, click the Save All command.
or
Click the Save All button on the Standard toolbar.
Save a form file
Make sure the form is open, and then, on the File menu, click the Save
command.
or
Click the Save button on the Standard toolbar.
Create an .exe file
On the Build menu, click the Build or Rebuild command.
Deploy an
application by using
ClickOnce technology
Click the Publish command on the Build menu, and then use the Publish
wizard to specify the location and settings for the application.
Reload a project
On the File menu, click the Open Project command.
or
On the File menu, point to Recent Projects and Solutions, and then click
the desired project.
or
Click the project in the recent projects list on the Visual Studio Start Page.
P.
Chapter 20
Creating Web Sites and Web Pages
by Using Visual Web Developer
and ASP.NET
After completing this chapter, you will be able to:
n
Start Visual Web Developer and create a new Web site.
n
Use Visual Web Developer tools and windows, including the Web Page Designer.
n
Use the Visual Web Developer Toolbox to add server controls to Web pages.
n
Add text, formatting effects, and Visual Basic code to a Web page that calculates loan
payments for a car loan.
n
Create a Web page that displays Help information.
n
Use the HyperLink control to link one Web page to another on a Web site.
n
Use the GridView control to display a table of database information on a Web page.
n
Set the Title for a Web page and edit the master page.
In this chapter, you’ll learn how to build Web sites and Web pages by using the Visual Web
Developer tool included with Microsoft Visual Studio 2010. Visual Web Developer has the
look and feel of the Visual Studio Integrated Development Environment (IDE), but it is
­customized for Web programming and Microsoft ASP.NET 4, the Microsoft .NET Framework
component designed to provide state-of-the-art Internet functionality. Although a complete
description of Web programming and ASP.NET isn’t possible here, there’s enough in common
between Web programming and Windows programming to allow you to do some useful
experimentation—even if you have little or no experience with Hypertext Markup Language
(HTML). Invest a few hours in this chapter, and you’ll see how quickly you can build a Web
site that calculates loan payments for car loans, create a Web page with Help information,
and display loan prospects from a Microsoft Access database by using the GridView control.
Inside ASP.NET
ASP.NET 4, Microsoft’s Web development platform, has been enhanced in this release.
Some of the improvements include how Web pages are created in the Web Page Designer;
­various ­feature enhancements to ASP.NET Web pages and ASP.NET MVC; support for
­recently ­introduced browsers and handheld devices; a new ASP.NET Chart server ­control;
enhancements to the FormView, ListView, and QueryExtender controls; new dynamic data
491
492
Part IV Database and Web Programming
controls and ­enhancements; and improvements to the AJAX (Asynchronous JavaScript
and XML) ­programming model. Although ASP.NET has some similarities with an earlier Web
­programming technology named Active Server Pages (ASP), ASP.NET has been significantly
­enhanced since its first release in Visual Studio .NET 2002, and continues to evolve as new
features are added to the .NET Framework and Visual Studio software. Visual Web Developer
is the tool that you use to create and manage ASP.NET user interfaces, commonly called Web
pages or (in a more comprehensive sense) Web sites.
Tip In programming books about ASP.NET, you’ll sometimes see Web pages referred to as Web
Forms and Web sites referred to as Web applications or ASP.NET applications.
By using Visual Web Developer, you can create a Web site that displays a user ­interface,
­processes data, and provides many of the commands and features that a standard
­application for Windows might offer. However, the Web site you create is viewed in a
Web browser, such as Internet Explorer, Mozilla Firefox, Apple Safari, or even one of the
new ­mobile device types, including Google Chrome, the Research in Motion BlackBerry
smart phone, and the Apple iPhone. These Web sites are typically stored on one or more
Web ­servers, which use Microsoft Internet Information Services (IIS) to display the correct
Web pages and handle most of the computing tasks required by your Web site. (In Visual
Studio 2010, Web sites can also be located and run on a local computer that does not
­require IIS, giving you more options for development and deployment.) This ­distributed
strategy ­allows your Web sites to potentially run on a wide range of Internet-based or
­stand-alone c­ omputers—wherever your users and their rich data sources are located.
To create a Web site in Visual Studio 2010, you click the New Web Site command on the File
menu, and then use the Visual Web Developer to build one or more Web pages that will
collectively represent your Web site. Each Web page consists of two pieces:
n
A Web Forms page, which contains HTML, ASP.NET markup, and controls to create the
user interface.
n
A code-behind file, which is a code module that contains program code that “stands
behind” the Web Forms page.
This division is conceptually much like the Windows Forms you’ve been creating in Microsoft
Visual Basic—there’s a UI component and a code module component. The code for both of
these components can be stored in a single .aspx file, but typically the Web Forms page code
is stored in an .aspx file, and the code-behind file is stored in an .aspx.vb file.
In addition to Web pages, Web sites can contain code modules (.vb files), HTML pages (.htm
files), configuration information (Web.config files), global Web application information
(Global.asax files), cascading style sheet (CSS) information, scripting files (JavaScript), master
Chapter 20 Creating Web Sites and Web Pages by Using Visual Web Developer and ASP.NET
493
pages, and other components. You can use the Web Page Designer and Solution Explorer to
switch back and forth between these components quickly and efficiently.
Web Pages vs. Windows Forms
What are the important differences between Web pages and Windows Forms? To begin
with, Web pages offer a slightly different programming paradigm than Windows Forms.
Whereas Windows Forms use a Windows application window as the primary user interface
for a program, a Web site presents information to the user through one or more Web pages
with supporting program code. These pages are viewed through a Web browser, and you
can create them by using the Web Page Designer.
Like a Windows Form, a Web page can include text, graphic images, buttons, list boxes, and
other objects that are used to provide information, process input, or display output. However,
the basic set of controls you use to create a Web page is not the set on the Common Controls
tab of the Toolbox. Instead, ASP.NET Web sites must use controls on one of the tabs in the
Visual Web Developer Toolbox, including Standard, Data, HTML, and many others. Each of
the Visual Web Developer controls has its own unique methods, properties, and events, and
­although there are many similarities between these controls and Windows Forms controls,
there are also several important differences. For example, the Visual Studio DataGridView
control is called GridView in Visual Web Developer and has different properties and methods.
Many Web page controls are server controls, meaning that they run on the Web server.
Server controls have an “asp” prefix in their tag. HTML controls (located on the HTML tab
of the Visual Web Developer Toolbox) are client controls by default, meaning that they run
only within the user’s browser. For now, however, you simply need to know that you can use
server controls, HTML controls, or a combination of both in your Web site projects. As you
gain experience in Web programming, you may want to investigate AJAX programming in
Visual Studio, which can enhance the efficiency of your Web applications and add advanced
user-interface elements for users.
Server Controls
Server controls are more capable than HTML controls and function in many ways like the
Windows Forms controls. Indeed, many of the server controls have the same names as the
Windows Forms controls and offer many of the same properties, methods, and events. In
­addition to simple controls such as Button, TextBox, and Label, more sophisticated controls
such as Chart, FileUpload, LoginView, and RequiredFieldValidator are provided on a number
of tabs in the Toolbox; Visual Studio 2010 has added a number of controls to the list. The
screen shot on the following page shows a sample of the server controls in the Visual Web
Developer Toolbox. (Dynamic Data and Reporting controls are not shown.)
494
Part IV Database and Web Programming
HTML Controls
The HTML controls are a set of older user interface (UI) controls that are supported by all
Web browsers and conform closely to the early HTML standards developed for managing
UI elements on a typical Web page. They include Button, Text, and Checkbox—useful basic
controls for managing information on a Web page that can be represented entirely with HTML
code. Indeed, you might recognize these controls if you’ve coded in HTML before. However,
although they’re easy to use and have the advantage of being a “common denominator”
for Web browsers, they’re limited by the fact that they have no ability to maintain their own
state. (In other words, the data that they contain will be lost between views of a Web page.)
The following screen shot shows the HTML controls offered on the HTML tab of the Toolbox
in Visual Web Developer:
Chapter 20 Creating Web Sites and Web Pages by Using Visual Web Developer and ASP.NET
495
Building a Web Site by Using Visual
Web Developer
The best way to learn about Visual Web Developer and ASP.NET is to get some ­hands­-on
practice. In the exercises in this chapter, you’ll create a simple car loan calculator that
­determines monthly payments and contains an About tab that explains how the program
works. Later in the chapter, you’ll use the GridView control to display a table of data on
a Web page in the same Web site. You’ll begin by verifying that Visual Studio is properly
configured for ASP.NET programming, and then you’ll create a new Web site project. Next,
you’ll use the Web Page Designer to create a Web page with text and links on it, and you’ll
use controls in the Visual Web Developer Toolbox to add controls to the Web page.
Considering Software Requirements
for ASP.NET Programming
Before you can create your first ASP.NET Web site, you need to make sure your computer is
set up properly. To perform ASP.NET programming, you need to have Visual Web Developer
installed. Visual Web Developer is a component of Visual Studio 2010 Professional, Premium,
and more advanced editions. You can also download Visual Web Developer 2010 Express at
http://www.microsoft.com/express/Web/, and it contains almost all the features described in this
chapter (I’ll point out any differences as we go). If you are using Visual Web Developer 2010
Express, be sure to set the settings to Expert by clicking the Tools menu, clicking Settings, and
then clicking Expert Settings. This will ensure that the steps in this chapter more closely match
your software.
Visual Studio 2010 and Visual Web Developer include their own local Web server, so setting up
and configuring a Web server with Microsoft Internet Information Services (IIS) and the .NET
Framework is not required. Having a local Web server makes it easy to create and test your
ASP.NET Web sites, and you’ll see it described below as the ASP.NET Development Server.
In Visual Studio 2010, you can create and run your Web site in one of three locations:
n
Your own computer (via the ASP.NET Development Server)
n
An HTTP server that contains IIS and related components
n
An FTP site (a remote file server)
The first location is the option we’ll use in this book because it requires no additional
­hardware or software. In addition, when you develop your Web site on the local file system,
all the Web site files are stored in one location. When you’re finished testing the application,
you can deploy the files to a Web server of your choosing.
496
Part IV Database and Web Programming
Create a new Web site
1. Start Visual Studio, and then click the New Web Site command on the File menu.
Note If you don’t see the New Web Site command on the File menu, then you don’t have
Visual Web Developer installed. To download Visual Web Developer Express, visit
http://www.microsoft.com/express/Web/ and follow the installation instructions.
Although you might have seen the New Web Site command before, we haven’t used it
yet in this book. This command starts Visual Web Developer and prepares Visual Studio
to build a Web site. You see a New Web Site dialog box similar to the following:
In this dialog box, you can select the Web site or application template, the location for
the Web site (local file system, HTTP server, or FTP site), and the programming ­language
that you want to use (Visual Basic or Microsoft Visual C#). You can also identify the
­version of the .NET Framework that you want to target with your Web application.
(Version 4 offers the most features, but there are times that you may need to design
­specifically for platforms with an earlier version of the .NET Framework. However, Visual
Web Developer 2010 Express does not provide the option of targeting a specific version
of the .NET Framework.)
2. In the New Web Site dialog box, verify that Visual Basic is the selected language and
that ASP.NET Web Site is the selected template.
3. In the Web Location list, make sure that File System is selected.
4. Type C:\Vb10sbs\MyChap20 in the File Name text box.
Although you have been specifying the folder location for projects after you have
built the projects in this book, in Visual Web Developer, projects are saved up front.
Chapter 20 Creating Web Sites and Web Pages by Using Visual Web Developer and ASP.NET
497
The “my” prefix in the path will avoid a conflict with the solution Web site in the
­practice files (C:\Vb10sbs\Chap20) that I’ve built for you.
5. Click OK to accept your selections.
Visual Studio loads Visual Web Developer and creates a Web page (Default.aspx) to
contain the user interface and a code-behind file (Default.aspx.vb) that will store the
code for your Web page.
6. If you don’t see Default.aspx open in the Web Page Designer, double-click Default.aspx
in Solution Explorer now to open it.
7. At the bottom of the Web Page Designer, click the Design tab.
Your screen looks something like the one shown in the following screen shot:
Unlike the Windows Forms Designer, the Web Page Designer displays the Web page in
three possible views in the IDE, and three tabs at the bottom of the Designer (Design,
Split, and Source) allow you to change your view of the Web page.
The Design tab shows you approximately how your Web page will look when a Web
browser displays it. When the Design tab is selected, a basic template page (“My ASP.NET Application”) appears in the Designer with the result of source-code
­formatting, and you can add controls to your Web page and adjust how objects on
the page are arranged.
On the Source tab, you can view and edit the HTML and ASP.NET markup that’s used to
display the Web page in a Web browser. If you’ve used Microsoft Expression Web, you’ll
498
Part IV Database and Web Programming
be familiar with these two ways of displaying a Web page and perhaps also with some
of the HTML tags that control how Web pages are actually displayed. The Split tab
­offers a composite view of the Design and Source tabs.
A few additional differences between the Windows Forms Designer and the Web
Page Designer are worth noting at this point. The Toolbox now contains several
­collections of controls used exclusively for Web programming. Solution Explorer also
contains a different list of project files for the Web site you’re building, as shown in the
­following screen shot. In particular, notice the Default.aspx file in Solution Explorer;
this file ­contains the UI code for the active Web page. Nested under the Default.aspx
file, you’ll find a file named Default.aspx.vb. A configuration file named Web.config
and a master page file named Site.master are also listed.
Note When you close your new Web site and exit Visual Web Developer, note that you open
the Web site again by clicking the Visual Studio File menu and then clicking the Open Web Site
command. Web sites are not opened by using the Open Project command on the File menu.
Now you’re ready to add some text to the Web page by using the Web Page Designer.
Using the Web Page Designer
Unlike a Windows Form, a Web page can have text added directly to it when it is in the Web
Page Designer. In Source view, the text appears within HTML and ASP.NET tags somewhat as
it does in the Visual Studio Code Editor. In Design view, the text appears in top-to-bottom
fashion within a grid as it does in a word processor such as Microsoft Word, and you’ll see no
HTML. In the next exercises, you’ll type text in Design view, edit it, and then make formatting
changes by using buttons on the Formatting toolbar. Manipulating text in this way is usually
Chapter 20 Creating Web Sites and Web Pages by Using Visual Web Developer and ASP.NET
499
much faster than adding a Label control to the Web page to contain the text. You’ll practice
entering the text for your car loan calculator in the following exercise.
Add text in Design view
1. Click the Design tab, if it is not currently selected, to view the Web Page Designer in
Design view.
A faint rectangle appears at the top of the Web page, near the template text
“WELCOME TO ASP.NET.” The template text is there to show you how text appears on
a Web Form, and where you can go to get additional information about ASP.NET. You’ll
also notice that your Web page has Home and About tabs, which are provided for you
as part of your default page.
2. Position your insertion point at the end of the text “WELCOME TO ASP.NET.”
A blinking I-beam appears at the end of the line.
3. Press the BACKSPACE key to remove “WELCOME TO ASP.NET,” and then type Car Loan
Calculator.
Visual Studio displays the title of your Web page exactly as it will appear when you
open the Web site in your browser.
4. Delete the line beginning with “To learn more about ASP.NET. . .,” and in its place, type
the following sentence:
Enter the required information and click Calculate!
5. Delete the sentence in the template beginning with “You can also find
­documentation. . .”
Now you’ll use the Formatting toolbar to format the title with italic formatting
and a different color.
6. Right-click the Standard toolbar in Visual Web Developer to display the list of toolbars
available in the IDE.
7. If you do not see a check mark next to Formatting in this list, click Formatting to add
the Formatting toolbar.
The Formatting toolbar now appears in the IDE if it was not already visible. Notice that
it contains a few features not usually found on a text formatting toolbar.
8. Select the text “Car Loan Calculator.”
Before you can format text in Visual Web Developer, you must select it.
9. Click the Italic button on the Formatting toolbar.
10. On the Format menu, click the Font command, click Red in the Color list box, and then
click OK.
500
Part IV Database and Web Programming
Your screen looks like this:
Now, you’ll examine the HTML and ASP.NET markup for the text and formatting you entered.
View the HTML and ASP.NET markup for a Web page
1. Click the Source tab at the bottom of the Designer.
The Source tab displays the actual HTML and ASP.NET markup for your Web page.
To see more of the markup, you might want to resize a few programming tools
­temporarily and use the document scroll bars. The markup looks like the following
­screen shot. Your markup might have some differences.
Chapter 20 Creating Web Sites and Web Pages by Using Visual Web Developer and ASP.NET
501
A Web page is made up of page information, scripting code, cascading style sheet (CSS)
information, HTML tags, ASP.NET tags, image references, objects, and text. The @ Page
directive contains information about the language you selected when creating the Web
application, the name of any code-behind file, and any inherited forms.
HTML and ASP.NET tags typically appear in pairs so that you can see clearly where
a section begins and ends. For example, the <style> tag identifies the beginning of
text formatting, and the </style> tag identifies the end. Notice that the “Car Loan
Calculator” text appears within <em></em> tags to make the text italic. Below the
“Car Loan Calculator” text, the second line of text you entered is displayed.
Tip Remember that the Source tab is an actual editor, so you can change the text that you
entered by using standard text editing techniques. If you know something about HTML
and ASP.NET, you can add other tags and content as well.
2. Click the Design tab to display your Web page in Design view, and open the Toolbox if
it is not visible.
Adding Server Controls to a Web Site
Now you’ll add TextBox, Label, and Button controls to the car loan calculator. Although
these controls are located in the Visual Web Developer Toolbox, they’re very similar to the
Windows Forms controls of the same name that you’ve used throughout this book. (I’ll
cover a few of the important differences as they come up.) The most important thing to
­remember is that in the Web Page Designer, controls are inserted at the insertion point if you
­double-click the control name in the Toolbox. After you add the controls to the Web page,
you’ll set property settings for the controls.
Use TextBox, Label, and Button controls
1. Display the Standard tab of the Toolbox, if it isn’t already visible.
2. Position the insertion point below the last line of text on the Web page, and then press
ENTER to create a little blank space below the text for the controls.
Because controls are placed at the insertion point, you need to use the text editing keys
to position the insertion point appropriately before double-clicking a control in the
Toolbox.
Note By default, the Web Page Designer positions controls relative to other controls.
This is an important difference between the Web Page Designer and the Windows Forms
Designer. The Windows Forms Designer allows you to position controls wherever you
like on a form. You can change the Web Page Designer so that you can position controls
­wherever you like on a Web page (called absolute positioning); however, you might get
­different behavior in different Web browsers.
502
Part IV Database and Web Programming
3. Double-click the TextBox control on the Standard tab of the Toolbox to create a text
box object at the insertion point on the Web page.
Notice the asp:textbox#TextBox1 text that appears above the text box object. The “asp”
prefix indicates that this object is an ASP.NET server control. (This text disappears when
you run the program.)
4. Click the right side of the text box object to place the insertion point at the outside
edge, and then press ENTER.
5. Double-click the TextBox control again to add a second text box object to the
Web page.
6. Repeat Steps 4 and 5 to create a third text box object below the second text box.
Now you’ll use the Label control to insert labels that identify the purpose of the text
boxes.
7. Click to the right of the first text box object to place the insertion point at the right
edge of the text box.
8. Press the SPACEBAR key twice to add two blank spaces, and then double-click the Label
control in the Toolbox to add a label object to the Web page.
9. Repeat Steps 7 and 8 to add label objects to the right of the second and third text boxes.
10. Click to the right of the third label object to place the insertion point to the right of the
label, and then press ENTER.
11. Double-click the Button control to create a button object at the bottom of the Web page.
The Button control, like the TextBox and Label controls, is very similar to its Windows
Forms counterpart. Your screen looks like this:
Chapter 20 Creating Web Sites and Web Pages by Using Visual Web Developer and ASP.NET
503
Now you’ll set a few properties for the seven new controls you have created on the Web
page. If it is not already visible, open the Properties window by pressing F4. As you set
the properties, you’ll notice one important difference between Web pages and Windows
Forms—the familiar Name property has been changed to ID in Visual Web Developer.
Despite their different names, the two properties perform the same function.
12. Set the following properties for the objects on the form:
Object
Property
Setting
TextBox1
ID
txtAmount
TextBox2
ID
txtInterest
TextBox3
ID
txtPayment
Label1
ID
lblAmount
Text
“Loan Amount”
ID
lblInterest
Text
“Interest Rate (for example, 0.09)”
ID
lblPayment
Text
“Monthly Payment”
ID
btnCalculate
Text
“Calculate”
Label2
Label3
Button1
Your Web page looks like this:
504
Part IV Database and Web Programming
Writing Event Procedures for Web Page Controls
You write default event procedures (or event handlers) for controls on a Web page by
double-clicking the objects on the Web page and typing the necessary program code in
the Code Editor. Although the user will see the controls on the Web page in his or her own
Web browser, the actual code that’s executed will be located on the local test computer or
a Web server, depending on how you configured your project for development and how it
is eventually deployed. For example, when the user clicks a button on a Web page that is
hosted by a Web server, the browser sends the button click event back to the server, which
processes the event and sends a new Web page back to the browser. Although the process
seems similar to that of Windows Forms, there’s actually a lot going on behind the scenes
when a control is used on an ASP.NET Web page!
In the following exercise, you’ll practice creating the default event procedure for the
­btnCalculate object on the Web page.
Create the btnCalculate_Click event procedure
1. Double-click the Calculate button on the Web page.
The code-behind file (Default.aspx.vb) opens in the Code Editor, and the btnCalculate_
Click event procedure appears.
2. Type the following program code:
Dim LoanPayment As Double
'Use Pmt function to determine payment for 36 month loan
LoanPayment = Pmt(CDbl(txtInterest.Text) / 12, 36, CDbl(txtAmount.Text))
txtPayment.Text = Format(Abs(LoanPayment), "$0.00")
This event procedure uses the Pmt function, a financial function that’s part of the Visual
Basic language, to determine what the monthly payment for a car loan would be by ­using
the specified interest rate (txtInterest.Text), a three-year (36-month) loan period, and the
specified principal amount (txtAmount.Text). The result is stored in the LoanPayment
double-precision variable, and then it is formatted with appropriate monetary formatting
and displayed by using the txtPayment text box object on the Web page.
The two Text properties are converted from string format to double-precision format
by using the CDbl function. The Abs (absolute value) function is used to make the
loan payment a positive number. (Abs currently has a jagged underline in the Code
Editor because it relies on the System.Math class, which you’ll specify next.) Why make
the loan payment appear as a positive number? The Pmt function returns a negative
number by default (reflecting money that’s owed), but I think negative formatting
looks strange when it isn’t part of a balance sheet, so I’m converting it to positive.
Chapter 20 Creating Web Sites and Web Pages by Using Visual Web Developer and ASP.NET
505
Notice that the program statements in the code-behind file are just regular Visual Basic
code—the same stuff you’ve been using throughout this book. Basically, the process
feels similar to creating a Windows application.
3. Scroll to the top of the Code Editor, and then enter the following program statement as
the first line of the file:
Imports System.Math
As you learned in Chapter 5, “Visual Basic Variables and Formulas, and the .NET
Framework,” the Abs function isn’t included in Visual Basic by default, but it is part of
the System.Math class in the .NET Framework and can be more easily referenced in
your project by the Imports statement. Web applications can make use of the .NET
Framework class libraries just as Windows applications can.
The Code Editor looks like this:
4. Click the Save All button on the Standard toolbar.
That’s it! You’ve entered the program code necessary to run the car loan calculator and make
your Web page interactive. Now you’ll build and run the project and see how it works. You’ll
also learn a little bit about security settings within Internet Explorer, a topic closely r­ elated to
Web development.
Build and view the Web site
1. Click the Start Debugging button on the Standard toolbar.
Visual Studio starts the ASP.NET Development Server, which runs ASP.NET applications
locally (on your own computer) so that you can test this application. A status balloon
appears at the bottom of your screen and lets you know the local Uniform Resource
506
Part IV Database and Web Programming
Locator (URL) on your computer that has been established, as shown in the following
screen shot. You’ll also see a message about debugging:
The potentially confusing Debugging Not Enabled dialog box is not a major concern.
Visual Web Developer is just indicating that the Web.config file in your project does
not currently allow debugging (a standard security feature). Although you can bypass
this dialog box each time that you test the application within Visual Web Developer by
clicking the Run Without Debugging button, I recommend that you modify the Web.
config file now.
Security Tip Before you widely distribute or deploy a real Web site, be sure to disable
­debugging in Web.config to keep your application safe from unauthorized tampering.
2. Click OK to modify the Web.config file.
Visual Studio modifies the file, builds your Web site, and displays the opening Web
page in Internet Explorer.
The car loan calculator looks like the screen shot on the following page. If Internet
Explorer does not appear, you might need to select it on the Windows taskbar.
Chapter 20 Creating Web Sites and Web Pages by Using Visual Web Developer and ASP.NET
507
Security Tip You might see the Information Bar at the top of Internet Explorer ­indicating
that intranet settings are turned off by default. An intranet warning is again related to
Internet Explorer’s design to protect you from rogue programs or unauthorized access.
An intranet is a local network (typically a home network or small workgroup network),
and because Visual Studio uses intranet-style addressing when you test Web sites built on
your own computer, you’re likely to see this warning message. To suppress the ­warning
temporarily, click the Information Bar and then click Don’t Show Me This Again. To remove
intranet warnings more permanently, click the Internet Options command on the Tools
menu of Internet Explorer, click the Security tab, and then click Local Intranet. Click the
Sites button, and clear the check mark from Automatically Detect Intranet Network in
the Local Intranet dialog box. However, exercise caution whenever you disable security
­warnings, as they are meant to protect you.
Now, let’s get back to testing our Web page.
3. Type 18000 in the Loan Amount text box, and then type 0.09 in the Interest Rate
text box.
You’ll compute the monthly loan payment for an $18,000 loan at 9 percent interest for
36 months.
508
Part IV Database and Web Programming
4. Click the Calculate button.
Visual Basic calculates the payment amount and displays $572.40 in the Monthly
Payment text box. Your screen looks like this:
5. Close Internet Explorer.
You’re finished testing your Web site for now. When Internet Explorer closes, your
­program is effectively ended. As you can see, building and viewing a Web site is
­basically the same as building and running a Windows application, except that the
Web site is executed in the browser. You can even set break points and debug your
application just as you can in a Windows application.
Curious about installing a Web site like this on an actual Web server? The basic procedure for
deploying Web sites is to copy the .aspx files and any necessary support files for the project
to a properly configured virtual directory on a Web server running IIS and .NET Framework 4.
There are a couple of ways to perform deployment in Visual Web Developer. To get started,
click Copy Web Site on the Website menu, or click Publish Web Site on the Build menu.
(Visual Web Developer 2010 Express does not include the Publish Web Site command.)
For more information about your options, see “ASP.NET Deployment Content Map” in the
Visual Studio Help documentation. To find a hosting company that can host ASP.NET Web
­applications, you can check out http://www.asp.net.
Chapter 20 Creating Web Sites and Web Pages by Using Visual Web Developer and ASP.NET
509
Validating Input Fields on a Web Page
Although this Web page is useful, it runs into problems if the user forgets to enter
a principal amount or an interest rate or specifies data in the wrong format. To make
Web sites like this more robust, I usually add one or more validator controls that
force users to enter input in the proper format. The validator controls are located on
the Validation tab of the Visual Web Developer Toolbox and include controls that
­require data entry in a field (RequiredFieldValidator), require entry in the proper range
(RangeValidator), and so on. For information on the validator controls, search the Visual
Studio Help documentation. They are straightforward to use.
Customizing the Web Site Template
Now the fun begins! Only very simple Web sites consist of just one Web page. Using Visual
Web Developer, you can expand your Web site quickly to include additional information and
resources, including HTML pages, XML pages, text files, database records, Web services, login
sessions, site maps, and more. If you want to add a Web page, you have three options:
n
You can create a new Web page by using the HTML Page template or the Web Form
template. You select these templates by using the Add New Item command on the
Website menu. After you create the page, you add text and objects to the page by
­using the Web Page Designer.
n
You can add a Web page that you have already created by using the Add Existing
Item command on the Web site menu, and then customize the page in the Web Page
Designer. You use this method if you want to include one or more Web pages that you
have already created in a tool such as Expression Web. (If possible, add pages that don’t
rely on external style sheets and resources, or you’ll need to add those items to the
project as well.)
n
You can use an existing Web page that is part of the Web site template that you are
using. For example, in the Web site template that you have open now, there is an About
Web page and various Login Web pages that you can customize and use quickly.
In the following exercise, you’ll display the About Web page supplied by the template that you
are using, and you will customize it with some information about how the car loan calculator
application works.
Customize the About.aspx Web page
1. Display Solution Explorer, click the About.aspx file, and click the View Designer button.
Visual Web Designer displays About.aspx in the Designer, and it displays a line of
­placeholder text (“Put content here.”).
510
Part IV Database and Web Programming
2. Delete the placeholder text, and then type the following information:
Car Loan Calculator
The Car Loan Calculator Web site was developed for the book Microsoft Visual
Basic 2010 Step by Step, by Michael Halvorson (Microsoft Press, 2010). The Web
site is best viewed using Microsoft Internet Explorer version 6.0 or later. To learn
more about how this ADO.NET application was created, read Chapter 20 in the
book.
Operating Instructions:
Type a loan amount, without dollar sign or commas, into the Loan Amount box.
Type an interest rate in decimal format into the Interest Rate text box. Do not
include the “%” sign. For example, to specify a 9% interest rate, type “0.09.”
Note that this loan calculator assumes a three-year, 36-month payment period.
Click the Calculate button to compute the basic monthly loan payment that does
not include taxes or other fees.
3. Using buttons on the Formatting toolbar, add bold formatting for the headings and
italic for the book title, as shown here:
4. Click the Save All button on the Standard toolbar to save your changes.
5. Click the Start Debugging button.
Visual Studio builds the Web site and displays it in Internet Explorer.
Chapter 20 Creating Web Sites and Web Pages by Using Visual Web Developer and ASP.NET
511
6. Click the Home tab on the Web page.
Visual Studio displays the Home page for your Web site, the car loan calculator.
7. Compute another loan payment to experiment further with the loan calculator.
If you want to test another set of numbers, try entering 20000 for the loan amount
and 0.075 for the interest rate. The result should be $622.12.
8. Now click the About tab to view the About Web page with instructions for your
program.
Internet Explorer displays the About page on the screen. Your browser looks something
like this:
9. Read the text, and then click the Back button in Internet Explorer.
Just like any Web site, this one lets you click the Back and Forward buttons to jump
from one Web page to the next.
10. Close Internet Explorer to close the Web site.
You’ve added a simple About page to your Web site, and you have experimented
with moving from one page to the next. Pretty cool so far. Now, try something more
­sophisticated that shows how far you can take your Web site if you choose to include
information from a database.
512
Part IV Database and Web Programming
Displaying Database Records on a Web Page
For many users, one of the most exciting aspects of the World Wide Web is the ability to
access large amounts of information rapidly through a Web browser. Often, of course, the
quantity of information that needs to be displayed on a commercial Web site far exceeds
what a developer can realistically prepare using simple text documents. In these cases, Web
programmers add database objects to their Web sites to display tables, fields, and records
of database information on Web pages, and they connect the objects to a secure database
­residing on the Web server or another location.
Visual Studio 2010 makes it easy to display simple database tables on a Web site, so as
your computing needs grow, you can use Visual Studio to process orders, handle security,
­manage complex customer information profiles, and create new database records—all
from the Web. Importantly, Visual Web Developer delivers this power very effectively.
For example, by using the GridView control, you can display a database table ­containing
dozens or thousands of records on a Web page without any program code. You’ll see
how this works by completing the following exercise, which adds a Web page ­containing
loan contact data to the Car Loan Calculator project. If you completed the database
­programming exercises in Chapter 18, “Getting Started with ADO.NET,” and Chapter 19,
“Data Presentation Using the DataGridView Control,” be sure to notice the similarities
(and a few differences) between database programming in a Windows environment and
­database programming on the Web.
Add a new Web page for database information
1. Click the Add New Item command on the Website menu.
Visual Web Developer displays a list of components that you can add to your Web site.
2. Click the Web Form template, type FacultyLoanLeads.aspx in the Name text box, and
then click Add.
Visual Web Developer adds a new Web page to your Web site. You’ll customize it with
some text and server controls.
3. Click the Design tab to switch to Design view.
4. Enter the following text at the top of the Web page:
The following grid shows instructors who want loans and their contact phone
numbers:
5. Press ENTER twice to add two blank lines below the text.
Remember that Web page controls are added to Web pages at the insertion point, so it
is always important to create a few blank lines when you are preparing to add a control.
Next, you’ll display two fields from the Faculty table of the Faculty2010.accdb database by
adding a GridView control to the Web page. GridView is similar to the DataGridView control
you used in Chapter 19, but GridView has been optimized for use on the Web. (There are also
Chapter 20 Creating Web Sites and Web Pages by Using Visual Web Developer and ASP.NET
513
a few other differences, which you can explore by using the Properties window and Visual
Studio Help documentation.) Note that I’m using the same Access database table I used
in Chapters 18 and 19, so you can see how similar database programming is in Visual Web
Developer. Many programmers also use SQL databases on their Web sites, and Visual Web
Developer also handles that format very well.
Add a GridView control
1. With the new Web page open and the insertion point in the desired location,
­double-click the GridView control on the Data tab of the Visual Web Developer
Toolbox.
Visual Web Developer adds a grid view object named GridView1 to the Web page. The
grid view object currently contains placeholder information.
2. If the GridView Tasks list is not already displayed, click the GridView1 object’s smart tag
to display the list.
3. Click the Choose Data Source arrow, and then click the <New Data Source> option.
4. Visual Web Developer displays the Data Source Configuration Wizard, a tool that you
used in Chapters 18 and 19 to establish a connection to a database and select the
tables and fields that will make up a dataset.
Your screen looks like this:
514
Part IV Database and Web Programming
5. Click the Access Database icon, type Faculty2010 in the Specify An ID For The Data
Source box, and then click OK.
You are now prompted to specify the location of the Access database on your system.
(This dialog box is slightly different than the one you used in Chapter 18.)
6. Type C:\Vb10sbs\Chap18\Faculty2010.accdb, and then click Next.
Note If you get a message that says “The Microsoft.ACE.OLEDB.12.0 provider is not
r­ egistered on the local machine,” you might not have Access 2007 or later installed. If you
don’t have Access 2007 or later installed, you will need to download and install the 2007
Office System Driver: Data Connectivity Components from Microsoft.com.
You are now asked to configure your data source; that is, to select the table and fields
that you want to display on your Web page. Here, you’ll use two fields from the Faculty
table. (Remember that in Visual Studio, database fields are often referred to as columns,
so you’ll see the word columns used in the IDE and the following instructions.)
7. Click the Name list box arrow, and then click Faculty. (There is probably only one or two
database tables here, but if there are several, click the Name arrow to view them.)
8. Select the Last Name and Business Phone check boxes in the Columns list box.
Your screen looks like this:
Chapter 20 Creating Web Sites and Web Pages by Using Visual Web Developer and ASP.NET
515
Through your actions here, you are creating an SQL SELECT statement that configures
a dataset representing a portion of the Faculty2010.accdb database. You can see the
SELECT statement at the bottom of this dialog box.
9. Click Next to see the Test Query screen.
10. Click the Test Query button to see a preview of your data.
You’ll see a preview of actual Last Name and Business Phone fields from the database.
This data looks as expected, although if we were preparing this Web site for wider
distribution, we would take the extra step of formatting the Business Phone column
so that it contains standard spacing and phone number formatting.
11. Click Finish.
Visual Web Developer closes the wizard and adjusts the number of columns and
column headers in the grid view object to match the selections that you have made.
However, it continues to display placeholder information (“abc”) in the grid view cells.
12. With the GridView Tasks list still open, click the Auto Format command.
13. Click the Professional scheme.
The AutoFormat dialog box looks like this:
The ability to format, adjust, and preview formatting options quickly is a great feature
of the GridView control.
14. Click OK, and then close the GridView Tasks list.
The FacultyLoanLeads.aspx Web page is complete now, and looks like the screen
shot on the following page. (My GridView control is within a <div> tag, but yours
might be within a <p> tag.)
516
Part IV Database and Web Programming
Now, you’ll add a hyperlink on the first Web page (or home page) that will display this Web
page when the user wants to see the database table. You’ll create the hyperlink with the
HyperLink control, which has been designed to allow users to jump from the current Web
page to a new one with a simple mouse click.
How does the HyperLink control work? The HyperLink control is located in the Standard
Toolbox. When you add a HyperLink control to your Web page, you set the text that will be
displayed on the page by using the Text property, and then you specify the desired Web page
or resource to jump to (either a URL or a local path) by using the NavigateUrl property. That’s
all there is to it.
Add a hyperlink to the home page
1. Click the Default.aspx tab at the top of the Designer.
The home page for your Web site opens in the Designer.
2. Click to the right of the Calculate button object to place the insertion point after that
object.
Chapter 20 Creating Web Sites and Web Pages by Using Visual Web Developer and ASP.NET
3. Press ENTER to create space for the hyperlink object.
4. Double-click the HyperLink control on the Standard tab of the Toolbox to create
a ­hyperlink object at the insertion point.
5. Select the hyperlink object, and then set the Text property of the object to “Display
Loan Prospects.”
517
We’ll pretend that your users are bank loan officers (or well-informed car salespeople)
looking to sell auto loans to university professors. Display Loan Prospects will be the
link that they click to view the selected database records.
6. Set the ID property of the hyperlink object to “lnkProspects.”
7. Click the NavigateUrl property, and then click the ellipsis button in the second column.
The Select URL dialog box opens.
8. Click the FacultyLoanLeads.aspx file in the Contents Of Folder list box, and then
click OK.
9. Click Save All to save your changes.
Your link is finished, and you’re ready to test the Web site and GridView control in your
browser.
Test the final Car Loan Calculator Web site
Tip The complete Car Loan Calculator Web site is located in the C:\Vb10sbs\Chap20\
Chap20 folder. Use the Open Web Site command on the File menu to open an existing
Web site.
1. Click the Start Debugging button.
Visual Studio builds the Web site and displays it in Internet Explorer.
2. Enter 8000 for the loan amount and 0.08 for the interest rate, and then click Calculate.
The result is $250.69. Whenever you add to a project, it is always good to go back and
test the original features to verify that they have not been modified inadvertently. Your
screen looks like the screen shot on the following page.
518
Part IV Database and Web Programming
The new hyperlink (Display Loan Prospects) is visible at the bottom of the Web page.
3. Click Display Loan Prospects to load the database table.
Internet Explorer loads the Last Name and Business Phone fields from the Faculty2010.
accdb database into the grid view object. Your Web page looks something like this:
Chapter 20 Creating Web Sites and Web Pages by Using Visual Web Developer and ASP.NET
519
The information is nicely formatted and appears useful. By default, you’ll find that the
data in this table cannot be sorted, but you can change this option by selecting
the Enable Sorting check box in GridView Tasks. If your database contains many rows
(­records) of information, you can select the Enable Paging check box in GridView Tasks
to display a list of page numbers at the bottom of the Web page (like a list that you
might see in a search engine that displays many pages of “hits” for your search).
4. Click the Back and Forward buttons in Internet Explorer.
As you learned earlier, you can jump back and forth between Web pages in your Web
site, just as you would in any professional Web site.
5. When you’re finished experimenting, close Internet Explorer to close the Web site.
You’ve added a table of custom database information without adding any program code!
One Step Further: Setting Web Site Titles
in Internet Explorer
Haven’t had enough yet? Here are two last Web programming tips to enhance your Web site
and send you off on your own explorations.
You might have noticed while testing the Car Loan Calculator Web site that Internet Explorer
displayed “Home Page” in the title bar and window tab when displaying your Web site. Your
program also displays the very large template title “MY ASP.NET APPLICATION” at the top
of the window. In other words, your screen looked like this:
You can customize what Internet Explorer and other browsers display in the title bar by ­setting
the Title property of the DOCUMENT object for your Web page; and you can modify the
“MY ASP.NET APPLICATION” string by editing the site master page. Give editing both values
a try now.
Set the Title property
1. With the Default.aspx Web page open in Design view, click the DOCUMENT object in
the Object list box at the top of the Properties window.
520
Part IV Database and Web Programming
Each Web page in a Web site contains a DOCUMENT object that holds important
general settings for the Web page. However, the DOCUMENT object is not selected
by default in the Designer, so you might not have noticed it. One of the important
­properties for the DOCUMENT object is Title, which sets the title of the current Web
page in the browser.
2. Set the Title property to “Car Loan Calculator.”
The change does not appear on the screen, but Visual Web Developer records it internally.
Now, change the title of your application in the site master page.
Edit the master page title
1. Click the Site.Master file in Solution Explorer, and then click the View Designer button.
Visual Studio displays the master page in the Designer. The master page is a template
that provides default settings for your Web site and lets you adjust characteristics such
as ­appearance, banner titles, menus, and links. For example, you can click smart tags
­associated with the Web site’s menu items and adjust them much as you customized
menus in Chapter 4, “Working with Menus, Toolbars, and Dialog Boxes.”
Your screen looks like this:
Chapter 20 Creating Web Sites and Web Pages by Using Visual Web Developer and ASP.NET
2. Delete the title “MY ASP.NET APPLICATION” and type TIME FOR A NEW CAR?
521
Visual Web Designer enters your new title. Now run the Web site again.
3. Click the Start Debugging button.
Visual Studio opens Internet Explorer and loads the Web site. Now a more useful title
bar and banner message appears, as shown in the following screen shot:
Now that looks better.
4. Close Internet Explorer, and then update the Title properties for the other Web pages
on your Web site.
5. When you’re finished experimenting with the Car Loan Calculator, save your changes
and close Visual Studio.
Congratulations on completing the entire Microsoft Visual Basic 2010 Step by Step
­programming course! Take a few moments to flip back through this book and see all that
you have learned. Now you’re ready for more sophisticated Visual Basic challenges and
­programming techniques. Check out the resource list in the Appendix, “Where to Go for More
Information,” for a few ideas about continuing your learning. But take a break first—you’ve
earned it!
522
Part IV Database and Web Programming
Chapter 20 Quick Reference
To
Do This
Create a new ASP.NET
Web site
Click the New Web Site command on the File menu, click the
ASP.NET Web Site template, specify a folder location in the Web
Location list box, and then click OK.
Switch between Design view
and Source view in the Web
Page Designer
Click the Source or Design tabs in the Web Page Designer. For a
mixed view, click the Split tab.
Enter text on a Web page
Click the Design tab, and then type the text you want to add.
Format text on a Web page
On the page, select the text that you want to format, and then click
a button or control on the Formatting toolbar. Additional formatting
options are available on the Format menu.
View the HTML and ASP.NET
markup in your Web page
Click the Source tab in the Web Page Designer.
Add controls to a Web page
Display the Web page in Design view, open the Toolbox (which
automatically contains Visual Web Developer controls), position
the insertion point where you want to place the control on the page,
and then double-click the control in the Toolbox.
Change the name of an
object on a Web page
Use the Properties window to change the object’s ID property to
a new name.
Write the default event
procedure for an object on
a Web page
Double-click the object to display the code-behind file, and then
write the event procedure code for the object in the Code Editor.
Verify the format of the data
entered by the user into
a control on a Web page
Use one or more validator controls from the Validation tab of the
Toolbox to test the data entered in an input control.
Run and test a Web site in
Visual Studio
Click the Start Debugging button on the Standard toolbar. Visual
Studio builds the project, starts the ASP.NET Development Server,
and loads the Web site in Internet Explorer.
Create a Web page for
a project
Click the Add New Item command on the Website menu, and then
add a new Web Form or an HTML Page template to the project.
Create and format the page by using the Web Page Designer.
Create a link to other Web
pages on your Web site
Add a HyperLink control to your Web page, and then set the
control’s NavigateUrl property to the address of the linked
Web page.
Display database records
on a Web page
Add a GridView control to a Web page in the Web Page Designer.
Establish a connection to the database and format the data by using
commands in the GridView Tasks list. (The Choose Data Source
command starts the Data Source Configuration Wizard.)
Set the title displayed for
Web pages on the Internet
Explorer title bar
For each Web page, use the Properties window to set the
DOCUMENT object’s Title property.
Adjust the banner title,
menus, and other default
values in the master page
Select the Site.Master file in Solution Explorer, and then click View
Designer. Adjust the master page’s default values in the Designer.
Index
Symbols
and Numbers
- (subtraction operator),
143, 147
& (string concatenation operator),
75, 147, 149, 184
* (multiplication operator),
143, 147
. . . (ellipsis), in menu
commands, 100
.gif files, 113
.jpeg files, 113
.NET Framework
accessing Help files for, 28
Array class, 288–89
Exception objects, 236–37
identifying version of, 496
Imports statement, 243
math methods, 152–55
MSDN Help in, 28
My namespace, 314–16
overview, 153
specifying version in new
projects, 39
StreamReader class,
316–17
String class, 327
System.Drawing
namespace, 376
System.lO namespace, 242
System.Math class, 154
.png files, 113
/ (division operator),
143, 147
@ Page directive, 501
\ (backslash), 147
^ (exponential operator),
43, 147, 149
_ (line continuation character),
75, 187
| (pipe symbol), 113
+ (addition operator), 143, 147
< (less than operator), 161, 331
<= (less than or equal to operator),
161, 331
<> (not equal to operator),
161, 331
= (assignment or equal to operator),
161, 182, 331
= (assignment or equal to), 125
> (greater than operator), 161, 331
>= (greater than or equal to
operator), 161, 331
>cmd command, using to switch to
Command Window, 223
A
Abs(n) method, 152, 504–05
absolute path names, 89
Access databases,
working with, 444
access keys
adding, 100–02, 119
defined, 99
displaying, in Windows, 100
Add connection dialog box, 447
Add Controls program
creating new Label and Button
controls, 363, 365–66
folder location, 366
running, 366–67
Add method (List Box), 85, 87, 175
Add New Item dialog box, 248
Add ToolStrip Button button, 109
AddHandler statement, 417
adding
code snippets, 208
nonstandard dialog boxes, 117
addition operator (+), 143, 147
address, coordinate system, 376
ADO Faculty Form program,
456–58
ADO.NET, 442
ADO.NET Entity Framework, 442
Advanced Math program,
147–52
AIIowFullOpen property, 114
All Windows Forms tab, 67
AllowUserToResizeColumns
property, 478
Alphabetical button (Properties
window), 15
Always Show Solution
check box, 7, 31
Anchor and Dock program
folder location, 370
organizing objects at run
time, 368–69
running, 370–71
Anchor property, 368–69
anchoring objects, 368–71, 374
And (logical operator), 167–69
AndAlso operator, 169–71
animating objects
by using properties,
380–81
expanding and shrinking,
386–88
moving on forms, 380–81
on forms (Sun icon example),
382–85
animation, 380
AnyColor property, 114
applications
console, 373–74
datacentric, 439
deploying, 62–63, 65
arguments
defined, 131, 257
in Function procedures, 257
in Sub procedures, 262
more than one in a
function, 133
passing by value and by
reference, 268–71
Array Class Sorts project, 289–95
Array class, overview, 288–89
array literal, 278
arrays. See also dynamic arrays;
fixed-size arrays
assigning values to, 295
converting strings with separators
to, 332, 346
creating, 274, 295
declaring, 278–79
For . . . Next loops in, 281–82
overview, 273–74
processing elements in, 295
public, creating, 295
redimensioning, preserving data
in, 295
reordering contents of, 296
scope of, 274
setting aside memory for, 276
sorting, 289–95
syntax elements, table of, 274
three-dimensional, 288
working with elements, 277
As keyword, 125
As Type keyword, 257
Asc function, 330, 339, 347
ASCII codes
characters, sorting and, 329
converting, 330, 347
529
530
ASP.NET
determining, 330
dramatic shifts in causing
errors, 340
encrypting text by changing,
337–38
ASP.NET
overview, 491–93
software requirements for, 495
tags, 501
Web sites, creating, 522
assemblies, 12, 62
assigning
color, 113
value and simultaneously
declaring variables, 207
assignment or equal to operator (=),
125, 161, 182, 331
Atan(n) method, 152
Auto Format command, 515
Auto Hide command (Windows
menu), 17, 21–22, 34
Autos window
described, 216
overview, 217
using, 225
AutoSize property (Layout
category), 47–48, 198
B
background colors and images, 391
backslash (\), 147
base classes
creating, 399, 412
inheriting, 408–11
inheriting in new classes, 413
Basic Math program
program statements, 145–47
working with basic operators,
144–45
[ ] (brackets), 257
BindingNavigator control, 485
BindingSource property, 468
Birthday program
building, 73–76
folder location, 76
running, 76–78
bitmaps, 112
bits, 135
Boolean data type, 136
Boolean expressions, 163
Boolean properties, 51
BorderStyle property (Appearance
category), 47
bound controls, 454
bound objects, 466
brackets ([ ]), 257
break mode. See debugging mode
breakpoints
defined, 212
removing, 224–25
setting, 213, 225
browsers
opening Web, 23–24
setting default, 93
Brush object, 377
Build command, 61
building Web sites, 505–08
Button control (Toolbox)
creating, 365–66
creating buttons with, 70
using with Web pages, 502
buttons
adding, 40–42
creating, 71, 95
ellipsis, 15
overview, 71
radio, 81–83
smart tag, 50
toolbar, 108–10
View Designer, 54
ByRef keyword
in Sub procedures, 262, 266
passing arguments with, 268–70
when to use, 270
Byte data type, 136
bytes, 135
ByVal keyword
default setting, 262
passing arguments with, 268–70
when to use, 270
C
calculations
performing with functions,
258–61
visual feedback during, 296
calling
forms, DialogEvent property in,
358–59
Function procedures, 258, 271
printing event handlers, 437
Sub procedures, 262–63, 271
Car Loan Calculator project
adding controls to, 501–02
adding text in Web Page
Designer, 499–501
customizing, 509–11
testing, 507–08
Web site for, 505–08
Windows Forms Designer vs, 498
carriage return
as separators in lines of text, 332
characters, 184
formatting text strings with, 295
Case Else clause, 172
case sensitivity in code, 130, 193
Catch code blocks. See Try . . . Catch
code blocks
Categorized button (Properties
window), 15
Categorized button (Property
window), 45
CDbl function, 504–05
cells, changing colors of, 480–81
CellStyle Builder dialog box, 480–81
Celsius Conversion program
folder location, 195
using Do loops, 193–96
changing
compiler settings in IDE, 29–30
default page in Web
browser, 23
property settings, 14–16
Char data type, 136
characters
ASCII set, 329–30
carriage return, 184
converting to ASCII codes, 347
IBM extended set, 330
maximum number of,
in text lines, 185
password, 169
Unicode, 330
check boxes, creating, 78–80, 95
check marks, adding, 100
CheckBox control (Toolbox), 78–80
CheckBox program
creating, 78–80
folder location, 80
running, 81
CheckedChanged event
procedure, 83
CheckedListBox control, 85
CheckState property, 80
Choose Data Source dialog box, 446
Chr function, 330, 339, 347
class libraries, 90, 157
class variables, declaring, 403–04
classes
adding new to projects, 401
base. See base classes
creating, 402–08
declaring object variables
to use, 413
defined, 90
FileStream, opening text files
with, 437
inheriting, 413
methods, creating in, 405–06, 412
overview, 401
properties, creating in,
404–05, 412
Click procedure, 56–58
ClickOnce technology, 62, 65
client controls. See HTML
Clock menu program
adding access keys to, 101–02
changing order of items, 102
creating, 98–99
editing menu event procedures,
103–05
clock properties, 106
closing
programs, 13
programs without saving, 251–52
tool windows, 17
Visual Studio, 33
code
case sensitivity in, 193
character length of lines, 75
comments in, 86
declaring variables at top
of form, 139
executing one line of, 225
for displaying Print dialog box
and print files, 427–28
HTML in Web pages, 522
opening hidden forms with, 373
program style, 54
protected, 229
using fundamental data
types in, 137–41
viewing, 11
writing, 52–56, 65
Code Editor
accessing Help files for, 28
character length of lines
of code, 75
displaying, 54
entering program statements,
52–56
examining expressions,
properties, variables in, 225
executing one line, of code in, 225
identifying mistakes in, 54–55
opening, 52, 65
code snippets
adding, 208
inserting, 203–08
reorganizing, 207–08
Code Snippets Manager command,
207–08
Code Snippets Manager
dialog box, 207
code-behind files, 468
collections. See also Controls
collection
creating, 304–06, 312
overview, 297
processing objects in, 311
controls
referencing objects in, 298
special treatment for
objects in, 311
tracking Internet addresses with,
305–06
color
assigning, 113
changing, 116
changing cell, 480–81
filling shapes with, 377
in Visual Basic code, identifying
elements with, 54
setting background, 391
setting foreground, 49
Color dialog box
customizing color settings, 114
opening, 116
writing event procedures for
button, 113–14
ColorDialog control
adding, 111
properties of, 114
purpose, 110
ColumnHeadersVisible property,
480, 489
columns. See also fields
changing width, 478, 489
configuring individual, 479–80
hiding headers, 480, 489
removing, 476, 488
ComboBox control, 85
command prompt, 373
Command window
overview, 223
running commands in
IDE from, 226
running File.SaveAll, 224
switching from Immediate
window, 223, 226
commands
>cmd, 223
Auto Hide (Windows menu),
21–22
menu, guidelines, 100
running in IDE from Command
window, 226
commas, displaying with Format
function, 140, 137
comment character (‘), 295
comments, 57, 86, 95
comparing strings, 33, 329–31
comparison (or relational)
operators, 161, 173–77, 330–31
compiler settings
checking, 31–33
customizing, 29–30
in Visual Studio, 32–33
compiler settings, checking, 31–33
compiling
forms into .exe or .dll files, 394–95
programs, 34
component tray, displaying in the
IDE, 98
components
data access layer, 451
switching between, 8
conditional expressions
comparing, 167–69, 179
defined, 161
If . . . Then decision structure,
161–62
in Do Loops, 192
logical operators in, 167–69
order of If statements, 163
order of operator types, 167
writing, 179
configuring
data source for Web display,
514–15
date time picker object, 78
individual columns, 479–80
SQL statements, 514–15
Visual Studio for Visual Basic
Development, 34
connecting
to database tables, 488
to databases, 466, 468–71
connection string, 446
connections
binding to controls on forms, 443
choosing, 448
establishing, using Data Source
configuration Wizard, 444–52
console applications, 373–74
Constant Tester program, 142–43
constants
creating, 157
in program code, 142–43
vbCR, 206
continuing lines with _ character,
75, 187
controls
adding to forms, 354, 364–67, 374
adding to Web pages, 522
bound, 454–55
defined, 90
dialog box, 110–11
masked text box, binding to
dataset objects, 458–59
moving with For Each . . . Next
loops, 301–02
on user input, 164–67
organization of, in Toolbox, 41
organizing, on forms, 367–71
overview, 67
server vs. client, 493
531
532
Controls collection
server, adding to Web pages,
501–02
validator, 509, 522
Windows Forms, 67
writing event procedures for Web
pages, 504–05
Controls collection.
See also collections
moving controls with
For Each . . . Next loops, 301–02
moving objects, 311
Name property for special
treatment of objects, 303–04
object experimentation
procedure, 299
overview, 297
Controls collection program
moving controls with
For Each . . . Next loops, 301–02
using For Each . . . Next loops
to change Text properties,
299–301
convert to string (CStr)
function, 57
coordinate system, 376
Cos(n) method, 152
counter variables
global, 140, 190–91
in loops, 182
opening files with, 190–91
other uses for, 186
overview, 183
crashes, program. See run-time
errors
creating
folders, 72
modules, 248–51
standard-sized objects, 183
toolbars with ToolStrip control,
107–10
creating lines, shapes on, 390
CStr (convert to string) function, 57
customizing
color settings, with Properties
window, 114
compiler settings in IDE, 29–30
Help files, 34
inherited forms, 412
Web pages, 509–11
D
data access in Web forms
environment, 488
data grid view objects
adding second, 482–84, 489
changing column width, 489
creating, 471–74
creating color scheme for
rows, 489
creating to display database
tables, 488
hiding column headers in, 489
preventing editing or changing
of data, 489
previewing data bound to,
474–75, 488
removing columns from, 476, 488
setting properties, 479–82
sorting data in, 478–79
data navigator, 443
Data Source Configuration Wizard
choosing database model, 445
creating datasets in, 443
starting, 445
Data Sources window
creating database objects on
forms with, 454–58
overview, 452
data types
assigning, 125
fundamental, 135–41
inference of, by Visual Basic,
126–27
signed, 135
specifying in function
procedures, 257
string, 135
unsigned, 135
user-defined (UDTs), 141
Data Types program, 137–41
database objects
creating by using Data Sources
window, 454–58
defined, 450
databases
choosing format, 446
copying local, 449
displaying information on Web
pages, 512–13
establishing connection to, 466,
468–71
Faculty.mdb sample, 444
filtering and sorting information
stored in datasets, 466
formatting data on forms, 466
overview, 441
relational, 443
updating, 485–87, 489
DataBindings property,
overview, 459
datacentric applications, 439
DataGridView control
overview, 467
scrolling, resizing, and sorting
with, 478–79
DataGridView tasks list, 476
DataGridView Tasks list, 474
Dataset Designer, 451–52
datasets
binding controls to, 458–59
creating, 466
defined, 443, 450
displaying information on forms,
453–55
in Data Source Configuration
Wizard, 445, 452
information, displaying during
debugging sessions, 226
typed vs untyped, 451
visualizers, 220
DataTips, 215–16
Date data type, 136
date, setting system,
in Windows, 105
DateString property, 104–05, 107
DateTimePicker control, 73–78
DayOfYear property, 75
debug builds, executable file type in
Visual Studio, 60
Debug Test program
debugging, 212–14
folder location, 218
removing breakpoints, 224–25
Debug toolbar, displaying, 225
debugging mode. See also testing
disabling, in Web config, 506
opening text visualizers in,
220–21
starting, 214
stopping, 226
using, 212–17
Debugging Not Enabled dialog box,
505–06
debugging sessions
displaying HTML, XML, dataset
information during, 226
stopping, 226
Decimal data type, 136, 182
decision structures. See also If . . . Then
decision structures; Select Case
decision structures
decision structures, defined, 161
declaration statements, array
information included in, table,
282, 274
declared variables, hiding in
classes, 412
declaring collections as variables,
304–05
declaring variables
at top of form’s code, 139
by inference, 126–27
implicitly, 126–27
in Dim statement, 125–26
in projects with more than one
form, 140
object, to use classes, 413
public, in modules, 253–55
required compiler settings for, 32
while assigning values, 190, 207
Decrypt string variable, 344, 347
Default.aspx, 497
defensive programming
techniques, 243
delayed saving feature, 31, 40
deleting
breakpoints, 226
form files, 354
menu items, 102
objects, 43, 65
toolbar buttons, 110
deploying
applications, 62–63, 65
Web sites, 508
descriptive label properties,
setting, 48–49
Design mode
moving objects in, 42
Source mode, switching
between, 522
Design view, adding text in,
499–500
Designer. See also Menu Designer;
View Designer; Web Page
Designer
changing startup forms using,
371–73
Dataset, 451–52
displaying, 10–11
location in IDE, 8
scroll bars in, 40
Source tab, 500
switching to, 10
view button, 54
Window Forms. See Windows
Forms Designer
Desktop Bounds program
folder location, 363
setting DesktopBounds property,
362–64
DesktopBounds property, 359,
362–64
detecting mouse events, 177–78
development environment. See IDE
dialog box controls, 110–11, 120
dialog boxes
accessing Help files for, 28
Add New Item, 248
adding Print Preview and Page
Setup, 430–33
Code Snippets Manager, 207
error handlers
Color, 113–14
defined, 352
displaying, 120
displaying after creation, 112
displaying output, 157
displaying printing in
programs, 437
Edit Columns, 476
getting input by using, 156
inheriting, 394–97
input function of, 78
Input Mask, 164–65, 458
message, 133
New Project, 38–39
nonstandard, 117
Open. See Open dialog box
Open Project, 5–6
opening, 112
opening forms in. See ShowDialog
method
Page Setup, 430–33
Project Location, 72
Select Resource, 49
DialogResult property, 358–59
Digital Clock program
creating, 197–99
folder location, 199
running, 199
Dim keyword, 275
Dim statement, 124–26, 156, 208
dimensioning, 286–87
Disc Drive Error project
folder location, 230
loading, 230–32
disc drive errors,
writing handlers, 233
Disc Drive Handler program
folder location, 240
tracking run-time errors with
variables, 240–42
Discard button, closing without
saving, 252
disconnected data sources, 450
disks, creating new text files on, 321
division by zero, 145, 171
division operator (/), 143, 147
division, integer, 147
Do loops
avoiding endless, 193–96, 207
converting temperatures by using
(Celsius Conversion program
example), 193–96
described, 192
syntax, 192–93
Until keyword in, 196, 208
Dock property, 8, 368–69, 374
docking
objects, 368–71, 374
tool windows, 17, 19–21, 34
windows, 8
docking guides, 17–18
documents
multipage, printing, 437
tabbed. See tabbed documents
Double data type, 136
double-clicking
names of properties, 51
to create standard-sized
objects, 183
Draw Shapes program
creating lines, rectangles, and
ellipse shapes, 378–80
folder location, 379
DrawImage method, 419
DrawLine method, example, 377
drop-down list boxes, 85, 95
Dynamic Array program
folder location, 286
testing, 286–87
using, to hold temperatures,
284–86
dynamic arrays. See also arrays
creating, 283–84, 295
defined, 275
recording temperatures in,
284–87
E
Edit Columns dialog box, 476,
479–80
editing
event procedures, 112–13
menu event procedures, 102–05
ellipsis ( . . . ), in menu commands, 100
ellipsis buttons, 15
Else If keyword, 162–63
Else keyword, 162–63
Encrypt Text program
examining the code of, 338
folder location, 337
encryption, protecting text with,
336–40, 344, 347
End button, writing code for, 52–54
End If keyword, 162–63
End keyword, 53
End Select keywords, 172
EndofStream property, 317, 345
EndsWith method, 332
environment settings,
changing, 29–30
equal to or assignment operator (=),
71, 161, 331
error handlers. See also errors
defensive programming
techniques vs, 243
533
534
errors
for printing, 422
nested Try . . . Catch code blocks
in, 242
overview, 228
specifying retry periods, 240–42
structured, 243
structured, defined, 211
structured, function of, 227
testing (Disc Drive Error
project), 234
when to use, 228
writing disc drive, 233
errors. See also error handlers
creating, in programs, 245
disc drive, 229
generating for testing purposes,
240–42
indicators for (jagged)***, 211
logic, 210
path, 229
run-time, 149–52, 210, 244
syntax, 210
testing for specific in event
handlers, 245
types of problems addressed by
handlers, table, 228–29
event handlers
calling printing, 437
creating printing, 437
testing for specific
conditions in, 245
writing, 177–78
event procedures
constants in, 142–43
defined, 53, 91
displaying additional forms by
using, 356–57
editing, 112–13
menu, editing, 102–05
writing color button, 113–14
writing, for objects on Web
pages, 522
writing, for Web page controls,
504–05, 509–11
event-driven programming, 159–60
events
in Visual Basic, 160
mouse, detecting, 177–78
Exception objects
combining Catch statements
with, 239
overview, 236
types of, table, 236–37
what to use, 237
exceptions. See run-time errors
executable file types (.exe)
and Windows applications, 61
creating, 60–61, 65
overview, 60
executing
one line of code, 225
statements more than
once, 181
statements specific number of
times, 207
statements until conditions
met, 207
Exit For statement, 191, 207
Exit Try statement, 243–44
Exp(n) method, 152
expanding objects at run time,
386–88
Explorer Form template, 353
exponential operator (^), 143,
147, 149
expressions
adding to Watch window, 226
Boolean, 163
conditional, 161–63, 192
examining in Code Editor, 225
F
F1 Help key, 26–27
F8 key, alternative to Step Into
button, 219
Faculty.mdb sample database
folder location, 447
overview, 444
feedback, visual. See progress bar
fields. See also columns
backing, 403
defined, 442
displaying multiple database,
454–56
File menu, Save All command, 56
File.SaveAll command, 224
files
code-behind, 468
defining valid, 112
deleting form, 354
encrypting, 336
forms, saving, 65
opening using For . . . Next loops,
186–88
renaming form, 354
sequential, 317
switching between, 22–23, 34
trashing, 336
FileStream class, opening text files
with, 437
Fill Array button, 291–92
filling shapes with color, 377
Filter list, adding items to, 113
Filter property, 112
filtering
data, by writing SQL
statements, 466
database information stored in
datasets, 466
input, 165–66
Finally clause
displaying message boxes
with, 235
with Try . . . Catch code blocks,
234–35
Fixed Array program
creating, 279–82
folder location, 282
running, 283
testing, 282–83
fixed-size arrays. See also arrays
declaring, syntax items, 275
recording temperatures in,
279–83
floating windows, 19
focus, in text boxes, 144
FolderBrowserDialog control, 110
folders, creating, 72–73
Font property, 15, 47–48
FontDialog control, 110
For Each . . . Next loops
changing Text properties with
(Controls Collection program
example), 299–301
Name property in, 302–04
referencing objects in collections,
298–99
For keyword, 182
For Loop Icon program
folder location, 190
loading, 186–89
running, 188–89
For Loop program
displaying text by using
For . . . Next loop, 187, 183–85
folder location, 184
testing, 184–85
For Loops, complex, 185–86
For . . . Next loops
complex, 185–86
described, 182
displaying text by using, 183–85
exiting, 207
in arrays, 281–82
opening files by using, 186–88,
190–91
syntax, 182
writing, 181–82
ForeColor property (Properties
window), 16, 49, 113, 190–91
Form Inheritance program,
394–99
form variables, public vs., 255
Form_Load procedure, 63, 87
Format function, to display
commas, 137
formatting
database data on forms, 466
predefined patterns for, 164.
See also masks
program statements, 53
text, 15
Formatting toolbars, 499–500
forms
accessing Help files for, 28
adding navigation controls to, 466
adding to programs, 351–56, 373
anchoring objects on, 368–71, 374
changing transparency of, 388–90
controls, adding at run time,
364–67, 374
creating bound objects capable of
displaying dataset data on, 466
creating with code, setting
properties, 374
displaying additional, using event
procedures, 356–57
docking objects on, 368–71
files, saving, 65
formatting database information
on, 466
hidden, opening, 373
inherited, customizing,
397–99, 412
minimizing, maximizing, and
restoring, 364, 374
opening, 10, 357
positioning on Windows desktop,
359–64
public variables vs. variables
in, 255
startup, 371–74
transparency, changing, 391
uses for, 352
variables in projects with
multiple, 140
formulas
creating, 157
defined, 143
parentheses in, 156–57
frames, creating, 81
Framework. See .NET Framework
Framework Math program, 153–55
FromFile method, 83, 87, 187, 237
front ends, database, 439
FullOpen property, 114
Function procedures
calling, 258, 271
defined, 255
overview, 256
syntax items in, 257–58
If. . .Then decision structures
function statements, 257
functions
defined, 133
InputBox, 131–32
LBound, UBound, 280
MsgBox, 133
performing calculations with
(win rate example), 258–61
public, creating, 270
syntax items, using, 257–58
with more than one
argument, 133
G
GDI+ graphics services, changing
form transparency, 376, 388
general-purpose procedures, 256
global counter variables, 140,
190–91
graphics
printing, 418, 437
resizing, 49
Graphics Interchange Format (.gif).
See .gif files
Graphics.DrawImage
method, 418, 437
Graphics.DrawString method,
420–23, 437
Graphics.MeasureString
method, 424
greater than operator (>), 161, 331
greater than or equal to operator
(>=), 161, 331
GridColor property, 386
grids
aligning objects to, 42
cell color, changing, 480–81
gridline color, changing, 481, 489
hidden by default, 42
reversing direction of
sort, 489
snapline, 42
sorting records in, 489
GridView control, 512–15
group boxes, property settings,
table of, 83
GroupBox control, 81–82
guide diamonds, 17
H
Height property, 386
Hello World program
creating, 68
folder location, 72
overview, 67
running, 72–73
Help files
accessing, 28, 34
customizing, 34
F1 key, 26–27
managing settings, 25–26
MSDN, 27–28
navigating, 28
topic locations in Visual
Studio 2010, 28
Help Library Manager, 25–26
hidden forms, opening by using
program code, 373
hiding
declared variables in classes, 412
forms, 373
shortcut keys, 118
tool windows, 21, 34
Hour (date) method,
description, 107
HTML
controls described, 493
controls overview, 494
creating pages, 522
displaying during debugging
sessions, 215
tags, 501
viewing for Web pages, 500, 522
visualizers, 220
Hungarian Naming
Convention, 130
HyperLink control, 516, 522
hyperlinks, adding, 516–17
I
IBM extended character set, 330
icons
file type, 112
pin, 215
shortcut, 61
IDE
accessing Help files for, 28
changing compiler settings for,
29–30, 34
component tray, 98
Data Source Configuration
Wizard, 445
Navigator, 22–23
overview, 4
running commands from
Command Window in, 226
running Visual Basic from, 58
toolbars available in, 8
If . . . Then decision structures
conditional expressions using,
161–62
in Checkbox controls, 80
logic errors in, 211
535
536
Image property
short-circuiting, 169–71, 179
syntax, 179
Image property, 49
images, setting background, 391
immed command, using to switch to
Immediate window, 223
Immediate window
modifying variables with, 222–23
opening, 226
switching to Command window,
223, 226
Import and Export Settings
command (Tools menu),
22, 29–30
Imports statement
math methods, 152
referencing class libraries, 154–55,
157, 243
index position, of objects, 298
inheritance, 90, 393–94
Inheritance Picker dialog box,
394, 396
inherited forms, customizing,
397–99, 412
inheriting
base classes in new classes, 413
dialog boxes, 394–97
forms’ interfaces and
functionalities, 412
Inherits keyword, 413
Inherits statement, 400, 408–11
Input Box program, 131–32
Input Controls program, 78–79
Input Mask dialog box,
164–65, 458
input, controlling user, 164–67
InputBox function, 131–32
Insert Snippet command,
203–08, 316
Insert Standard Items button, 108
inserting code snippets, 203–08
insertion point, in text boxes, 144
Int function, 57
Integer data type, 136–37, 182
integer division (\), 147–48
Intellisense, 53, 71
Internet addresses, tracking by
using new collections, 305–06
Internet Explorer
disabling security warnings, 507
title bar, 519–22
intranet security settings, 507
Is keyword, 173
J
Joint Photographic Experts Group
format. See .jpeg files
K
keys, primary, 470
keywords. See also specific
keywords
defined, 89
in variable names, 130
Intellisense and, 53
L
Label control
adding objects, 102–03
creating, 365–66
using with Web pages, 502
labels
adding, 43–44, 102–03
changing property settings, 16
defined, 43
descriptive properties, setting,
48–49
number properties, setting,
47–48
Language-Integrated Query (LINQ),
442, 462
LBound function, 280
Left property, 380
less than operator (<), 161, 331
less than or equal to operator (<_),
161, 331
letters, converting to numbers, 340
lightweight views, 27
line continuation character (_),
75, 187
lines
creating on forms, 390
entering, 104
processing in text boxes, 332
reading text files by, 345
linking, to Web pages, 522
LinkLabel control (Toolbox), 91
links, changing color of, 92–93
LinkVisited property, 93
LINQ (Language-Integrated Query),
442, 462
List Box control, 174
List Box program
folder location, 88
running, 88
list boxes
adding items to, 85, 95
creating, 85–87, 95
defined, 84–85
drop-down, creating, 85
in Visual Studio, 71
Insert Snippet, 204
ListBox control, 84
Local Help files, 25
Location property
described, 380
overview, 381–82
Location text box, 40
logic errors
defined, 210
finding and correcting, 213
identifying, 211
logical operators, 167–69
Long data type, 136–37, 182
loops
avoiding endless, 193
creating, 181–82
creating complex, 185–86
setting run time periods for, 208
lower and upper bounds, specifying
in public arrays, 295
Lucky Seven game program
adding additional forms,
352–56
adding Help forms, 352–56
building executable files, 61
closing, 64
closing without saving, 252
creating, 38–44
folder location, 59
properties of, in table, 51
reloading, 63–64
running, 58–59, 357–58
user interface contents, 38
M
macros, compatibility between
Word versions, 309–10, 312
manipulation, string, 326–27
Mask property, 164
MaskedTextBox control, 164,
458–60
masks
defined, 164
formatting database information
with, 458–61
mathematical (or arithmetic)
operators, 146, 143
mathematical (or arithmetic)
operators, 150, 147
maximizing forms at run time, 374
MaximumSize property, 364
MaxLength property, 185
Me keyword, 355
Me object, 373
MeasureString method, 424
memory management, 125, 276
menu bar, 8
Menu Designer
adding access keys, 98–100
changing order of commands, 102
menu items. See also menus
adding access keys, 100
adding access keys to, 119
adding to menu commands,
98–99
changing order of, 102, 119
creating, 119
deleting, 102
guidelines for, 100
naming, 104
shortcut keys, assigning, 102,
117–19
Menu program
folder location, 105, 114
menus and dialog boxes in, 114
running, 105–06, 115–17
menus. See also menu items
event procedures, editing, 102–05
running, 88
MenuStrip control (Toolbox)
displaying objects, 98
overview, 97
shortcut keys, assigning, 117–18
message boxes. See also dialog
boxes
creating, 74–75
displaying, 235
displaying information on
forms, 133
MessageBox class, 134
metafiles, Windows, 112
methods
calling, 157
creating in classes, 405–06, 412
defined, 75, 91
Graphics.DrawString, 420–23
math, 152
Print, 418, 437
ShowDialog, 112
Microsoft Access. See Access
Microsoft Intellisense, 53, 71
Microsoft OLE DB, 448
Microsoft.Jet.OLEDB error
message, 444
minimizing forms at run time, 374
MinimumSize property, 364
Minute (date) method,
description, 107
mistakes, identifying by jagged
lines, 54–55
mnuOpenItem Click event
procedure, 343–44
mnuSaveAsItem_Click event
procedure, 338
Mod (remainder division operator),
143, 148
modal forms, 357
modeless forms, 352
objects
modules
adding, 252–55
adding existing, 270
creating, 248–51, 270
overview, 248
removing, 270
removing from projects, 251
renaming, 250, 270
saving, 250–51
Month (date) method,
description, 107
mouse events, detecting, 177–78
moving
objects, 42, 64
objects in Control
collections, 311
objects on forms, 380–82
tool windows, 17–19, 34
toolbar buttons, 110
Moving Icon program
animating sun icon, 382–85
folder location, 385
running, 385–86
MSDN Online Help, 27–28
MSDN, switching views in, 27
MsgBox function
creating message boxes, 74–75
displaying contents of variables,
133–35
Xor (logical operator)
encryption, 340
Multiline property, 183–86
multiline text boxes, size limit, 185
multiplication operator (*),
143, 147
multi-targeting feature, 39
Music Trivia program
closing, 13
opening, 5–7
running, 11–13
My namespace
accessing forms using, 356
overview, 314–16
reading text files with, 345
writing text files, 346
My.Computer.FileSystem object
ReadAllText method, 315–21
WriteAllText method, 321–23
N
Name property, 174–75, 302–04
namespaces, 90
naming
classes, 403
conventions for variables, 130
data, 124
menu items, 104
navigation controls
adding second, 484
adding to forms, 466
navigation toolbar, 456–57
New Connection button, 446
New Project command (File Menu)
and Windows Installer, 63
console applications, 373
New Project dialog box, 38–39, 68
New Project link (Start Page), 38
New Web Site command, 496
Next keyword, 182, 184
non-modal forms, 352, 357
nonstandard dialog boxes, 117
Not (logical operator), 167
not equal to operator (<>), 161, 331
Now property, description, 107
number computation, random, 57
number sequences, creating in
loops, 185–89
numbers, converting letters to, 340
numeric values, encrypting, 340
O
Object data type, 136
object variables
declaring to use classes, 412
setting properties for, 413
object-oriented programming
(OOP), 393
objects. See also specific objects
adding, 40–42
aligning to hidden, 42
anchoring, 368–71, 374
animating, 391
changing property settings,
14–16, 47
choosing database, 449–50,
469–71
control, 365–66
creating based on new classes,
407–08
creating standard-sized, by
double-clicking, 183
defined, 13, 90
deleting, 43, 65
docking, 368–71, 374
events supported by
Visual Basic, 160
expanding, shrinking at
run time, 391
in collections, 297–98
index position of, 298
moving, 64, 311, 391
multiline text box,
size limits of, 185
processing, in collections, 311
537
538
Office applications
referencing in collections, 298–99
renaming, 179
renaming on Web pages, 522
resizing, 42, 65
selecting, for reuse. See
Inheritance Picker dialog box
special treatment for, in
collections, 311
startup, 371–74
switching between, 47
text box, 313
timer, 200, 203, 382–85
writing event procedures for on
Web pages, 522
Office applications, using Visual
Basic for Applications
collections in, 309
Online Help files, 25, 27–28
Opacity property, 388–91
Open button, editing event
procedures, 112–13
Open dialog box
displaying, 113, 314–15, 345
displaying and selecting
text file, 426
filtering file types, 112–13
Open Encrypted File command, 338
Open Project dialog box, 5–6
Open Web Site command, 498
OpenFileDialog control
adding, 111, 345
managing print requests with,
424–28
opening text files using, 314
purpose, 110
opening
Code Editor, 52, 65
dialog boxes, 112–13
files by using For . . . Next loops,
186–88, 190–91
forms, 10
Immediate window, 226
projects, 4–6, 34
projects, troubleshooting, 7
Watch windows, 218–19
Web browser, in Visual Studio,
23–24
operators
advanced, 147–50
arithmetic (or mathematical),
143, 147
comparison (or relational), 161
comparison (or relational)
operators, 330–31
logical, 167–69
order of precedence, 155–57, 167
shortcut, 147
Option Compare setting, 33
Option Explicit Off statement,
126–27
Option Explicit setting, 32
Option Infer setting, 33, 126–27
Option Strict setting, 32
Options command
(Tools menu), 40
Or (logical operator), 167
order of precedence, 155–57, 167
OrElse operator, 169–71
origin, coordinate system, 376
Other Windows menu, 8
Other Windows submenu, 23
P
Page Setup dialog box
adding with PageSetupDialog
control, 430–33
display page setup
dialog box, 432
testing, 434–37
PageSetupDialog control
adding, 430–33
purpose, 111
Paint event procedure, creating
shapes with, 378–80
parentheses
in Sub procedures, 262
use of, in formulas, 156–57
PasswordChar property, 169, 200
passwords, setting time limit for,
200–03
path errors, 229
path names, absolute
and relative, 89
Pen object, 377
Person Class program
building, 401–02
creating classes, 402–08
folder location, 407, 410
inheriting base classes, 408–10
testing, 410–11
picture boxes
adding to programs, 111
defined, 44
file types, 112–13
property settings, table of, 83
setting properties, 49–51
PictureBox control, 44, 83
pictures, adding, 44.
See also graphics
pin icons, 215
pipe symbol (|), 113
pixels, coordinate system, 376
Pmt function, overview, 504
Portable Network Graphics (.png).
See .png files
positioning startup forms on
Windows desktop, 374
practice files, installing, 4
Preserve keyword, 287
Preview Data dialog box, 474–75
previewing data bound to data grid
view objects, 474–75
primary keys, 470
Print Dialogs program
folder location, 433
testing Page Setup and Print
Preview features, 434–36
Print File program
adding Print Preview and Page
Setup, 431–33
building, 424–28
folder location, 428
running, 428–30
Print Graphics program
folder location, 419
running, 419–20
Print method, 418, 437
Print Preview dialog box, adding
with PrintPreviewDialog
control, 430–33
Print Preview, testing, 434–37
Print Text program
folder location, 423
running, 423
PrintDialog control
managing print requests with,
424–28
purpose, 111
PrintDocument class, 415–20
PrintDocument control, 416–19
PrintDocument object, 437
printing
adding code to display Print
dialog box, 427–28
creating event handler, 437
displaying dialog boxes, 437
event handlers, calling, 437
graphics from printing event
handlers, 437
managing requests with controls,
424–28, 430–33
multipage documents, 437
multipage text files, 424
preparing projects for, 437
set default settings, 427
text from printing event
handlers, 437
text from text box objects, 420
text using Graphics.DrawString
method, 420–23
using error handlers, 422
printing area, defining, 427–28
PrintPage, 424
PrintPreviewDialog control
adding, 430–33
purpose, 111
Private keyword, 403, 412
procedure statements, in Sub
procedures, 262
procedures. See also Sub procedures
click, 56–58
creating, 255–56
defined, 53
Function, calling, 258, 271
Function, defined, 255
general-purpose, 256
overview, 53
sharing, 247–48
Sub, defined, 255
Process class, 93
Process.Start method,
feature of, 93
processing elements in arrays, 295
program code
automatic additions by
Visual Basic, 55
comments in, 86
error messages, 55
executing one line of, 225
identifying elements by color, 55
opening hidden forms with, 373
writing, 65
program crashes, 227
program statements. See also code
Basic Math program, 145–47
defined, 53, 89, 123
entering in Code Editor, 52–56
executing, 208
overview, 53
procedures and, 53
sequencing numbers
by using, 207
setting properties using, 57
syntax in, 53
program style, 54
programming
defensive techniques, 243
event-driven, 159–60
steps for new projects, 38
programming languages available
in Visual Studio, 4, 38
programs. See also specific
programs
adding controls to, 110–11
adding new forms to, 373
adding toolbars to, 109, 119
closing, 13
closing without saving, 251–52
compiling, 34
Data Types, 137–41
errors in, creating, 245
relational (or comparison) operators
reloading, 63–64
running, 11–13, 258–61
saving, 56, 65
skeleton, 127
stopping, 72
using standard dialog
boxes in, 120
Visual Basic, creating with no user
interface, 374
progress bar, 290–91, 296
project files, 7
Project Location dialog box, 72
project settings, checking, 31–33
projects. See also specific projects
creating, 40–44, 68
opening, 4–6, 34
opening, troubleshooting, 7
programming steps for
new, 38
reloading, 65
saving, 72–73
with more than one form, 140
Projects folders, 6
prompting user for information,
131–32
properties. See also property
settings
adding to Watch window, 226
animating objects by using,
380–81
Boolean, 51
changing at run time, 71, 95
creating, 404–05
creating in classes, 412
defined, 90
descriptive label, setting, 48–49
for moving objects, 380
for picture boxes, setting, 49–51
names of, double-clicking, 51
number label, setting, 47–48
overview, 13
setting, 34, 45–47
setting at design time, 13
setting for data grid view objects,
479–82
setting for object variables, 413
setting, for Web pages, 503
tables of, reading, 51
viewing, 13
Properties window
categories in, 14–15
customizing color settings
with, 114
displaying, 45
location in IDE, 8
Object list, 13
organization of, 14, 46
overview, 13–16
property settings
changing, 14–16, 45
defined, 13
protecting text with basic
encryption, 336–40
providers, 448
public arrays, 295. See also arrays
public functions, creating, 270
Public keyword, 142, 275
public Sub procedures, 271
public variables
creating, 270
declaring in modules, 140,
251, 253–55
form variables vs., 255
Publish command, 62, 65
Q
Query Builder, creating SQL
statements with, 461–66
Quick Note program
examining code in, 326
folder location, 323
running, 323–25
quotation marks, with text
strings, 128
R
Radio Button program
creating, 82–83
folder location, 84
running, 84
radio buttons
creating, 82–83
defined, 81
RadioButton control, 81–82
random number computation, 57
Randomize function, 59
Randomize statement, 63–64
ReadAllText method, 315–21
ReadLine method, 317, 345
ReadOnly property, 486–87
Rebuild command, 61, 65
receiving input in specified
format, 179
records, in databases, 442
ReDim Preserve statement,
287–88
ReDim statement, dimensioning
with variables, 284
redimensioning
arrays, 295
for three-dimensional
arrays, 288
relational (or comparison)
operators, 161, 330–31
539
540
relational databases
relational databases, 443
relative path names, 89
release builds, executable file type
in Visual Studio, 60–61
reloading programs, 63–64
reloading projects, 63–65
remainder division operator (Mod),
143, 148
removing
breakpoints, 224–26
columns, 476, 488
renaming
form files, 354
modules, 250, 270
objects, 179
objects on Web pages, 522
Replace method, 332
resizing
button objects, 42
forms, 40
graphics, 49
objects, 42, 65
tool windows, 19, 34
restoring
forms at run time, 374
hidden windows, 17
Return statements, 257
reversing, order of an
array, 295
RichTextBox control (Toolbox)
managing print requests with,
424–28
spacing and formatting
options of, 185
RichTextBox object, loading text
files into, 437
Rnd function, 57
rows
changing color of, 481, 489
in data tables, 442
running
programs, 11–13
Visual Basic from IDE, 58
WebLink program, 94–95
Windows applications with
Windows Explorer, 61
run-time errors
correction of, 151
defensive programming
techniques, 243
defined, 150, 210
detecting, processing, 244
preventing, 171
program crashes, 227
solving, 211
testing for multiple, 237–39
throwing, 239
variables to track, 240–42
S
Save All button (Standard toolbar),
65, 72
Save All command (File menu),
56, 65
Save As dialog box,
displaying, 345
Save Data button, function
of, 485
Save New Projects When Created
check box, 31
SaveFileDialog control, 110
saving
delayed, 31, 40
form files, 65
programming environment
settings, 22
programs, 56, 65
projects, 31
user input, 130–32
SByte data type, 136
schema file, XML, 443, 451
scope
of arrays, 274
of variables, 128, 189–90
scroll bars
in list boxes, 84
in text boxes, 313
in the Designer, 40
ScrollBars property, 183
scrolling, faster, 407
search box, in Help files, 28
Search Criteria Builder dialog box,
462–63
Second (date) method,
description, 107
Select Case decision structures
comparison (or relational)
operators with, 173–77
defined, 87
event procedures, 140
syntax, 171–72, 179
Select Case keywords, 172
Select Case program
adding mouse event handler,
177–78
folder location, 176
processing inputs from list box,
173–77
running, 176–77
Select Resource dialog box, 49
SelectedIndex property,
85–86, 176
SelectedIndexChanged event
procedure, 86. See also event
procedures
sequential files, 317
server controls
adding to Web pages, 501–02
described, 493
overview, 493
servers, 495
SetBounds method, 380
setting
breakpoints, 225
properties, 34
time limits, 200–03
settings
default print settings, 427
saving programming
environment, 22
shapes
creating lines, rectangles, and
ellipses, 378–80
creating on forms, 390
filling with color, 377
sharing, variables and procedures,
247–48
ShellSort Sub procedures, 332,
335–36
Short data type, 136–37
shortcut icons, creating, 61
shortcut keys
assigning to menu items, 119
assigning to menus, 117–18
defined, 117
hiding, 118
testing, 118–19
ShortcutKeys property, 117, 119
Show method
switching between forms, 373
to open forms, 357
ShowDialog method
displaying Open dialog box, 113
opening dialog boxes, 112–13
switching between forms, 373
ShowHelp property, 114
shrinking objects at run time, 391
Sign(n) method, 152
Simonyi, Charles, 130
simultaneous declaring/ assigning
variables, 190
Sin(n) method, 152
Single data type, 136
Size structure, 364
SizeMode property (Behavior
category), 49
sizing
startup forms on desktop, 374
windows, 19
skeleton programs, 127
smart tag buttons, 50, 107–08
snapline grids, 42
snippets. See code snippets
SolidColorOnly property, 114
Solution Explorer
displaying, 10
location in IDE, 8
project files for web
building in, 498
renaming form files using, 354
Solution Name text box, 40
solutions
always show, 7, 31
overview, 7
Sort Array button, 292–93
Sort Text program
examining code in, 334–36
folder location, 332
running, 332–34
sorting
data in data grid view objects,
478–79
records in grids, 489
reversing direction of, 489
strings, 33
strings in text boxes, 331–36
text, 329–30
Source mode, Design mode,
switching between, 522
Source tab, 501
Spin button, writing code for, 54–56
Split method, 332, 346
SQL Server, 448
SQL statements
configuring, 514–15
creating with Query Builder,
462–66
overview, 461–62
Sqrt(n) method, 152
square roots, calculation of, 153–55
Standard toolbar
defined, 8
Start Debugging command, 58
Start Debugging command, 11, 58
Start method, 93–94
Start Page
New Project link, 38
opening projects from, 4
starting Visual Studio, 4–5, 34
StartPosition property, 360–62, 374
statement syntax, 53, 124
statements. See also specific types
executing, 208
function, 257
in If . . . Then decision structure,
161–62
sequencing numbers
by using, 207
Step Into button, 216
Step keyword, 207
Stop Debugging (Debug toolbar),
closing program with, 72
text
StreamReader class
adding text to additional form,
355–56
overview, 316–17
reading text files with, 345
StreamWriter class, 322, 346
String class
elements and Visual Basic
equivalents, 327–29
list of elements in, 346
processing strings in, 326–29
string concatenation operator (&),
75, 147, 149, 184
String data type, 136
string variables, 125
String.Concat method, 327
strings
comparing, 33, 329–31
connection, 446
manipulating and processing,
326–27
sorting, 33
structured error handlers,
211, 227, 243
Sub procedures. See also procedures
calling, 262–63, 271
defined, 255
managing input with, 264–68
overview, 262
parentheses in, 262
public, creating, 271
ShellSort, 332, 335–36
syntax items, using, 262
subroutines. See Sub procedures
Substring method, 332
subtraction operator (–), 143, 147
Sun icon animation. See Moving
Icon program
switching
between components, 8
between files, 22–23, 34
between forms, 373
between objects, 47
between tools, 22–23, 34
types of windows, 21
views in MSDN, 27
syntax errors
checking lines for, 104
identifying by jagged line, 72
in variable assignments, 140
overview, 210
solving, 210
unused variables, 128
syntax, statement, 53, 124
System Clock properties, 106
System.Drawing namespace, 376
System.Drawing.Graphics class
overview, 376–77
shapes and methods used in,
table, 377
System.Drawing.Printing
namespace, 416
System.IO namespace, 355
System.Math class, 152, 154
System.Windows.Forms.Form
class, 351
T
tab characters, formatting text
strings with, 295
tabbed documents
displaying code using, 11
displaying windows as, 17
switching to dockable or floating
windows, 21
tools as, 8
table adapters, 443
TableAdapterManager
component, 487
tables
binding second DataGridView
control to, 482–84
controlling multiple, 487
database, 488
defined, 442
dragging, binding, sizing,
472–73
Tan(n) method, 152
taskbar, Windows, 8
templates
Explorer Form, 353
in Add New Item dialog box, 248
Inherited Form, 395–96
inserting code. See snippets
testing. See also debugging mode
conditions in If . . . Then decision
structure, 162–63
connection, 447
error handler, 234
event handlers, specific
errors in, 245
for multiple run-time errors,
237–39
loop conditions, 192
text
aligning, 47
decrypting, 347
entering on Web pages, 522
formatting, 15
pasting from Windows
Clipboard, 324
printing from printing event
handlers, 437
printing from text box
objects, 420
541
542
Text Box Sub program
protecting with basic encryption,
336–40
sorting, 329–30
Text Box Sub program
creating, 264–67
folder location, 267
managing input with Sub
procedures, 264–68
running, 267–68
text boxes
creating, 70, 95
displaying text by using, 313
input function of, 78
Location, Solution Name, 40
multiline, size limits of, 185
overview, 70
processing lines in, 332
sorting strings in, 331–36
Text Browser program
examining code in, 320–21
folder location, 319
running, 317–19
text files
creating new on disk, 321
defined, 313
loading into RichTextBox
object, 437
multipage, printing, 424
opening and displaying, My
namespace, 315–16
opening and displaying,
StreamReader class, 316–17
opening with FileStream class, 437
reading, 313–14
writing, 321, 346
Text properties, changing
for descriptive labels, 48–49
for number labels, 48
with For Each . . . Next loops,
299–301
text strings
combining, 157
formatting with carriage returns,
tab characters, 295
TextAlign property (Appearance
category), 47
TextBox control
assigning values to variables,
146–47
using counter variables in
multiline text, 183–85
using with Web pages, 502
Throw statements, 239, 245
time, setting system,
in Windows, 104
Timed Password program
folder location, 202
setting password time limits, 200
settings for, table, 200–01
testing, 202–03
Timer control
described, 196
settings for, 198
using, 197–99
timer objects
creating animation by using,
382–85
uses for, 200, 203
TimeString property, 104, 107
title bars, on Web pages, 92, 522
To keyword, 173, 182, 207
toggles, 100
tool windows
auto hiding, 17
closing, 17
docking, 17, 19–21, 34
hiding, 21–22, 34
moving, 17–19, 34
resizing, 19, 34
restoring hidden, 17
toolbars
adding to programs, 119
creating, 107–10
creating with ToolStrip
control, 109
Debug, displaying, 225
Formatting, 499–500
moving and deleting
buttons on, 110
navigation, 456–57
viewing a list of, 8
Toolbox. See also specific controls
location in IDE, 8
organization of controls, 41
Web Page Designer, 498
tools
as tabbed documents, 8
switching between, 22–23, 34
viewing, 8
Visual Studio, 7–9
Toolstrip control, 103
ToolStrip control, 107–10
Top property, 380
ToString method, 75
TrackWins program
opening, 252
running, 261
win rate function, creating,
258–61
transparency, changing for
forms, 388–90
Transparent Form program
folder location, 389
setting Opacity property, 388–90
trashing files, 336
troubleshooting opening projects, 7
Try . . . Catch code blocks
error handlers, 236
exiting, 245
nested, in error handlers, 242
syntax, 229
trapping errors with (Disc Drive
Error program example),
233–34
using Finally clause with, 234
writing nested, 245
Type Here tag, 98–99
typed datasets, 451
U
UBound function, 280
UDTs (user-defined data type), 141
Ulnteger data type, 136
ULong data type, 136
unhandled exceptions, 232
Unicode, 330
Until keyword, in Do loops,
196, 208
UpdateAll method, 487
updating databases, 485–87, 489
upgrading from Visual Basic 2008,
5–6
upper and lower bounds, specifying
in public arrays, 302, 295
URL Collection program
creating collections, 305–06
folder location, 307
running, 307–09
user interfaces. See also forms
creating, 40–44, 64
elements. See properties
User Validation program
adding password protection,
168–69
controlling user input, 164–67
user-defined data types (UDTs), 141
UShort data type, 136
V
validator controls, 509
value, assigning
to arrays, 278–79, 295
while declaring variables, 190, 207
Variable Test program, 126–30
variables
adding to Watch window, 225
Autos window to view, 225
changing values of, 127–30, 156
counter, 182–85
declared, hiding in classes, 412
declaring, 156
declaring class, 403–04
declaring, in Dim statement,
125–26
Decrypt string, 344
defined, 89, 124
described, 247–48
displaying contents of, 133–35
examining in Code Editor, 225
implicit declaration of, 126–27
length of names, 130
modifying with the Immediate
window, 222–23
naming conventions, 130
public or global, 140
required compiler setting for
declaring, 32
sharing, 247–48
storage size of, 135
string, 125
tracking run-time errors with,
240–42
validating, 139
variants, 125
vbCr constant, 206
vbCrLF constant, 282
View Code button, 54, 65
View Designer, 54
View Menu, 8
viewing
code, 11
properties, 13
Web sites, 505–08
Visible property (Behavior
category), 49–51
Visual Basic. See also Visual Studio
accessing Help files for, 28
adding code automatically, 55
applications, deploying, 62
checking compiler settings, 32–33
comments in, 57
compiler, defined, 53
design mode, 42
determining version, 7
equivalents to String Class
elements, 327–29
error messages, 55
identifying elements by color, 55
Input Controls program, 78–79
line continuation character (_), 75
memory allocation for arrays, 276
program statements in, 53,
123–24
programs, creating with no user
interface, 374
random number computation
in, 57
running from IDE, 58
running programs from
Web server, 91
Web sites
Visual Basic 2008 vs Visual
Basic 2010, common control
changes, 67
Visual Basic for Applications,
309–10, 312
visual feedback during
calculations, 296
Visual Studio. See also Visual Basic
checking compiler settings in,
32–33
configuring for Visual Basic
development, 34
creating and running Web
sites in, 495
default settings, 29–30
deployment overview, 62–63
displaying list box of
properties, 71
executable file types,
creating in, 60
exiting, 33, 35
Help documentation in, 24–25
Help topic locations in, 28
icons, bitmaps, and animation
files in, 186
IDE. See IDE
programming languages available
in, 4, 38
programs, stopping in, 72
running programs in, 12
starting, 4–5
starting Visual Studio, 34
tools, 7–9
Web browser, opening, 23–24
Web sites, running
and testing, 522
Visual Studio 2008, Help
documentation in, 24–25
Visual Web Developer
creating Web sites, 491
deploying Web sites with, 508
displaying database tables, 512
download location, 496
visualizers
displaying information with, 226
types of, overview, 220
vTab constant, 282
W
Watch windows
adding variables, properties,
expressions to, 218–19, 225
displaying, 226
opening, 218
overview, 217
Web Browser command (Other
Windows submenu), 23
Web forms environment, data
access in, 488
Web Page Designer
described, 498–500
Design mode vs. Source mode,
switching between, 522
Design tab, 497
gridline color, changing, 481
page views in, 497
positioning controls in, 501
Source tab, 497
Split tab, 497
Web pages
adding text in Web Page
Designer, 498–500
changing names of
objects on, 522
components, 468, 501
controls, adding, 522
customizing, 509–11
displaying, 94
displaying database
records on, 522
displaying title on Internet
Explorer title bar, 92, 522
entering text on, 522
formatting text on, 522
Gridview control, adding,
512–15
hyperlinks, adding, 516–17
linking to other pages, 522
server controls, adding,
501–02
setting properties, 503
validating input fields, 509
validator controls, 522
viewing HTML code in, 522
viewing HTML for, 500
Windows Forms vs., 493
writing event procedures for
controls, 504–05
Web server, running Visual Basic
programs, 91
Web sites
adding pages for database
information, 512–13
adding pages to, 509
ASP.NET, creating, 522
building and viewing, 505–08
components, 468
creating, 496
creating with Visual Web
Developer, 491
deploying, 508
in Visual Studio, running and
testing, 522
locations for creating and running
in Visual Studio 2010, 495
543
544
Web.config file
setting title in Internet Explorer
title bar, 92, 519–21
testing (Car Loan Calculator
example), 517–19
Web.config file, 506
WebLink program
creating, 91–94
folder location, 94
running, 94–95
Weekday (date) function, 107
While keyword, 196
Width property, expanding,
shrinking picture box at run
time, 386
win rate function, creating,
258–61
windows. See also tool windows
docking, 8
floating, 19
minimizing, maximizing,
restoring, 364
switching between types of, 21
Windows applications and
executable file types, 61
Windows Clipboard, pasting text
from, 324
Windows Explorer, running
Windows applications with, 61
Windows Forms Application, 39
Windows Forms controls, 67
Windows Forms Designer vs Web
Page Designer, 498
Windows Forms vs Web pages, 493
Windows Installer, 63
Windows metafiles, 112
Windows taskbar, 8
Windows Version Snippet program,
203–06
Windows, running programs in, 61
WindowState property, 364
Word macros, compatibility
between versions, 309–10
Wrap keyword, 184
WriteAllText method, 321–23
writing
conditional expressions, 179
event handlers, 179
event handlers, disc drive, 233
event procedures (Color button
example), 113–14
program code, 65
X
XCOPY installation, 62
XML
displaying during debugging
sessions, 226
schema file, 443, 451
visualizers, 220
Xor (logical operator)
encrypting text by using the,
340–45
encrypting text with,
341–42
encrypting with, 347
meaning, 167
Xor Encryption program
examining the code of,
342–44
folder location, 341
running, 341–42
Y
Year (date) function, 107
Z
zero, division by, 145, 171
Zoom In program
folder location, 388
loading, 386–88
Michael Halvorson
Michael Halvorson is the author or co-author of more than
35 books, including Microsoft Visual Basic 2008 Step by Step,
Microsoft Office XP Inside Out, and Microsoft Visual Basic 6.0
Professional Step By Step. Halvorson has been the recipient of
­numerous non-fiction writing awards, including the Computer
Press Best How-to Book Award (Software category) and the
Society for Technical Communication Excellence Award (Writing
­category). Halvorson earned a bachelor’s degree in Computer
Science from Pacific Lutheran University in Tacoma, Washington,
and master’s and doctoral degrees in History from the University
of Washington in Seattle. He was employed at Microsoft
Corporation from 1985 to 1993, and he has been an advocate for Visual Basic ­programming
since the product’s ­original debut at Windows World in 1991. Halvorson is currently
an ­associate professor at Pacific Lutheran University.
Best Practices for Software Engineering
Software Estimation:
Demystifying the Black Art
Code Complete,
Second Edition
Steve McConnell
Steve McConnell
ISBN 9780735605350
ISBN 9780735619678
Amazon.com’s pick for “Best Computer Book of 2006”!
Generating accurate software estimates is fairly straightforward—once you understand the art of creating them.
Acclaimed author Steve McConnell demystifies the
process—illuminating the practical procedures, formulas,
and heuristics you can apply right away.
Widely considered one of the best practical guides to
programming—fully updated. Drawing from research,
academia, and everyday commercial practice, McConnell
synthesizes must-know principles and techniques into
clear, pragmatic guidance. Rethink your approach—and
deliver the highest quality code.
Simple Architectures for
Complex Enterprises
Agile Portfolio Management
Jochen Krebs
Roger Sessions
ISBN 9780735625679
Agile processes foster better collaboration, innovation,
and results. So why limit their use to software projects—
when you can transform your entire business? This book
illuminates the opportunities—and rewards—of applying
agile processes to your overall IT portfolio, with best
practices for optimizing results.
The Enterprise and Scrum
Ken Schwaber
ISBN 9780735623378
ISBN 9780735625785
Why do so many IT projects fail? Enterprise consultant
Roger Sessions believes complex problems require
simple solutions. And in this book, he shows how to
make simplicity a core architectural requirement—as
critical as performance, reliability, or security—to achieve
better, more reliable results for your organization.
ALSO SEE
Software Requirements, Second Edition
Karl E. Wiegers
ISBN 9780735618794
More About Software Requirements:
Thorny Issues and Practical Advice
Extend Scrum’s benefits—greater agility, higher-quality
products, and lower costs—beyond individual teams to
the entire enterprise. Scrum cofounder Ken Schwaber
describes proven practices for adopting Scrum principles
across your organization, including that all-critical
component—managing change.
Karl E. Wiegers
ISBN 9780735622678
Software Requirement Patterns
Stephen Withall
ISBN 9780735623989
Agile Project Management with Scrum
Ken Schwaber
ISBN 9780735619937
Solid Code
Donis Marshall, John Bruno
ISBN 9780735625921
microsoft.com/mspress
Dev BestPrac_ResPg_02.indd 1
4/4/10 9:41 PM
What do
you think of
this book?
We want to hear from you!
To participate in a brief online survey, please visit:
microsoft.com/learning/booksurvey
Tell us how well this book meets your needs­—what works effectively, and what we can
do better. Your feedback will help us continually improve our books and learning
resources for you.
Thank you in advance for your input!
Stay in touch!
To subscribe to the Microsoft Press® Book Connection Newsletter—for news on upcoming
books, events, and special offers—please visit:
microsoft.com/learning/books/newsletter
SurvPage_corp.indd 1
8/14/09 4:40 AM
Was this manual useful for you? yes no
Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Download PDF

advertising