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

Mastering Microsoft Visual Basic 2008 phần 1 ppt

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 (2.08 MB, 116 trang )

Petroutsos ffirs.tex V3 - 01/28/2008 6:03pm Page iii
Mastering Microsoft
Visual Basic 2008
Evangelos Petroutsos
Mark Ridgeway
Wiley Publishing, Inc.
Petroutsos ffirs.tex V3 - 01/28/2008 6:03pm Page ii
Petroutsos ffirs.tex V3 - 01/28/2008 6:03pm Page i
Mastering Microsoft
Visual Basic 2008
Petroutsos ffirs.tex V3 - 01/28/2008 6:03pm Page ii
Petroutsos ffirs.tex V3 - 01/28/2008 6:03pm Page iii
Mastering Microsoft
Visual Basic 2008
Evangelos Petroutsos
Mark Ridgeway
Wiley Publishing, Inc.
Petroutsos ffirs.tex V3 - 01/28/2008 6:03pm Page iv
Acquisitions Editor: Thomas Cirtin
Development Editor: Toni Zaccarini Ackley
Technical Editor: John Mueller
Production Editor: Daniel Scribner
Copy Editor: Sharon Wilkey
Production Manager: Tim Tate
Vice President and Executive Group Publisher: Richard Swadley
Vice President and Executive Publisher: Joseph B. Wikert
Vice President and Publisher: Neil Edde
Book Designer: Maureen Forys and Judy Fung
Proofreader: Nancy Riddiough
Indexer: Ron Strauss


Cover Designer: Ryan Sneed
Cover Image: Pete Gardner / Digital Vision / Getty Images
Copyright © 2008 by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN: 978-0-4701-8742-5
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 />Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with respect to
the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without limitation
warranties 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 professional 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 herefrom.
The fact that an organization or Website 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 Website may provide or recommendations it
may make. Further, readers should be aware that Internet Websites 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 or to obtain technical support, please contact our Customer Care
Department within the U.S. at (800) 762–2974, outside the U.S. at (317) 572–3993 or fax (317) 572–4002.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic
books.
Library of Congress Cataloging-in-Publication Data
Petroutsos, Evangelos.
Mastering Microsoft Visual basic 2008 / Evangelos Petroutsos. — 1st ed.
p. cm.
ISBN 978-0-470-18742-5 (paper/website)
1. Microsoft Visual BASIC. 2. BASIC (Computer program language) I. Title.

QA76.73.B3P492285 2008
005.2

762 — dc22
2007051637
TRADEMARKS: Wiley, the Wiley logo, and the Sybex logo are trademarks 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. 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.
10987654321
Petroutsos ffirs.tex V3 - 01/28/2008 6:03pm Page v
Dear Reader,
Thank you for choosing Mastering Microsoft Visual Basic 2008. This book is part of a family of
premium quality Sybex books, all written by outstanding authors who combine practical experi-
ence with a gift for teaching.
Sybex was founded in 1976. More than thirty years later, we’re still committed to producing
consistently exceptional books. With each of our titles we’re working hard to set a new standard
for the industry. From the paper we print on, to the authors we work with, our goal is to bring you
the best books available.
I hope you see all that reflected in these pages. I’d be very interested to hear your comments
and get your feedback on how we’re doing. Feel free to let me know what you think about this or
any other Sybex book by sending me an email at , or if you think you’ve found
a technical error in this book, please visit . Customer feedback is
critical to our efforts at Sybex.
Best regards,
Neil Edde
Vice President and Publisher
Sybex, an Imprint of Wiley
Petroutsos ffirs.tex V3 - 01/28/2008 6:03pm Page vi
Petroutsos ffirs.tex V3 - 01/28/2008 6:03pm Page vii

