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

Beginning Visual Basic 2012 docx

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 (12.12 MB, 724 trang )

Willis,
Newsome
$44.99 USA
$53.99 CAN
Programming Languages / Visual Basic
A thorough introduction to
the basics of Visual Basic 2010
wrox.com
Programmer
Forums
Join our Programmer to
Programmer forums to ask
and answer programming
questions about this book,
join discussions on the
hottest topics in the industry,
and connect with fellow
programmers from around
the world.
Code Downloads
Take advantage of free code
samples from this book, as
well as code samples from
hundreds of other books, all
ready to use.
Read More
Find articles, ebooks, sample
chapters, and tables of contents
for hundreds of books, and
more reference resources on
programming topics that matter


to you.
Synonymous with writing code in Visual Studio 2010, Visual Basic
is an incredibly popular programming language. Its speed and ease
of use make it a frequent first choice for new programmers, as well
as a heavily favored choice for the more experienced set eager to
learn Visual Basic’s latest iteration. This beginning guide provides
you with a solid foundation, unlocking the power and possibilities
of Visual Basic 2010 and giving detailed steps for quickly and easily
writing useful programs.
Beginning Microsoft Visual Basic 2010:
• Details the process for creating Windows Forms applications, WPF
Windows applications, web applications, WPF browser applications,
mobile device applications, and Web Services
• Discusses application debugging, error handling, and dealing with
unexpected events
• Addresses object-oriented programming and how to use it in your
applications
• Reviews dynamic data web sites and ASP.NET
• Introduces XML and shows how it can be used to integrate your
applications with others
• Explains deploying applications using ClickOnce technology
• Covers Access
®
, SQL Server
®
, and ADO.NET
Thearon Willis is an author or coauthor of nearly a dozen books and a senior
consultant who develops intranet applications using ASP.NET, DHTML, XML,
JavaScript, VBScript, VB COM components, and SQL Server.
Bryan Newsome is an author or coauthor of many books and works for a Microsoft

Partner in Charlotte specializing in Custom Software Solutions. He provides clients
with solutions and mentoring on leading-edge Microsoft technologies.
Wrox Beginning guides are crafted to make learning programming languages
and technologies easier than you think, providing a structured, tutorial format
that will guide you through all the techniques involved.
Wrox Programmer to Programmer™
Join the discussion @ p2p.wrox.com
Beginning
Visual Basic
®

2010
Microsoft
®
Visual Basic
®
2010
Microsoft
®
Thearon Willis, Bryan Newsome
Beginning
www.it-ebooks.info
Get more out of
wrox.com
Programmer to Programmer

Interact
Take an active role online by participating in our
P2P forums @ p2p.wrox.com
Wrox Online Library

Hundreds of our books are available online
through Books24x7.com
Wrox Blox
Download short informational pieces and code
to keep you up to date and out of trouble!
Join the Community
Sign up for our free monthly newsletter at
newsletter.wrox.com
Browse
Ready for more Wrox? We have books and
e-books available on .NET, SQL Server, Java,
XML, Visual Basic, C#/ C++, and much more!
Contact Us.
We always like to get feedback from our readers. Have a book idea?
Need community support? Let us know by e-mailing
Related Wrox Books
Beginning ASP.NET 4
ISBN: 978-0-470-50221-1
Microsoft MVP Imar Spaanjaars walks you through ASP.NET, Microsoft’s technology for building dynamically generated web
pages from database content. You’ll discover many improvements that ASP.NET 4 offers over the previous version, such as
Ajax improvements, jQuery support, and more. With this book you’ll gradually build a web site example that takes you through
the processes of building basic ASP.NET web pages, adding features with pre-built server controls, designing consistent pages,
displaying data, and more.
Beginning Microsoft Visual C# 2010
ISBN: 978-0-470-50226-6
Beginning Microsoft Visual C# 2010 starts with the basics and brings you thoroughly up to speed. You’ll first cover the fundamentals
such as variables, flow control, and object-oriented programming and gradually build your skills for web and Windows programming,
Windows forms, and data access.
Professional Visual Basic 2010 and .NET 4
ISBN: 978-0-470-50224-2

