Tải bản đầy đủ (.pdf) (84 trang)

Beginning Visual Basic 2005 phần 1 potx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (1.47 MB, 84 trang )

TEAM LinG
Beginning Visual Basic
®
2005
01_574019 ffirs.qxd 9/16/05 9:31 PM Page i
Beginning Visual Basic
®
2005
Thearon Willis and Bryan Newsome
01_574019 ffirs.qxd 9/16/05 9:31 PM Page iii
01_574019 ffirs.qxd 9/16/05 9:31 PM Page ii
Beginning Visual Basic®2005
Published by
Wiley Publishing, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com
Copyright © 2006 by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN-10: 0-7645-7401-9
ISBN-13: 978-0-7645-7401-6
Manufactured in the United States of America
10987654321
1MA/QV/RQ/QV/IN
Library of Congress Cataloging-in-Publication Data
Willis, Thearon.
Beginning Visual Basic 2005 / Thearon Willis and Bryan Newsome.
p. cm.
Includes bibliographical references and index.
ISBN-13: 978-0-7645-7401-6 (paper/website)
ISBN-10: 0-7645-7401-9 (paper/website)


1. Microsoft Visual BASIC. 2. BASIC (Computer program language) I. Newsome, Bryan, 1971- II. Title.
QA76.73.B3W5573 2005
005.2'768 dc22
2005010385
No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any means,
electronic, mechanical, photocopying, recording, scanning, or otherwise, except as permitted under Sections 107 or 108 of
the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization
through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA
01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Legal
Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4355, or
online at www.wiley.com/go/permissions.
LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REPRE-
SENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF
THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT LIMITATION WAR-
RANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY
SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE
SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS
NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES. IF PROFES-
SIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE
SOUGHT. NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HERE-
FROM. THE FACT THAT AN ORGANIZATION OR WEB SITE IS REFERRED TO IN THIS WORK AS A CITATION
AND/OR A POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE
PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEB SITE MAY PROVIDE OR RECOM-
MENDATIONS IT MAY MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEB SITES LISTED IN
THIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND
WHEN IT IS READ.
For general information on our other products and services please contact our Customer Care Department within the
United States at (800) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.
Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer, and related trade dress are trade-
marks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries,

and may not be used without written permission.Visual Basic is a registered trademark of Microsoft Corporation in the
United States and/or other countries. All other trademarks are the property of their respective owners. Wiley Publishing,
Inc., is not associated with any product or vendor mentioned in this book.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available
in electronic books.
01_574019 ffirs.qxd 9/16/05 9:31 PM Page iv
About the Authors
Thearon Willis is a Senior Consultant with over 20 years of programming experience. He started writing
applications using the BASIC language in 1980 and later moved on to Visual Basic and finally to Visual
Basic .NET.
Thearon began working with databases in 1987 and has been hooked on writing database applications
every since. He has experience with SQL Server, Oracle, and DB2 but works with SQL Server on a daily
basis. Thearon has programmed in several other languages, some of which include C++, assembly lan-
guage, Pascal, and COBOL. However, he enjoys Visual Basic .NET the best because it provides the fea-
tures needed to quickly build Windows and Web applications, as well as components and Web Services.
Thearon currently develops intranet applications, Web Services, and server-side and client-side utilities
using Visual Basic .NET. Most of these applications and utilities are database-driven and make use of
XML and XSL. Thearon lives with his wife Margie and daughter Stephanie in the Raleigh, North
Carolina, area.
Bryan Newsome works in Charlotte, North Carolina, as a custom software project manager specializing
in Microsoft solutions. He leads a team of developers focused on meeting the needs of each client and
project using the latest technologies. Each day, he helps provide clients with solutions and mentoring on
leading-edge Microsoft technologies. Bryan is a Microsoft Certified Application Developer for .NET.
01_574019 ffirs.qxd 9/16/05 9:31 PM Page v
01_574019 ffirs.qxd 9/16/05 9:31 PM Page vi
Credits
Acquisitions Editor
Katie Mohr
Development Editor
Sydney Jones

Technical Editor
Todd Meister
Production Editor
William A. Barton
Copy Editor
Publication Services, Inc.
Editorial Manager
Mary Beth Wakefield
Vice President & Executive Group Publisher
Richard Swadley
Vice President and Publisher
Joseph B. Wikert
Project Coordinator
Ryan Steffen
Graphics and Production Specialists
Andrea Dahl
Lauren Goddard
Lynsey Osborn
Alicia South
Julie Trippetti
Quality Control Technicians
Leeann Harney
Carl William Pierce
Media Development Specialists
Angela Denny
Kit Malone
Travis Silvers
Proofreading and Indexing
TECHBOOKS Production Services
01_574019 ffirs.qxd 9/16/05 9:31 PM Page vii

