Wrox Beginning Visual Basic 2005 4th Edition Nov 2005 ISBN 0764574019 pdf

  TEAM LinG Beginning Visual Basic ®

  2005 Beginning Visual Basic ®

  2005 Thearon Willis and Bryan Newsome

  Beginning Visual Basic®2005 Published by Wiley Publishing, Inc. 10475 Crosspoint Boulevard Indianapolis, IN 46256 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 10 9 8 7 6 5 4 3 2 1

  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.

  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.

  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

  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

  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

  2 Installing Visual Basic 2005

  22 Summary

  29

  28 Where Now?

  27 This Sounds like Java

  26 The .NET Vision

  25 MSN 1.0

  25 Microsoft’s Reliance on Windows

  23 Chapter 2: The Microsoft .NET Framework

  23 Exercise

  18 Using the Help System

  3 The Visual Basic 2005 IDE

  17 The Code Editor

  13 Modified Hungarian Notation

  1 Windows Versus DOS Programming

  9 Windows in the Visual Studio 2005 IDE

  8 Creating a Simple Application

  7 The Toolbars

  7 The Menu

  6 The Profile Setup Page

  10 The Toolbox Contents The .NET Framework Classes

  30 Executing Code

  55 Substrings

  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

  56 Formatting Strings

  45 Integer Math Shorthand

  57 Localized Formatting

  58 Replacing Substrings

  59 Using Dates

  60 Formatting Date Strings

  61 Extracting Date Properties

  62 Date Constants

  63 Defining Date Literals

  47 The Problem with Integer Math

  44 Common Integer Math Operations

  31 Common Language Runtime

  36 Chapter 3: Writing Software

  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

  37 Information and Data

  44 Working with Numbers

  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

  64

  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 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

  126 Using For Each . . . Next 128 Passing Arrays as Parameters 130 Sorting Arrays 133 Going Backwards 133 Initializing Arrays with Values 135

  125 Defining and Using Arrays

  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

  Understanding Enumerations 136

  Contents Using Hashtables

  Creating More Complex Applications 186

  The MessageBox Dialog Box 205

  Chapter 7: Displaying Dialog Boxes 205

  203 Exercise 2 203

  

Summary 203

Exercises 203

Exercise 1

  Help About 199

  Using Multiple Forms 199

  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

  Building the Form 178 Counting Characters 180 Counting Words 182 Creating the Show Me! Button Code 185

  161 Cleaning Up: Remove, RemoveAt, and Clear 164 Case Sensitivity

  Building a Simple Application 178

  Setting Up a Button Event 174

  

Chapter 6: Building Windows Applications 173

Responding to Events 173

  172 Exercise 2 172

  

Summary 171

Exercises 172

Exercise 1

  168 Using Preserve 170

  168 Dynamic Arrays

  167 Advanced Array Manipulation

  Available Icons for MessageBox 206 Available Buttons for MessageBox 207 Setting the Default Button 207 Miscellaneous Options 207 The Show Method Syntax 208 Contents Example Message Boxes

  209 The OpenDialog Control

  The FolderBrowserDialog Control 241

  Designing the Menus 250 Adding Toolbars and Controls 252 Coding Menus 254

  Creating Menus 250

  248 Access Keys 248 Shortcut Keys 248 Check Marks 248 The Properties Window 249

  247 Images

  247 Understanding Menu Features

  246 Exercise 2 246

  Summary 245 Exercises 246 Exercise 1

  How It Works 244

  The Properties of FolderBrowserDialog 242 Using the FolderBrowserDialog Control 242

  Printing a Document 234

  213 The OpenFileDialog Control

  The Properties of the PrintDocument Class 234

  The Properties of PrintDialog 233 Using the PrintDialog Control 234 The PrintDocument Class 234

  The PrintDialog Control 232

  The Properties of ColorDialog 230 Using the ColorDialog Control 231

  The ColorDialog Control 229

  The Properties of FontDialog 225 The Methods of FontDialog 226 Using the FontDialog Control 226

  The FontDialog Control 225

  The Properties of SaveFileDialog 220 The Methods of SaveFileDialog 221 Using the SaveFileDialog Control 221

  The SaveDialog Control 220

  213 The Properties of OpenFileDialog 214 The Methods of OpenFileDialog 215 Using the OpenFileDialog Control 216