If you’ve already covered the basics and want to dive deep into VB and .NET topics that professional programmers use most, this
is your book. You’ll find a quick review of introductory topics before the author team of experts moves into such topics as data
access with ADO.NET, Language Integrated Query (LINQ), security, ASP.NET web programming with Visual Basic, Windows workflow,
threading, and more. You’ll explore all the new features of Visual Basic 2010 as well as all the essential functions that you need,
including .NET features such as LINQ to SQL, LINQ to XML, WCF, and more. Plus, you’ll examine exception handling and debugging,
Visual Studio features, and ASP.NET web programming.
Visual Basic 2010 Programmer’s Reference
ISBN: 978-0-470-49983-2
Visual Basic expert Rod Stephens shows you how to leverage the latest features of VB 2010. This book covers the newest features
of Visual Basic 2010, such as array literals and initializers, collection initializers, implicit line continuation, Lambda expressions, and
more, and features extensively revised and tested code to ensure compliance with the latest release.
Visual Studio 2010 and .NET 4 Six-in-One
ISBN: 978-0-470-49948-1
This comprehensive resource offers all you need to know to get productive with .NET 4. Experienced authors and .NET gurus review all
the important new features of .NET 4, including .NET charting and ASP.NET charting, ASP.NET dynamic data and jQuery, and more.
www.it-ebooks.info
BEGINNING
MICROSOFT
®
VISUAL BASIC 2010
INTRODUCTION xxix
CHAPTER 1 WelcometoVisualBasic2010 1
CHAPTER 2 TheMicrosoft.NETFramework 23
CHAPTER 3 WritingSoftware 37
CHAPTER 4 Controlling the Flow 83
CHAPTER 5 WorkingwithDataStructures 123
CHAPTER 6 ExtensibleApplicationMarkupLanguage(XAML) 169
CHAPTER 7 BuildingWindowsApplications 193
CHAPTER 8 DisplayingDialogBoxes 237
CHAPTER 9 CreatingMenus 277

CHAPTER 10 Debugging and Error Handling 299
CHAPTER 11 BuildingObjects 339
CHAPTER 12 AdvancedObject-OrientedTechniques 381
CHAPTER 13 BuildingClassLibraries 417
CHAPTER 14 CreatingWindowsFormsUserControls 435
CHAPTER 15 AccessingDatabases 463
CHAPTER 16 DatabaseProgrammingwithSQLServerandADO.NET 483
CHAPTER 17 DynamicDataWebSite 537
CHAPTER 18 ASP.NET 549
www.it-ebooks.info
CHAPTER 19 VisualBasic2010andXML 583
CHAPTER 20 DeployingYourApplication 621
APPENDIX A ExerciseSolutions 639
APPENDIX B WheretoNow? 655
INDEX 661
www.it-ebooks.info
BEGINNING
Microsoft
®
Visual Basic 2010
www.it-ebooks.info
www.it-ebooks.info
BEGINNING
Microsoft
®
Visual Basic 2010
Thearon Willis
Bryan Newsome
Wiley Publishing, Inc.
www.it-ebooks.info

Beginning Microsoft
®
Visual Basic 2010
Published by
Wiley Publishing, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com
Copyright © 2010 by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN: 978-0-470-50222-8
Manufactured in the United States of America
10987654321
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
Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-
6008, 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 pro-
motional 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 pub-
lisher nor the author shall be liable for damages arising herefrom. 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 recommendations 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 (877) 762-2974, outside the United States 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 Control Number: 2009943647
Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Wrox Programmer to Programmer, and related trade dress 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. Microsoft and Visual Basic are registered trademarks 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.
www.it-ebooks.info
For my daughter, Stephanie, my most precious gift from God.
For Wendy, my wife and friend in Christ
— Thearon
For my wife Jennifer and daughter Katelyn.
— Bryan
www.it-ebooks.info
www.it-ebooks.info
ABOUT THE AUTHORS
THEARON WILLIS currently works as a senior developer and develops Windows applica-
tions and add-ins for Microsoft Office products using Microsoft Visual Basic .NET. Over
the years, Thearon has worked on a variety of systems from mainframe to client-server
development.
BRYAN NEWSOME leads a team of lead developers specializing in Microsoft solutions.
Since starting his career building Visual Basic 5 solutions, he has embraced each new
version Visual Basic and now creates all new solutions leveraging the .NET platform and
VB.NET. He provides clients with solutions and mentoring on leading edge Microsoft
technologies. For VB.NET, Bryan is a Microsoft Certified Application Developer.

www.it-ebooks.info
www.it-ebooks.info
ABOUT THE TECHNICAL EDITOR
DAMIEN FOGGON is a developer, writer, and technical reviewer in cutting-edge technologies and has
contributed to more than 50 books on .NET, C#, Visual Basic, and ASP.NET. He is a multiple MCPD
in .NET 2.0 and .NET 3.5 and can be found online at