01_574019 ffirs.qxd 9/16/05 9:31 PM Page viii
As always, I want to thank my wife Margie and my daughter Stephanie for the patience they have
shown while I write another book. Without their love and support, none of this would be possible.
—Thearon Willis
To all of the friends and family that make my life special in the past, present, and future: Jennifer (love
you, honey), Katelyn, Mom (I miss you), Dad, Ashley and Leslie, Judy and Tony, Jennifer S. and Steven.
All my love and happiness to each of you.
—Bryan Newsome
01_574019 ffirs.qxd 9/16/05 9:31 PM Page ix
01_574019 ffirs.qxd 9/16/05 9:31 PM Page x
Contents
Acknowledgments xxvii
Introduction xxix
Who Is This Book For? xxix
What Does This Book Cover? xxix
What Do I Need to Run Visual Basic 2005? xxx
Conventions xxxi
Customer Support xxxii
How to Download the Sample Code for the Book xxxii
Errata xxxii
p2p.wrox.com xxxiii
Why This System Offers the Best Support xxxiii
Chapter 1: Welcome to Visual Basic 2005 1
Windows Versus DOS Programming 2
Installing Visual Basic 2005 3
The Visual Basic 2005 IDE 6
The Profile Setup Page 7
The Menu 7
The Toolbars 8
Creating a Simple Application 9

Windows in the Visual Studio 2005 IDE 10
The Toolbox 13
Modified Hungarian Notation 17
The Code Editor 18
Using the Help System 22
Summary 23
Exercise 23
Chapter 2: The Microsoft .NET Framework 25
Microsoft’s Reliance on Windows 25
MSN 1.0 26
The .NET Vision 27
This Sounds like Java 28
Where Now? 29
Writing Software for Windows 29
02_574019 ftoc.qxd 9/16/05 9:50 PM Page xi
xii
Contents
The .NET Framework Classes 30
Executing Code 31
Common Language Runtime 33
Code Loading and Execution 33
Application Isolation 33
Security 34
Interoperation 34
Exception Handling 34
The Common Type System and Common Language Specification 35
Summary 36
Chapter 3: Writing Software 37
Information and Data 37
Algorithms 38

What Is a Programming Language? 39
Variables 39
Working with Variables 40
Comments and Whitespace 42
Comments 42
White Space 44
Data Types 44
Working with Numbers 44
Common Integer Math Operations 45
Integer Math Shorthand 47
The Problem with Integer Math 48
Floating-Point Math 49
Other States 50
Single-Precision Floating-Point Numbers 50
Working with Strings 51
Concatenation 52
Using the Concatenation Operator Inline 54
More String Operations 55
Substrings 56
Formatting Strings 57
Localized Formatting 58
Replacing Substrings 59
Using Dates 60
Formatting Date Strings 61
Extracting Date Properties 62
Date Constants 63
Defining Date Literals 64
02_574019 ftoc.qxd 9/16/05 9:50 PM Page xii
xiii
Contents

Manipulating Dates 65
Boolean 66
Storing Variables 67
Binary 67
Bits and Bytes 68
Representing Values 68
Converting Values 70
Methods 71
Why Use Methods? 72
Methods You’ve Already Seen 72
Building a Method 76
Choosing Method Names 79
Scope 80
Summary 82
Exercises 82
Exercise 1 82
Exercise 2 82
Chapter 4: Controlling the Flow 83
Making Decisions 83
The If Statement 84
The Else Statement 86
Allowing Multiple Alternatives with ElseIf 87
Nested If Statements 88
Single-Line If Statement 88
Comparison Operators 88
Using Not Equal To 89
Using the Numeric Operators 90
The And and Or Operators 93
More on And and Or 97
String Comparison 97

Select Case 99
Using Select Case 100
Case-Insensitive Select Case 103
Multiple Selections 106
The Case Else Statement 107
Different Data Types with Select Case 108
Loops 108
The For . . . Next Loop 109
Step 111
Looping Backwards 112
The For Each . . . Next Loop 113
02_574019 ftoc.qxd 9/16/05 9:50 PM Page xiii
xiv
Contents
The Do . . . Loop Loops 114
Do While . . . Loop 116
Acceptable Expressions for a Do . . . Loop 118
Other Versions of the Do . . . Loop 118
Nested Loops 119
Quitting Early 120
Quitting Do . . . Loops 122
Infinite Loops 123
Summary 124
Exercises 124
Exercise 1 124
Exercise 2 124
Chapter 5: Working with Data Structures 125
Understanding Arrays 125
Defining and Using Arrays 126
Using For Each . . . Next 128