To my dearest and most precious ones, Nefeli
and Eleni-Myrsini.
Petroutsos ffirs.tex V3 - 01/28/2008 6:03pm Page viii
Petroutsos fack.tex V3 - 01/28/2008 6:06pm Page ix
Acknowledgments
Many people contributed to this book, and I would like to thank them all. I first want to express my
deep appreciation to Mark Ridgeway for contributing the Web-related chapters (Chapters 25, 26,
and 27) and Chapter 5, ‘‘The Vista Interface,’’ and to John Mueller for providing the technical edit of
this book.I want to thank the programmers at Microsoft for their commitment to Visual Basic. Visual
Basic has evolved from a small, limited programming environment to a first-class development tool
for building all types of Windows and Web applications, from small hobbyist projects to enterprise
scale applications.
Special thanks to the talented people at Sybex — to all of them and to e ach one individually.
Starting with editor Toni Zuccarini Ackley, who has taken this book under her wing and improved
it in numerous ways. To acquisitions editor Tom Cirtin, who has followed the progress of the
book, its ups and downs, and managed to coordinate the entire team. To production editor Daniel
Scribner, who kept this project in order and on schedule. Thanks, Daniel. To copyeditor Sharon
Wiley, proofreader Nancy Riddiough, indexer Ron Strauss and everyone else who added t heir
expertise and talent
Petroutsos fack.tex V3 - 01/28/2008 6:06pm Page x
Petroutsos fauth.tex V3 - 01/28/2008 6:11pm Page xi
About the Author
Evangelos Petroutsos works as a consultant on medium to large projects, teaches, and writes
articles — but he mostly writes code, VB code. He specializes in VB and SQL, and from the new
technologies, he fancies XML. He has authored many articles and more than 10 programming
books, including the best-selling titles Mastering Microsoft Visual Basic 2005 and Mastering Visual
Basic .NET Database Programming, both published by Sybex.
Petroutsos fauth.tex V3 - 01/28/2008 6:11pm Page xii
Petroutsos ftoc.tex V2 - 01/28/2008 6:12pm Page xiii
Contents at a Glance

Introduction xxix
Chapter 1

Getting Started with Visual Basic 2008 1
Chapter 2

Variables and Data Types 35
Chapter 3

Programming Fundamentals 85
Chapter 4

GUI Design and Event-Driven Programming 123
Chapter 5

The Vista Interface 151
Chapter 6

Basic Windows Controls 173
Chapter 7

Working with Forms 217
Chapter 8

More Windows Controls 267
Chapter 9

The TreeView and ListView Controls 305
Chapter 10


Building Custom Classes 349
Chapter 11

Working with Objects 395
Chapter 12

Building Custom Windows Controls 429
Chapter 13

Handling Strings, Characters, and Dates 461
Chapter 14

Storing Data in Collections 499
Chapter 15

Accessing Folders and Files 541
Chapter 16

Serialization and XML 591
Chapter 17

Querying Collections and XML with LINQ 621
Chapter 18

Drawing and Painting with Visual Basic 2008 649
Chapter 19

Manipulating Images and Bitmaps 693
Chapter 20


Printing with Visual Basic 2008 717
Petroutsos ftoc.tex V2 - 01/28/2008 6:12pm Page xiv
xiv CONTENTS AT A GLANCE
Chapter 21

Basic Concepts of Relational Databases 753
Chapter 22

Programming with ADO.NET 805
Chapter 23

Building Data-Bound Applications 845
Chapter 24

Advanced DataSet Operations 885
Chapter 25

Building Web Applications 901
Chapter 26

ASP.NET 3.5 937
Chapter 27

ASP.NET Web Services 981
Appendix A

’’The Bottom Line’’ 997
Appendix B

’’Debugging and Error Handling’’ 1045

Index 1075
Petroutsos ftoc.tex V2 - 01/28/2008 6:12pm Page xv
Contents
Introduction xxix
Chapter 1