Chapter 8: Creating Menus

  Contents Coding the View Menu and Toolbars

  

Summary 307

Exercises 308

Exercise 1

  State 316 Behavior 316 Storing State 317 Real Properties 319 Read/Write Properties 323 The IsMoving Method 325

  Designing an Object 315

  Building Classes 313

Reusability 314

  Encapsulation 311 Methods and Properties 311 Events 311 Visibility 312 What Is a Class? 313

  Understanding Objects 309

  Chapter 10: Building Objects 309

  308 Exercise 2 308

  Using Structured Error Handling 305

  259 Testing Your Code 260

  Error Handling 304

  277 Setting Breakpoints 293 Debugging Using the Watch Window 300 Debugging with the Locals Window 302

  Debugging 277 Creating a Sample Project

  Syntax Errors 272 Execution Errors 275 Logic Errors 275

  

Chapter 9: Debugging and Error Handling 271

Major Error Types 272

  

Summary 270

Exercise 270

  Creating Context Menus 263 Enabling and Disabling Menu Items and Toolbar Buttons 266

  Context Menus 262

  

Constructors 327 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

  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

  348 Using Classes 350 Scanning Favorites 355 Viewing Favorites 363

  Contents Chapter 12: Building Class Libraries

  

Chapter 13: Creating Your Own Custom Controls 399

Windows Forms Controls 400

  Raster Graphics 428

  Creating a Project with User Controls 428 How Drawing Programs Work 428

  

Chapter 14: Programming Custom Graphics 427

Building a Simple Paint Program 427

  

Summary 425

Exercise 426

  Building the Form Library Project Login Form 413 Testing the FormsLibrary 420 Hooking Up the Events 422

  Design Time or Run Time 411 Creating a Form Library 413

  Adding Properties 404 Exposing Methods from User Controls 405 Exposing Events from User Controls 406

  Exposing Properties from User Controls 404

  Creating and Testing a User Control 400

  398

  383 Understanding Class Libraries

  Viewing Classes with the Object Browser 397

Summary 398

Exercise

  Using InternetFavorites.dll 396

  Designing Class Libraries 395 Using Third-Party Class Libraries 396

  Gacutil Utility 393 Why Is My Assembly Not Visible in the References Dialog Box? 393

  Registering Assemblies 392

  390 Assembly Versions 392

  389 Signing Assemblies

  388 Using Strong Names

  384 Building a Class Library for Favorites Viewer 386 A Multitiered Application

  384 Creating a Class Library

  Vector Graphics 429 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 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

  475 What Is a Database?

  Contents

  The Find Method 506

  Web Applications: The Basic Pieces 552

  Windows Forms Advantages 551 Web Forms Advantages 551

  Thin-Client Architecture 550 Web Forms versus Windows Forms 551

  Chapter 17: Web Forms 549

  547 Exercise 2 547

  

Summary 546

Exercises 547

Exercise 1

  How It Works: FillDataSetAndView 525

  Binding Example 518

  BindingContext and CurrencyManager 516 Binding Controls 517

  Data Binding 515

  How It Works 511

  Examining a DataSet Example 507

  The ADO.NET Classes in Action 507

  The RowFilter Property 505

  

Chapter 16: Database Programming with SQL Server and ADO.NET 493

ADO.NET 494

  The Sort Property 505

  The DataSet Class 504 DataView 504

  502

  Using Command Builders to Create the Other Commands 502 The Fill Method

  The SelectCommand Property 500

  SqlDataAdapter 499

  The ExecuteNonQuery Method 499

  The Parameters Collection 498

  The CommandText Property 498

  The Connection Property 497

  SqlCommand 497

  497

  Working with the Connection String Parameters 495 Opening and Closing the Connection

  ADO.NET Data Namespaces 494 The SqlConnection Class 495

  Web Servers 552 Browsers 552 Contents HyperText Markup Language

  552

  Web Site Authentication 585

  The Address Book Project 615

  XML for Visual Basic Newcomers 614

  What Does XML Look Like? 612

  

Chapter 19: Visual Basic 2005 and XML 611