Passing Arrays as Parameters 130
Sorting Arrays 133
Going Backwards 133
Initializing Arrays with Values 135
Understanding Enumerations 136
Using Enumerations 136
Determining the State 140
Setting Invalid Values 142
Understanding Constants 143
Using Constants 143
How It Works 145
Different Constant Types 145
Structures 145
Building Structures 146
Adding Properties to Structures 149
Working with ArrayLists 149
Using an ArrayList 150
Deleting from an ArrayList 153
Showing Items in the ArrayList 156
Working with Collections 157
Creating CustomerCollection 158
Adding an Item Property 159
Building Lookup Tables with Hashtable 161
02_574019 ftoc.qxd 9/16/05 9:50 PM Page xiv
xv
Contents
Using Hashtables 161
Cleaning Up: Remove, RemoveAt, and Clear 164
Case Sensitivity 167
Advanced Array Manipulation 168

Dynamic Arrays 168
Using Preserve 170
Summary 171
Exercises 172
Exercise 1 172
Exercise 2 172
Chapter 6: Building Windows Applications 173
Responding to Events 173
Setting Up a Button Event 174
Building a Simple Application 178
Building the Form 178
Counting Characters 180
Counting Words 182
Creating the Show Me! Button Code 185
Creating More Complex Applications 186
The Text Manipulation Project 186
Creating the Toolbar 186
Creating the Status Bar 190
Creating an Edit Box 191
Clearing the Edit Box 191
Responding to Toolbar Buttons 194
Understanding Focus 198
Using Multiple Forms 199
Help About 199
Summary 203
Exercises 203
Exercise 1 203
Exercise 2 203
Chapter 7: Displaying Dialog Boxes 205
The MessageBox Dialog Box 205

Available Icons for MessageBox 206
Available Buttons for MessageBox 207
Setting the Default Button 207
Miscellaneous Options 207
The Show Method Syntax 208
02_574019 ftoc.qxd 9/16/05 9:50 PM Page xv
xvi
Contents
Example Message Boxes 209
The OpenDialog Control 213
The OpenFileDialog Control 213
The Properties of OpenFileDialog 214
The Methods of OpenFileDialog 215
Using the OpenFileDialog Control 216
The SaveDialog Control 220
The Properties of SaveFileDialog 220
The Methods of SaveFileDialog 221
Using the SaveFileDialog Control 221
The FontDialog Control 225
The Properties of FontDialog 225
The Methods of FontDialog 226
Using the FontDialog Control 226
The ColorDialog Control 229
The Properties of ColorDialog 230
Using the ColorDialog Control 231
The PrintDialog Control 232
The Properties of PrintDialog 233
Using the PrintDialog Control 234
The PrintDocument Class 234
The Properties of the PrintDocument Class 234

Printing a Document 234
The FolderBrowserDialog Control 241
The Properties of FolderBrowserDialog 242
Using the FolderBrowserDialog Control 242
How It Works 244
Summary 245
Exercises 246
Exercise 1 246
Exercise 2 246
Chapter 8: Creating Menus 247
Understanding Menu Features 247
Images 248
Access Keys 248
Shortcut Keys 248
Check Marks 248
The Properties Window 249
Creating Menus 250
Designing the Menus 250
Adding Toolbars and Controls 252
Coding Menus 254
02_574019 ftoc.qxd 9/16/05 9:50 PM Page xvi
xvii
Contents
Coding the View Menu and Toolbars 259
Testing Your Code 260
Context Menus 262
Creating Context Menus 263
Enabling and Disabling Menu Items and Toolbar Buttons 266
Summary 270
Exercise 270

Chapter 9: Debugging and Error Handling 271
Major Error Types 272
Syntax Errors 272
Execution Errors 275
Logic Errors 275
Debugging 277
Creating a Sample Project 277
Setting Breakpoints 293
Debugging Using the Watch Window 300
Debugging with the Locals Window 302
Error Handling 304
Using Structured Error Handling 305
Summary 307
Exercises 308
Exercise 1 308
Exercise 2 308
Chapter 10: Building Objects 309
Understanding Objects 309
Encapsulation 311
Methods and Properties 311
Events 311
Visibility 312
What Is a Class? 313
Building Classes 313
Reusability 314
Designing an Object 315
State 316
Behavior 316
Storing State 317
Real Properties 319