Getting Started with Visual Basic 2008 1
Exploring the Integrated Development Environment 1
The Start Page 2
Starting a New Project 3
Using the Windows Form Designer 5
Creating Your First VB Application 11
Making the Application More User-Friendly 15
Understanding the IDE Components 18
The IDE Menu 18
Toolbox Window 23
Solution Explorer Window 23
Properties Window 23
Output Window 24
Command and Immediate Windows 24
Error List Window 25
Setting Environment Options 25
Building a Console Application 27
Using Code Snippets 29
Using the My Object 30
The Bottom Line 33
Chapter 2

Variables and Data Types 35
Variables 35

Declaring Variables 36
Types of Variables 39
The Strict, Explicit, and Infer Options 54
Object Variables 58
VariablesasObjects 60
Converting Variable Types 61
Formatting Numbers 64
User-Defined Data Types 66
Examining Variable Types 69
Why Declare Variables? 71
AVariable’sScope 71
A Variable’s Lifetime 73
Constants 74
Petroutsos ftoc.tex V2 - 01/28/2008 6:12pm Page xvi
xvi CONTENTS
Arrays 75
Declaring Arrays 75
Initializing Arrays 77
Array Limits 77
Multidimensional Arrays 78
Dynamic Arrays 81
The Bottom Line 82
Chapter 3

Programming Fundamentals 85
Flow-Control Statements 85
Decision Statements 86
Loop Statements 93
Nested Control Structures 98
The Exit Statement 100

Writing and Using Procedures 100
Subroutines 100
Functions 101
Arguments 103
Argument-Passing Mechanisms 104
Built-in Functions 107
Custom Functions 109
Passing Arguments and Returning Values 111
More Types of Function Return Values 113
Overloading Functions 117
The Bottom Line 121
Chapter 4

GUI Design and Event-Driven Programming 123
On Designing Windows Applications 123
Building a Loan Calculator 124
Understanding How the Loan Calculator Application Works 125
Designing the User Interface 126
Programming the Loan Application 129
Validating the Data 133
Building a Calculator 137
Designing the User Interface 137
Programming the MathCalculator 139
Using Simple Debugging Tools 145
Exception Handling 147
The Bottom Line 149
Chapter 5

The Vista Interface 151
Introducing XAML 151

Introducing the WPF Controls 153
Simple ‘‘Hello World’’ WPF Application 154
Simple Drawing Program 156
Petroutsos ftoc.tex V2 - 01/28/2008 6:12pm Page xvii
CONTENTS xvii
Data-Binding WPF Controls 159
Data-Binding Example 2: Binding to a Database 164
Creating a WPF Browser Application 166
Expression Blend Overview 168
The Bottom Line 171
Chapter 6

Basic Windows Controls 17 3
The TextBox Control 173
Basic Properties 174
Text-Manipulation Properties 176
Text-Selection Properties 179
Text-Selection Methods 180
Undoing Edits 181
VB 2008 at Work: The TextPad Project 181
Capturing Keystrokes 188
Auto-complete Properties 190
The ListBox, CheckedListBox, and ComboBox Controls 195
Basic Properties 196
Manipulating the Items Collection 197
Selecting Items 200
VB 2008 at Work: The ListBox Demo Project 200
Searching the ListBox 203
The ComboBox Control 205
The ScrollBar and TrackBar Controls 210

The ScrollBar Control 210
The TrackBar Control 213
The Bottom Line 214
Chapter 7

Working with Forms 217
The Appearance of Forms 217
Properties of the Form Object 218
Placing Controls on Forms 223
Setting the TabOrder Property 224
VB 2008 at Work: The Contacts Project 226
Anchoring and Docking 229
Splitting Forms into Multiple Panes 232
The Form’s Events 234
Loading and Showing Forms 236
The Startup Form 237
Controlling One Form from within Another 238
Forms versus Dialog Boxes 240
Building Dynamic Forms at Runtime 246
The Form’s Controls Collection 247
Creating Event Handlers at Runtime 253
Designing Menus 255
Petroutsos ftoc.tex V2 - 01/28/2008 6:12pm Page xviii
xviii CONTENTS
The Menu Editor 255
The ToolStripMenuItem Properties 257
Manipulating Menus at Runtime 260
Iterating a Menu’s Items 263
The Bottom Line 265
Chapter 8