.
www.it-ebooks.info
www.it-ebooks.info
CREDITS
ACQUISITIONS EDITOR
Paul Reese
PROJECT EDITOR
Maureen Spears
TECHNICAL EDITOR
Damien Foggon
PRODUCTION EDITOR
Eric Charbonneau
COPY EDITOR
Luann Rouff
EDITORIAL DIRECTOR
Robyn B. Siesky
EDITORIAL MANAGER
Mary Beth Wakefield
MARKETING MANAGER
David Mayhew
PRODUCTION MANAGER
Tim Tate
VICE PRESIDENT AND EXECUTIVE GROUP

PUBLISHER
Richard Swadley
VICE PRESIDENT AND EXECUTIVE
PUBLISHER
Barry Pruett
ASSOCIATE PUBLISHER
Jim Minatel
PROJECT COORDINATOR, COVER
Lynsey Stanford
PROOFREADER
Jen Larsen, Word One
INDEXER
Johnna VanHoose Dinse
COVER IMAGE
© biffspandex/istockphoto
www.it-ebooks.info
www.it-ebooks.info
ACKNOWLEDGMENTS
FIRST AND FOREMOST I WANT to thank God for giving me the wisdom and knowledge to share with
others and for the many talents that he has blessed me with. I would also like to thank all the people
at Wiley who work so hard to bring this book to market. I’d be remiss if I didn’t thank my good friend
and co-author Bryan Newsome; thanks for your hard work and dedication.
—Thearon
THANKS TO EVERYONE AT WILEY who worked so hard to get this book on the shelves. Special thanks
to Maureen Spears who went above and beyond to help me finish my review on schedule. Of course,
thanks goes out to Thearon Willis for completing one more edition.
—Bryan
www.it-ebooks.info
www.it-ebooks.info
CONTENTS

INTRODUCTION xxix
CHAPTER 1: WELCOME TO VISUAL BASIC 2010 1
Event-Driven Programming 2
Installing Visual Basic 2010 3
The Visual Studio 2010 IDE 6
The Profile Setup Page 7
The Menu 7
The Toolbars 9
Creating a Simple Application 10
Windows in the Visual Studio 2010 IDE 11
The Toolbox 13
Modified Hungarian Notation 15
The Code Editor 16
Using the Help System 20
Summary 20
CHAPTER 2: THE MICROSOFT .NET FRAMEWORK 23
Microsoft’s Reliance on Windows 23
MSN 1.0 24
The .NET Vision 25
This Sounds Like Java 26
Where Now? 27
Writing Software for Windows 27
The .NET Framework Classes 28
Executing Code 29
Common Language Runtime 30
Code Loading and Execution 31
Application Isolation 31
Security 31
Interoperability 32
Exception Handling 32

The Common Type System and Common Language Specification 33
Summary 33
www.it-ebooks.info
CONTENTS
CHAPTER 3: WRITING SOFTWARE 37
Information and Data 37
Algorithms 38
What Is a Programming Language? 39
Working with Variables 39
Comments and Whitespace 42
Comments 42
Whitespace 43
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 51
Single-Precision Floating-Point Numbers 51
Working with Strings 51
Concatenation 53
Using the Concatenation Operator Inline 54
More String Operations 54
Substrings 55
Formatting Strings 56
Localized Formatting 58
Replacing Substrings 58
Using Dates 59
Formatting Date Strings 60

Extracting Date Properties 61
Date Constants 62
DefiningDateLiterals 63
Manipulating Dates 64
Boolean 65
Storing Variables 65
Binary 66
Bits and Bytes 66
Representing Values 67
Converting Values 68
Methods 70
Why Use Methods? 70
Methods You’ve Already Seen 71
XVIII
www.it-ebooks.info
CONTENTS
Building a Method 75
Choosing Method Names 77
Scope 78
Summary 80
CHAPTER 4: CONTROLLING THE FLOW 83
Making Decisions 83
The If Statement 84
The Else Statement 86
Allowing Multiple Alternatives with ElseIf 86
Nested If Statements 88
Single-Line If Statement 88
Comparison Operators 88
Using Not Equal To 88
Using the Numeric Operators 90

The And and Or Operators 93
Using the And Operator 95
More on And and Or 96
String Comparison 97
Select Case 98
Case-Insensitive Select Case 101
Multiple Selections 104
The Case Else Statement 105
Different Data Types with Select Case 105
Loops 106
The For Next Loop 106
Using the Step Keyword 108
Looping Backwards 109
The For Each Next Loop 110
The Do Loop Loops 111
Do While Loop 113
Acceptable Expressions for a Do Loop 114
Other Versions of the Do Loop 114
Nested Loops 115
Quitting Early 117
Quitting Do Loops 118
Infinite Loops 119
Summary 120
XIX
www.it-ebooks.info
CONTENTS
CHAPTER 5: WORKING WITH DATA STRUCTURES 123
Understanding Arrays 123
Defining and Using Arrays 123
Using For Each Next 126