Read/Write Properties 323
The IsMoving Method 325
Constructors 327
02_574019 ftoc.qxd 9/16/05 9:50 PM Page xvii
xviii
Contents
Creating a Constructor 327
Inheritance 329
Adding New Methods and Properties 331
Adding a GetPowerToWeightRatio Method 333
Changing Defaults 335
Polymorphism: Scary Word, Simple Concept 336
Overriding More Methods 337
Inheriting from the Object Class 339
Objects and Structures 340
The Framework Classes 340
Namespaces 341
The Imports Statement 343
Creating Your Own Namespace 343
Inheritance in the .NET Framework 345
Summary 346
Exercises 346
Exercise 1 346
Exercise 2 346
Chapter 11: Advanced Object-Oriented Techniques 347
Building a Favorites Viewer 347
Internet Shortcuts and Favorites 348
Using Classes 350
Scanning Favorites 355
Viewing Favorites 363

An Alternative Favorite Viewer 365
Building a Favorites Tray 365
How It Works 368
Displaying Favorites 368
Using Shared Properties and Methods 371
Using Shared Procedures 372
Using Shared Methods 376
Understanding Object-Oriented Programming and Memory Management 378
Garbage Collection 379
Releasing Resources 380
Defragmentation and Compaction 381
Summary 382
Exercise 382
02_574019 ftoc.qxd 9/16/05 9:50 PM Page xviii
xix
Contents
Chapter 12: Building Class Libraries 383
Understanding Class Libraries 384
Creating a Class Library 384
Building a Class Library for Favorites Viewer 386
A Multitiered Application 388
Using Strong Names 389
Signing Assemblies 390
Assembly Versions 392
Registering Assemblies 392
Gacutil Utility 393
Why Is My Assembly Not Visible in the References Dialog Box? 393
Designing Class Libraries 395
Using Third-Party Class Libraries 396
Using InternetFavorites.dll 396

Viewing Classes with the Object Browser 397
Summary 398
Exercise 398
Chapter 13: Creating Your Own Custom Controls 399
Windows Forms Controls 400
Creating and Testing a User Control 400
Exposing Properties from User Controls 404
Adding Properties 404
Exposing Methods from User Controls 405
Exposing Events from User Controls 406
Design Time or Run Time 411
Creating a Form Library 413
Building the Form Library Project Login Form 413
Testing the FormsLibrary 420
Hooking Up the Events 422
Summary 425
Exercise 426
Chapter 14: Programming Custom Graphics 427
Building a Simple Paint Program 427
Creating a Project with User Controls 428
How Drawing Programs Work 428
Raster Graphics 428
Vector Graphics 429
02_574019 ftoc.qxd 9/16/05 9:50 PM Page xix
xx
Contents
The GraphicsItem Class 430
Screen and Client Coordinates 432
Listening to the Mouse and Drawing GraphicsCircle Objects 434
Invalidation 438

Optimized Drawing 439
Choosing Colors 440
Creating the ColorPalette Control and Sizing the Control 440
Responding to Clicks 446
Dealing with Two Colors 449
Indicating the Assigned Buttons 451
Using Advanced Colors 457
Using the Color Dialog Box 459
Using System Colors 460
Using Different Tools 461
Implementing Hollow Circle 461
Working with Images 466
Drawing Images 467
Scaling Images 469
Preserving the Aspect Ratio 471
More Graphics Methods 473
Summary 474
Chapter 15: Accessing Databases 475
What Is a Database? 475
Microsoft Access Objects 476
Tables 476
Queries 476
The SQL SELECT Statement 477
Queries in Access 479
Creating a Customer Query 479
Data Access Components 483
DataSet 483
DataGridView 484
BindingSource 484
BindingNavigator 484

TableAdapter 484
Data Binding 485
Summary 491
Exercises 492
Exercise 1 492
Exercise 2 492
02_574019 ftoc.qxd 9/16/05 9:50 PM Page xx
xxi
Contents
Chapter 16: Database Programming with SQL Server and ADO.NET 493
ADO.NET 494
ADO.NET Data Namespaces 494
The SqlConnection Class 495
Working with the Connection String Parameters 495
Opening and Closing the Connection 497
SqlCommand 497
The Connection Property 497
The CommandText Property 498
The Parameters Collection 498
The ExecuteNonQuery Method 499
SqlDataAdapter 499
The SelectCommand Property 500
Using Command Builders to Create the Other Commands 502
The Fill Method 502
The DataSet Class 504
DataView 504
The Sort Property 505
The RowFilter Property 505
The Find Method 506
The ADO.NET Classes in Action 507