Understanding XML 611

  608 Exercise 2 609

  Summary 607 Exercises 608 Exercise 1

  Login Controls 595

  How It Works 594

  Windows Authentication 585 Forms Authentication 586 Web Site Administration Tool (WAT) 586

  Chapter 18: Forms Authentication 585

  VBScript and JavaScript 553 Cascading Style Sheets 553

  Summary 582 Exercise 583

  Using the GridView to Build a Data-Driven Web Form 575 Web Site Locations with VS 2005 580

  How It Works 571

  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

  Building Web Applications 555

  Development 554 Controls: The Toolbox 554

  Web.config 554

  Global.asax 554

  Benefits 553 Special Web Site Files 554

  Active Server Pages 553

  Creating the Project 615 The SerializableData Class 616 Loading the XML File 622

  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?

  650 SOAP 651

  Building a Web Service 653

  649 How Does a Web Service Work?

  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

  A Web Services Demonstration 654 Adding More Methods 656 Contents

  

Chapter 21: Deploying Your Application 687

What Is Deployment? 687

  Common Language Runtime 706 ActiveSync 706 Common in the Compact Framework 707 The Compact Framework Classes 708

  Offline Resources (Books) 727

  P2P.Wrox.com 726 Microsoft Resources 726 Other Resources 727

  Online Resources 726

  Appendix A: Where To Now? 725

  Exercise 723

  Building a Pocket PC Game 711 Summary 723

  

Chapter 22: Building Mobile Applications 705

Understanding the Environment 705

  ClickOnce Deployment 688

  Exercise 1 703 Exercise 2 704

  Summary 703 Exercises 703

  Private Assemblies 700 Shared Assemblies 701 Deploying Desktop Applications 702 Deploying Web Applications 702 Deploying XML Web Services 702 Useful Tools 702

  697 Deploying Different Solutions 700

  694 User Interface Editor

  Creating a Visual Studio 2005 Setup Application 693 Creating a Setup application

  XCOPY Deployment 693

  Professional VB .NET, 2nd Edition 727 ASP.NET 2.0 Beta Preview 728

  Contents

Appendix B: Implementing the Microsoft Solutions Framework 731

  735 Supply Application Documentation

  Appendix D: Solutions 745

  Secure Sockets Layer 742 Finding Answers 743

Summary 744

  741 Security Policy 741 Evidence 741

  740 Permissions

  

Appendix C: An Introduction to Security 739

Code Access Security (CAS)

  Managing Tradeoffs 736 Defining Success with the MSF 737