More Windows Controls 267
The Common Dialog Controls 267
Using the Common Dialog Controls 268
The ColorDialog Control 270
The FontDialog Control 272
The OpenDialog and SaveDialog Controls 274
The FolderBrowserDialog Control 279
The RichTextBox Control 283
The RTF Language 284
Text Manipulation and Formatting Properties 286
Methods 289
Advanced Editing Features 290
Cutting and Pasting 291
Searching in a RichTextBox Control 291
Handling URLs in the Document 292
Displaying a Formatted Directory Listing 293
VB 2008 at Work: The RTFPad Project 294
The Bottom Line 302
Chapter 9

The TreeView and ListView Controls 305
Understanding the ListView, TreeView, and ImageList Controls 305
Tree and List Structures 306
The ImageList Control 309
The TreeView Control 310
Adding Nodes at Design Time 312
Adding Nodes at Runtime 313
VB 2008 at Work: The TreeViewDemo Project 316
VB 2008 at Work: The Globe Project 320

Scanning the TreeView Control 328
The ListView Control 330
The Columns Collection 332
ListView Items and Subitems 334
The Items Collection 336
The SubItems Collection 336
VB 2008 at Work: The ListViewDemo Project 337
Sorting the ListView Control 340
Processing Selected Items 342
VB 2008 at Work: The CustomExplorer Project 343
Additional Topics 346
The Bottom Line 347
Petroutsos ftoc.tex V2 - 01/28/2008 6:12pm Page xix
CONTENTS xix
Chapter 10

Building Custom Classes 349
Classes and Objects 349
What Is a Class? 350
Classes Combine Code with Data 351
Building the Minimal Class 352
Adding Code to the Minimal Class 355
Using Property Procedures 356
Customizing Default Members 362
Custom Enumerations 366
Object Constructors 375
Using the SimpleClass in Other Projects 376
Firing Events 378
Instance and Shared Methods 380
A ‘‘Real’’ Class 384

Parsing a Filename 384
Converting Numbers to Strings 385
Operator Overloading 388
VB 2008 at Work: The LengthUnits Class 389
The Bottom Line 394
Chapter 11

Working with Objects 395
Issues in Object-Oriented Programming 395
Classes versus Objects 395
Objects versus Object Variables 396
Properties versus Fields 400
Shared versus Instance Members 401
Type Casting 402
Early versus Late Binding 403
Discovering a Variable’s Type 404
Inheritance 404
How to Apply Inheritance 405
Polymorphism 415
Building the Shape Class 417
Who Can Inherit What? 421
Parent Class Keywords 422
Derived Class Keywords 422
Parent Class Member Keywords 423
Derived Class Member Keyword 423
VB 2008 At Work: The InheritanceKeywords Project 424
MyBase and MyClass 425
The Class Diagram Designer 427
The Bottom Line 428
Chapter 12


Building Custom Windows Controls 429
On Designing Windows Controls 429
Enhancing Existing Controls 430
Petroutsos ftoc.tex V2 - 01/28/2008 6:12pm Page xx
xx CONTENTS
Building the FocusedTextBox Control 431
Building Compound Controls 438
VB 2008 at Work: The ColorEdit Control 439
Building User-Drawn Controls 442
VB 2008 at Work: The Label3D Control 443
Raising Custom Events 450
Using the Custom Control in Other Projects 452
Designing Irregularly Shaped Controls 453
Customizing List Controls 456
Designing Owner-Drawn ListBox Controls 457
The Bottom Line 459
Chapter 13

Handling Strings, Characters, and Dates 461
Handling Strings and Characters 461
The Char Class 462
The String Class 464
The StringBuilder Class 473
VB 2008 at Work: The StringReversal Project 476
VB 2008 at Work: The CountWords Project 479
Handling Dates and Times 481
The DateTime Class 481
The TimeSpan Class 492
The Bottom Line 497