Examining a DataSet Example 507
How It Works 511
Data Binding 515
BindingContext and CurrencyManager 516
Binding Controls 517
Binding Example 518
How It Works: FillDataSetAndView 525
Summary 546
Exercises 547
Exercise 1 547
Exercise 2 547
Chapter 17: Web Forms 549
Thin-Client Architecture 550
Web Forms versus Windows Forms 551
Windows Forms Advantages 551
Web Forms Advantages 551
Web Applications: The Basic Pieces 552
Web Servers 552
Browsers 552
02_574019 ftoc.qxd 9/16/05 9:50 PM Page xxi
xxii
Contents
HyperText Markup Language 552
VBScript and JavaScript 553
Cascading Style Sheets 553
Active Server Pages 553
Benefits 553
Special Web Site Files 554
Global.asax 554
Web.config 554

Development 554
Controls: The Toolbox 554
Building Web Applications 555
Creating a Web Form for Client- and Server-Side Processing 555
Performing Data Entry and Validation 561
Designing the Site’s Look and Feel 565
How It Works 571
Using the GridView to Build a Data-Driven Web Form 575
Web Site Locations with VS 2005 580
Summary 582
Exercise 583
Chapter 18: Forms Authentication 585
Web Site Authentication 585
Windows Authentication 585
Forms Authentication 586
Web Site Administration Tool (WAT) 586
How It Works 594
Login Controls 595
Summary 607
Exercises 608
Exercise 1 608
Exercise 2 609
Chapter 19: Visual Basic 2005 and XML 611
Understanding XML 611
What Does XML Look Like? 612
XML for Visual Basic Newcomers 614
The Address Book Project 615
Creating the Project 615
The SerializableData Class 616
Loading the XML File 622

02_574019 ftoc.qxd 9/16/05 9:50 PM Page xxii
xxiii
Contents
Changing the Data 625
Sending E-mail 625
Creating a List of Addresses 627
Ignoring Members 631
Loading Addresses 633
Adding New Addresses 634
Navigating Addresses 636
Deleting Addresses 638
Testing at the Edges 639
Integrating with the Address Book Application 640
Demonstrating the Principle of Integration 640
Reading the Address Book from Another Application 642
Summary 647
Exercises 647
Exercise 1 647
Exercise 2 647
Chapter 20: Web Services and .NET Remoting 649
What Is a Web Service? 649
How Does a Web Service Work? 650
SOAP 651
Building a Web Service 653
A Web Services Demonstration 654
Adding More Methods 656
The Picture Server Service 657
Creating the Project 658
Returning Arrays 660
Returning Complex Information 664

The Picture Server Client 668
Web Services Description Language 668
Creating the Client 668
Adding a Web Reference 670
Displaying the Folder List 671
Displaying the File List and Choosing Files 675
.NET Remoting 678
Generating the Proxy 682
Summary 685
Exercises 686
Exercise 1 686
Exercise 2 686
02_574019 ftoc.qxd 9/16/05 9:50 PM Page xxiii
xxiv
Contents
Chapter 21: Deploying Your Application 687
What Is Deployment? 687
ClickOnce Deployment 688
XCOPY Deployment 693
Creating a Visual Studio 2005 Setup Application 693
Creating a Setup application 694
User Interface Editor 697
Deploying Different Solutions 700
Private Assemblies 700
Shared Assemblies 701
Deploying Desktop Applications 702
Deploying Web Applications 702
Deploying XML Web Services 702
Useful Tools 702
Summary 703

Exercises 703
Exercise 1 703
Exercise 2 704
Chapter 22: Building Mobile Applications 705
Understanding the Environment 705
Common Language Runtime 706
ActiveSync 706
Common in the Compact Framework 707
The Compact Framework Classes 708
Building a Pocket PC Game 711
Summary 723
Exercise 723
Appendix A: Where To Now? 725
Online Resources 726
P2P.Wrox.com 726
Microsoft Resources 726
Other Resources 727
Offline Resources (Books) 727
Professional VB .NET, 2nd Edition 727
ASP.NET 2.0 Beta Preview 728
02_574019 ftoc.qxd 9/16/05 9:50 PM Page xxiv

×