Passing Arrays As Parameters 128
Sorting Arrays 130
Going Backwards 131
Initializing Arrays with Values 132
Understanding Enumerations 133
Using Enumerations 134
Determining the State 137
Setting Invalid Values 139
Understanding Constants 139
Using Constants 140
Different Constant Types 142
Structures 142
Building Structures 142
Adding Properties to Structures 145
Working with ArrayLists 146
Using an ArrayList 146
Deleting from an ArrayList 149
Showing Items in the ArrayList 152
Working with Collections 153
Creating CustomerCollection 154
Adding an Item Property 155
Building Lookup Tables with Hashtable 157
Using Hashtables 157
Cleaning Up: Remove, RemoveAt, and Clear 160
Case Sensitivity 162
Advanced Array Manipulation 164
Dynamic Arrays 164
Using Preserve 165
Summary 166
CHAPTER 6: EXTENSIBLE APPLICATION MARKUP LANGUAGE (XAML) 169

What Is XAML? 170
XAML Syntax 171
XX
www.it-ebooks.info
CONTENTS
Windows Presentation Foundation 174
CreatingaRichWPFUserInterface 175
Using WPF Common Controls 180
Wiring Up Events 186
Summary 189
CHAPTER 7: BUILDING WINDOWS APPLICATIONS 193
Responding to Events 193
Setting Up a Button Event 194
Building a Simple Application 201
Building the Form 201
Counting Characters 205
Counting Words 207
Creating More Complex Applications 213
The Text Editor Project 213
Creating the Toolbar 214
Creating the Status Bar 218
Creating an Edit Box 220
Clearing the Edit Box 222
Responding to Toolbar Buttons 224
Using Multiple Forms 230
The About Dialog Box 230
Summary 233
CHAPTER 8: DISPLAYING DIALOG BOXES 237
The MessageBox 237
Available Icons for MessageBox 238

Available Buttons for MessageBox 239
Setting the Default Button 239
Miscellaneous Options 239
The Show Method Syntax 240
Example Message Boxes 241
The OpenFileDialog Control 244
The OpenFileDialog Control 245
The Properties of OpenFileDialog 246
OpenFileDialog Methods 247
Using the OpenFileDialog Control 247
XXI
www.it-ebooks.info
CONTENTS
The SaveDialog Control 252
The Properties of SaveFileDialog 252
SaveFileDialog Methods 253
Using the SaveFileDialog Control 253
The FontDialog Control 257
The Properties of FontDialog 257
The Methods of FontDialog 257
Using the FontDialog Control 258
The ColorDialog Control 260
The Properties of ColorDialog 261
Using the ColorDialog Control 261
The PrintDialog Control 263
The Properties of PrintDialog 264
Using the PrintDialog Control 264
The PrintDocument Class 264
The Properties of the PrintDocument Class 265
Printing a Document 265

The FolderBrowserDialog Control 271
The Properties of FolderBrowserDialog 272
Using the FolderBrowserDialog Control 272
Summary 275
CHAPTER 9: CREATING MENUS 277
Understanding Menu Features 277
Images 278
Access Keys 278
Shortcut Keys 278
Check Marks 278
The Properties Window 279
Creating Menus 280
Designing the Menus 280
Adding Toolbars and Controls 282
Coding Menus 283
Coding the View Menu and Toolbars 287
Testing Your Code 288
Context Menus 290
Creating Context Menus 291
Enabling and Disabling Menu Items and Toolbar Buttons 294
Summary 297
XXII
www.it-ebooks.info
CONTENTS
CHAPTER 10: DEBUGGING AND ERROR HANDLING 299
Major Error Types 300
Syntax Errors 300
Execution Errors 303
Logic Errors 304
Debugging 305

Creating a Sample Project 305
Setting Breakpoints 321
Debugging Using the Watch Window and QuickWatch Dialog Box 327
Debugging with the Autos Window 330
Debugging with the Locals Window 330
Error Handling 331
Using Structured Error Handling 333
Summary 335
CHAPTER 11: BUILDING OBJECTS 339
Understanding Objects 339
Encapsulation 341
Methods and Properties 341
Events 341
Visibility 342
What Is a Class? 342
Building Classes 343
Reusability 344
Designing an Object 345
State 346
Behavior 346
Storing State 347
Real Properties 349
Read/Write Properties 352
The IsMoving Method 355
Constructors 357
Inheritance 359
Adding New Methods and Properties 360
Adding a GetPowerToWeightRatio Method 363
Changing Defaults 365
Polymorphism: Scary Word, Simple Concept 366

Overriding More Methods 367
XXIII
www.it-ebooks.info

×