Summary 737

  The Testing Phase 735 The Deployment Phase 735

  735

  735 Completing the Code

  Software Development Life Cycle 732 Microsoft Solutions Framework 732

  Setup: Building Staging Areas for Development and Testing 734 Completing the Prototype

  The Planning Phase 734 The Developing Phase 734

  Risk Analysis 734

  Create a Scope Document 734

  Define Roles 733

  Goals 733

  Problem Statement 733

  The Envisioning Phase 733

  Index 771

  Acknowledgments

  This project was made possible by a number of people. First, thanks go out to Thearon for helping me get involved in a project like this. Thanks buddy. Next is everyone at Wiley Publishing, especially Sydney Jones, Katie Mohr, and Todd Meister. Without the help from you three, I would have been so lost and this book would not have been possible. Also, thanks to Annette Cloninger for helping me. And finally, thanks to my beautiful wife, Jennifer, for putting up with me while I put my life on hold for so many months to get this done (and some pretty late nights too).

  —Bryan Newsome

  Introduction

  Visual Basic 2005 is Microsoft’s latest version of the highly popular Visual Basic .NET programming lan- guage, one of the many languages supported in Visual Studio 2005. Visual Basic 2005’s strength lies in its ease of use and the speed at which you can create Windows applications, Web applications, mobile device applications, and Web Services.

  In this book, we will introduce you to programming with Visual Basic 2005 and show you how to create the types of applications and services mentioned above. Along the way you’ll also learn about object- oriented techniques and learn how to create your own business objects and Windows controls. Microsoft’s .NET Framework provides Visual Basic 2005 programmers with the ability to create full object oriented programs, just like the ones created using C# or C++. The .NET Framework provides a set of base classes that are common to all programming languages in Visual Studio 2005, which provides you with the same ability to create object-oriented programs as a programmer using C# or C++.

  This book will give you a thorough grounding in the basics of programming using Visual Basic 2005; from there the world is your oyster.

  Who Is This Book For?

  This book is designed to teach you how to write useful programs in Visual Basic 2005 as quickly and eas- ily as possible. There are two kinds of beginners for whom this book is ideal: ❑ You’re a beginner to programming and you’ve chosen Visual Basic 2005 as the place to start.

  That’s a great choice! Visual Basic 2005 is not only easy to learn; it’s also fun to use and very powerful. ❑ You can program in another language but you’re a beginner to .NET programming. Again, you’ve made a great choice! Whether you’ve come from Fortran or Visual Basic 6, you’ll find that this book quickly gets you up to speed on what you need to know to get the most from Visual Basic 2005.

  What Does This Book Cover?

  Visual Basic 2005 offers a great deal of functionality in both tools and language. No one book could ever cover Visual Basic 2005 in its entirety—you would need a library of books. What this book aims to do is to get you started as quickly and easily as possible. It shows you the roadmap, so to speak, of what there is and where to go. Once we’ve taught you the basics of creating working applications (creating the windows Introduction

  and controls, how your code should handle unexpected events, what object-oriented programming is, how to use it in your applications, and so on) we’ll show you some of the areas you might want to try your hand at next: Chapters 1 through 8 provide an introduction to Visual Studio 2005 and Windows programming.

  ❑ Chapter 9 provides an introduction to application debugging and error handling. ❑

  Chapters 10 through 12 provide an introduction to object-oriented programming and building ❑ objects.

  Chapters 13 and 14 provide an introduction to graphics in Windows applications. ❑

  Chapters 15 and 16 provide an introduction to programming with databases and covers Access, ❑ SQL Server, and ADO.NET.

  Chapter 17 provides an introduction to ASP.NET and shows you how to write applications for ❑ the Web.

  Chapter 19 provides a brief introduction to XML; a powerful tool for integrating your applica- ❑ tions with others—regardless of the language they were written in.

  Chapter 20 introduces you to Web Services; a technology whereby functionality offered on the ❑ Internet can be accessed by your applications and seamlessly integrated into them.

  Chapter 21 introduces you to building applications for mobile devices using the Compact ❑ Framework classes.

  What Do I Need to Run V isual Basic 2005?

  Apart from a willingness to learn, all you’ll need for the first 14 chapters are a PC running Windows 2000, Windows XP (Home or Professional Edition), or Windows Server 2003; Internet Explorer; and of course:

  Microsoft Visual Basic 2005 Express Edition ❑ or

  Microsoft Visual Basic 2005 Standard Edition ❑ or

  Microsoft Visual Basic 2005 Professional Edition ❑ or

  Microsoft Visual Basic 2005 Team System ❑

  As the later chapters cover more advanced subject areas, you will need other software to get the most out of them. Also, Visual Basic 2005 Express does not support creating Web applications, mobile applica- tions, and deployment projects:

  Introduction

  Chapter 15 requires Microsoft Access 2000. ❑

  For Chapter 16, you will need to have access to SQL Server 2000, SQL Server 2005, or SQL ❑ Server 2005 Express.

  Don’t worry if you don’t have these products already and want to wait a while before you purchase them. You should still find that you get a lot out of this book.

  Conventions

  We’ve used a number of different styles of text and layout in this book to help differentiate between the different kinds of information. Here are examples of the styles we use and an explanation of what they mean.

  Try It Out How Do They Work? 1. Each step has a number.

  2. Follow the steps through.

  3. Then read the subsequent “How It Works” to find out what’s going on.

  Background information, asides, and references appear in text like this.

  Bullets appear indented, with each new bullet marked like this. ❑

  Code has several styles. If it’s a word that we’re talking about in the text—for example, when discussing a . . . loop, it’s in . If it’s a block of code that can be typed as a program and run, it’s

  For Next this font

  also in a gray box:

  Private Sub btnAdd_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnAdd.Click Dim n As Integer n = 27 MessageBox.Show(n) End Sub

  Sometimes you’ll see code in a mixture of styles, like this:

  Private Sub btnAdd_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnAdd.Click Dim n As Integer n = 27 n = n + 2 MessageBox.Show(n)

  End Sub

  In cases like this, the code with a white background is code that Visual Studio 2005 has automatically generated (in a Try It Out) or code you are already familiar with (in a How It Works); the lines high- lighted in gray is a new addition to the code. Introduction Customer Suppor t

  We always value hearing from our readers, and we want to know what you think about this book: what you liked, what you didn’t like, and what you think we can do better next time. You can send us your comments by e-mail to feedback@wrox.com . Please be sure to mention the book title in your message.

  How to Download the Sample Code for the Book

  When you visit the Wrox site, www.wrox.com/ , simply locate the title through our Search facility or by using one of the title lists. Click Download in the Code column or Download Code on the book’s detail page. The files that are available for download from our site have been archived using WinZip. When you have saved the attachments to a folder on your hard drive, you need to extract the files using a decom- pression program such as WinZip, PKUnzip, or UltimateZip. When you extract the files, the code is usu- ally extracted into chapter folders. When you start the extraction process, ensure that your decompression software is set to use folder names.

  Errata

  We’ve made every effort to make sure that there are no errors in the text or in the code. However, no one is perfect, and mistakes do occur. If you find an error in one of our books, like a spelling mistake or a faulty piece of code, we would be very grateful to have your feedback. By sending in errata, you may save another reader from hours of frustration, and of course, you will be helping us provide even higher quality information. Simply e-mail the information to support@wrox.com ; your information will be checked and, if correct, posted to the errata page for that title or used in subsequent editions of the book.

  To find errata on the Web site, go to www.wrox.com/ , and simply locate the title through our Advanced Search or title list. Click the Book Errata link, which is below the cover graphic on the book’s detail page. If you wish to query a problem in the book directly with an expert who knows the book in detail, then e-mail support@wrox.com , with the title of the book and the last four numbers of the ISBN in the sub- ject field of the e-mail. A typical e-mail should include the following things:

  The title of the book, last four digits of the ISBN (4019), and page number of the problem in the ❑

  Subject field Your name, contact information, and the problem in the body of the message

  ❑ We won’t send you junk mail. We need the details to save your time and ours. When you send an e-mail message, it will go through the following chain of support:

  Customer Support—Your message is delivered to our customer support staff, who are the first

  ❑ people to read it. They have files on most frequently asked questions and will answer anything general about the book or the Web site immediately.

  Editorial—Deeper queries are forwarded to the technical editors responsible for that book. They

  ❑ have experience with the programming language or particular product and are able to answer detailed technical questions on the subject.

  Introduction The authors—Finally, in the unlikely event that the editor cannot answer your problem, they

  ❑ will forward the request to the author. We do try to protect the author from any distractions to their writing; however, we are quite happy to forward specific requests to them. All Wrox authors help with the support on their books. They will e-mail the customer and the editor with their response, and again all readers should benefit. The Wrox Support process can offer support only to issues that are directly pertinent to the content of our published title. Support for questions that fall outside the scope of normal book support is provided via the community lists at .

  http://p2p.wrox.com/forum p2p.wrox.com

  For author and peer discussions, join the P2P mailing lists. Our unique system provides programmer-to- programmer contact on mailing lists, forums, and newsgroups, all in addition to our one-to-one e-mail support system. If you post a query to P2P, you can be confident that it is being examined by many Wrox authors and other industry experts who are present on our mailing lists. At you will find

  p2p.wrox.com

  a number of different lists that will help you, not only while you read this book, but also as you develop your own applications. Particularly appropriate to this book are the and

  beginning_vb vb_dotnet lists.

  To subscribe to a mailing list just follow these steps: 1. Go to .

  http://p2p.wrox.com/ 2. Choose the appropriate category from the left menu bar.

  3. Click the mailing list you wish to join.

  4. Follow the instructions to subscribe and fill in your e-mail address and password.

  5. Reply to the confirmation e-mail you receive.

  6. Use the subscription manager to join more lists and set your e-mail preferences.

  Why This System Offers the Best Support

  You can choose to join the mailing lists, or you can receive them as a weekly digest. If you don’t have the time, or facility, to receive the mailing list, you can search our online archives. Junk mails and spam are deleted, and your own e-mail address is protected by the unique Lyris system. Queries about joining or leaving lists, and any other general queries about lists, should be sent to listsupport@p2p.wrox.com .