Chapter 14

Storing Data in Collections 499
Advanced Array Topics 499
Sorting Arrays 499
Searching Arrays 502
Performing Other Array Operations 506
Array Limitations 509
The ArrayList Collection 509
Creating an ArrayList 509
Adding and Removing ArrayList Items 510
Sorting ArrayLists 513
Searching ArrayLists 515
Iterating an ArrayList 515
The HashTable Collection 516
VB 2008 at Work: The WordFrequencies Project 518
The SortedList Collection 523
VB 2008 at Work: The SortedList Project 524
Other Collections 527
The IEnumerator and IComparer Interfaces 528
Enumerating Collections 528
Custom Sorting 531
Generic Collections 537
The Bottom Line 539
Petroutsos ftoc.tex V2 - 01/28/2008 6:12pm Page xxi
CONTENTS xxi
Chapter 15

Accessing Folders and Files 541
The IO Namespace and the FileSystem Component 541

Using the My.Computer.FileSystem Component 542
Manipulating Folders and Files with the IO Namespace 546
The Directory Class 547
The File Class 554
Drive, Folder, and File Properties 560
The Path Class 564
VB 2008 at Work: The CustomExplorer Project 566
Accessing Files 569
Using Streams 570
VB 2008 at Work: The RecordSave Project 580
The FileSystemWatcher Component 585
Properties 585
Events 586
VB 2008 at Work: The FileSystemWatcher Project 587
The Bottom Line 589
Chapter 16

Serialization and XML 591
Understanding Serialization Types 591
Using Binary and SOAP Serialization 592
Serializing Individual Objects 592
Deserializing Individual Objects 594
Serializing Collections 595
Deserializing Collections 596
Persisting a HashTable 598
Persisting a TreeView’s Nodes 601
Using XML Serialization 607
Serializing and Deserializing Individual Objects 608
Serializing Custom Objects 609
Serializing ArrayLists and HashTables 613

Working with XML Files 615
Understanding XML Structure 615
Editing XML Files 617
The Bottom Line 620
Chapter 17

Querying Collections and XML with LINQ 621
What Is LINQ? 621
LINQ Components 623
LINQ to Objects 625
Querying Collections 627
Aggregating with LINQ 630
LINQ to XML 631
Traversing XML Documents 633
Adding Dynamic Content to an XML Document 634
LINQ to SQL 642
Petroutsos ftoc.tex V2 - 01/28/2008 6:12pm Page xxii
xxii CONTENTS
Retrieving Data with the ExecuteQuery Method 646
The Bottom Line 647
Chapter 18

Drawing and Painting with Visual Basic 2008 649
Displaying and Sizing Images 649
Drawing with GDI+ 652
The Basic Drawing Objects 654
Drawing Shapes 663
Drawing Methods 667
Gradients 681
Clipping 685

Applying Transformations 687
VB 2008 at Work: The ImageCube Project 690
VB 2008 at Work: Plotting Functions 691
The Bottom Line 691
Chapter 19

Manipulating Images and Bitmaps 693
Specifying Colors 693
The RGB Color Cube 694
Defining Colors 695
The Image Object 699
Properties 699
Methods 699
VB 2008 at Work: The Thumbnails Project 702
Exchanging Images through the Clipboard 705
The Bitmap Object 706
Processing Bitmaps 708
VB 2008 at Work: The ImageProcessing Project 710
The Bottom Line 715
Chapter 20

Printing with Visual Basic 2008 717
The Printing Components 717
The PrintDocument Control 717
The PrintDialog Control 720
The PageSetupDialog Control 721
The PrintPreviewDialog Control 723
Printer and Page Properties 725
Retrieving the Printer Names 726
Page Geometry 728

VB 2008 at Work: The SimplePrintout Project 729
VB 2008 at Work: The PageSettings Project 732
Practical Printing Examples 737
Printing Tabular Data 738
Printing Plain Text 744
Printing Bitmaps 748
The Bottom Line 751

×