1 Welcome to V isual

  Basic 2005

  The goal of this book is to help you come up to speed with the Visual Basic 2005 language even if you have never programmed before. You will start slowly and build on what you learn. So take a deep breath, let it out slowly, and tell yourself you can do this. No sweat! No kidding! Programming a computer is a lot like teaching a child to tie his shoes. Until you find the correct way of giving the instructions, not much gets accomplished. Visual Basic 2005 is a language in which you can tell your computer how to do things. But, like a child, the computer will understand only if you explain things very clearly. If you have never programmed before, this sounds like an arduous task, and sometimes it is. However, Visual Basic 2005 gives you a simple language to explain some complex things. Although it never hurts to have an understanding of what is happening at the low- est levels, Visual Basic 2005 frees the programmer from having to deal with the mundane complexi- ties of writing Windows programs. You are free to concentrate on solving problems.

  Visual Basic 2005 helps you create solutions that run on the Microsoft Windows operating system. If you are looking at this book, you might have already felt the need or the desire to create such programs. Even if you have never written a computer program before, as you progress through the Try It Out exercises in this book, you will become familiar with the various aspects of the Visual Basic 2005 language, as well as its foundation in Microsoft’s .NET Framework. You will find that it is not nearly as difficult as you have been imagining. Before you know it, you will be feeling quite comfortable creating a variety of different types of programs with Visual Basic 2005. Also (as the name .NET implies) Visual Basic 2005 can be used to create applications for use over the Internet. You can also create mobile applications for Pocket PCs and SmartPhones. However, when learning any new technology, you have to walk before you can run, so in this book you will begin by focusing on Windows applications before extending your boundaries to other platforms.

  In this chapter, we will cover the following subjects: The installation of Visual Basic 2005

  ❑ A tour of the Visual Basic 2005 Integrated Development Environment (IDE)

  ❑ How to create a simple Windows program ❑

  How to use and leverage the integrated help system ❑

  Windows Versus DOS Programming

  A Windows program is quite different from its ancient relative, the MS-DOS program. A DOS program follows a relatively strict path from beginning to end. Although this does not necessarily limit the func- tionality of the program, it does limit the road the user has to take to get to it. A DOS program is like walking down a hallway; to get to the end you have to walk down the hallway, passing any obstacles that you may encounter. A DOS program would only let you open certain doors along your stroll. Windows, on the other hand, opened up the world of event-driven programming. Events in this context include, for example, clicking a button, resizing a window, or changing an entry in a text box. The code that you write responds to these events. To go back to the hallway analogy: In a Windows program, to get to the end of the hall, you just click on the end of the hall. The hallway can be ignored. If you get to the end and realize that is not where you wanted to be, you can just set off for the new destination with- out returning to your starting point. The program reacts to your movements and takes the necessary actions to complete your desired tasks (Visual Basic 2005). Another big advantage in a Windows program is the abstraction of the hardware; which means that Windows takes care of communicating with the hardware for you. You do not need to know the inner workings of every laser printer on the market just to create output. You do not need to study the schematics for graphics cards to write your game. Windows wraps up this functionality by providing generic routines that commu- nicate with the drivers written by hardware manufacturers. This is probably the main reason that Windows has been so successful. The generic routines are referred to as the Windows Application Programming

  Interface (API).

  Before Visual Basic 1.0 was introduced to the world in 1991, developers had to be well versed in C and C++ programming, as well as the building blocks of the Windows system itself, the Windows API. This complexity meant that only dedicated and properly trained individuals were capable of turning out soft- ware that could run on Windows. Visual Basic changed all of that, and it has been estimated that there are now as many lines of production code written in Visual Basic as in any other language.

  Visual Basic changed the face of Windows programming by removing the complex burden of writing code for the user interface (UI). By allowing programmers to draw their own UI, it freed them to concen- trate on the business problems they were trying to solve. Once the UI is drawn, the programmer can then add the code to react to events.

  Visual Basic has also been extensible from the very beginning. Third-party vendors quickly saw the mar- ket for reusable modules to aid developers. These modules, or controls, were originally referred to as