Wrox Beginning Microsoft Visual Basic 2008 May 2008 ISBN 0470191341 pdf

  

Beginning

® ®

  

Microsoft Visual Basic 2008

Acknowledgments .........................................................................................xi

Introduction ....................................................................................................... xxvii

  

Chapter 1: Welcome to Visual Basic 2008 ...................................................... 1

Chapter 2: The Microsoft .NET Framework .................................................... 25 Chapter 3: Writing Software ......................................................................... 37 Chapter 4: Controlling the Flow .................................................................... 87 Chapter 5: Working with Data Structures ................................................... 133 Chapter 6: Extensible Application Markup Language (XAML) ...................... 185 Chapter 7: Building Windows Applications .................................................. 211 Chapter 8: Displaying Dialog Boxes ............................................................ 257 Chapter 9: Creating Menus ........................................................................ 301 Chapter 10: Debugging and Error Handling ................................................. 325 Chapter 11: Building Objects ..................................................................... 363 Chapter 12: Advanced Object-Oriented Techniques ..................................... 403 Chapter 13: Building Class Libraries ........................................................... 439 Chapter 14: Creating Windows Forms User Controls ................................... 457 Chapter 15: Programming Custom Graphics ............................................... 485 Chapter 16: Accessing Databases.............................................................. 535 Chapter 17: Database Programming with SQL Server and ADO.NET ............. 555 Chapter 18: ASP.NET ................................................................................. 617 Chapter 19: Web Projects .......................................................................... 653 Chapter 20: Visual Basic 2008 and XML .................................................... 677 Chapter 21: Distributed Computing with Windows Communication Foundation ..................................................... 717 Chapter 22: Building a Sequential Workflow Using the Windows Workflow Foundation .............................................................. 737

Chapter 23: Building Mobile Applications ................................................... 755

Chapter 24: Deploying Your Application ...................................................... 775 Chapter 25: Where to Now? ....................................................................... 793 (Continued)

  

Appendix A: Exercise Solutions .................................................................. 797

Appendix B: Using the Microsoft Solutions Framework ................................ 827

Appendix C: An Introduction to Code Security and SSL ............................... 835

Appendix D: An Introduction to Windows CardSpace ................................... 841

Appendix E: .NET Framework Differences .................................................... 849

Index ........................................................................................................ 853

  

Beginning

Microsoft

  ® Visual Basic

  ® 2008

  

Thearon Willis

and

Bryan Newsome

Wiley Publishing, Inc. Published by Wiley Publishing, Inc. 10475 Crosspoint Boulevard Indianapolis, IN 46256 Copyright © 2008 by Wiley Publishing, Inc., Indianapolis, Indiana Published simultaneously in Canada

  ISBN: 978-0-470-19134-7 Manufactured in the United States of America 10 9 8 7 6 5 4 3 2 1

  Library of Congress Cataloging-in-Publication Data Willis, Thearon.

  Beginning Microsoft Visual basic 2008 / Thearon Willis and Bryan Newsome. p. cm. Includes index.

  ISBN 978-0-470-19134-7 (paper/website)

  1. Microsoft Visual BASIC 2. BASIC (Computer program language) I. Newsome, Bryan, 1971- II. Title. QA76.73.B3W45556 2008 005.2'762—dc22

  2008004982 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 representations or warranties with respect to the accuracy or completeness of the contents of this work and specifically disclaim all war- ranties, including without limitation warranties of fitness for a particular purpose. No warranty may be cre- ated 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 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, 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.

   For my daughter, Stephanie, my most precious gift from God.

   For Wendy, my love and friend in Christ.

   Thearon To Jennifer and Katelyn. Love, Bryan

  About the Authors

  Thearon Willis currently works as a senior developer and builds Windows applications and add - ins for Microsoft Office products using Microsoft Visual Basic 2008. Over the years, Thearon has worked on a variety of systems from mainframe to client - server development.

  Bryan Newsome works as a director for a custom software solutions company specializing in Microsoft applications. 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.

  Acquisitions Editor Katie Mohr Development Editors Sara Shlaer Sydney Jones Technical Editor Mark Lavoie Production Editor Kathryn Duggan Copy Editor Travis Henderson Editorial Manager Mary Beth Wakefield

  Production Manager Tim Tate Vice President and Executive Group Publisher Richard Swadley Vice President and Executive Publisher Joseph B. Wikert Project Coordinator, Cover Lynsey Stanford Proofreader Jeremy Bagai, Word One New York Editing & Proofreading Indexer Johnna VanHoose Dinse

  Credits

  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 Katie Mohr for giving me the opportunity to write this book and Sara Shlaer and Sydney Jones for their hard work in editing. Also thanks to all the other 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 So many people put so much effort into publishing this work. Thank you all; this would not be possible without your hard work and dedication. Special thanks to Katie Mohr, Sara Shlaer, Sydney Jones, and Mark Lavoie for making my work readable and technically sound. It was a pleasure to work with you all over the past months. Thank you Thearon; you were a terrific mentor for me and the reason I ever had the opportunity to write.

  — Bryan

  Contents Acknowledgments xi Introduction xxvii

Chapter 1: Welcome to Visual Basic 2008

  2 Installing Visual Basic 2008

  27 This Sounds like Java

  35

  35 Summary

  34 The Common Type System and Common Language Specification

  34 Exception Handling

  33 Interoperation

  33 Security

  33 Application Isolation

  32 Code Loading and Execution

  31 Common Language Runtime

  30 Executing Code

  29 The .NET Framework Classes

  29 Writing Software for Windows

  28 Where Now?

  26 The .NET Vision

  3 The Visual Basic 2008 IDE

  1 Event-Driven Programming

  25 Microsoft’s Reliance on Windows

  24 Chapter 2: The Microsoft .NET Framework

  24 Exercise

  23 Summary

  19 Using the Help System

  18 The Code Editor

  14 Modified Hungarian Notation

  10 The Toolbox

  9 Creating a Simple Application

  8 The Toolbars

  7 The Menu

  7 The Profile Setup Page

  25 MSN 1.0

Chapter 3: Writing Software

  85 Chapter 4: Controlling the Flow

  74 Methods You’ve Already Seen

  75 Building a Method

  78 Choosing Method Names

  81 Scope

  82 Summary

  84 Exercises

  87 Making Decisions

  72 Methods

  87 The If Statement

  88 The Else Statement

  90 Allowing Multiple Alternatives with ElseIf

  91 Nested If Statements

  92 Single-Line If Statement

  92 Comparison Operators

  93 String Comparison 103

  73 Why Use Methods?

  37 Information and Data

  37 Algorithms

  44 Working with Numbers

  38 What Is a Programming Language?

  39 Working with Variables

  39 Comments and Whitespace

  42 Comments

  42 Whitespace

  44 Data Types

  45 Common Integer Math Operations

  70 Representing Values

  45 Integer Math Shorthand

  48 Working with Strings

  52 Using Dates

  61 Boolean

  68 Storing Variables

  69 Binary

  69 Bits and Bytes

  70 Converting Values Select Case 105

  Case-Insensitive Select Case 108 Multiple Selections 112 The Case Else Statement 113 Different Data Types with Select Case 114

  Loops 114

  The For . . . Next Loop 115 The For Each . . . Next Loop 120 The Do . . . Loop Loops 121 Nested Loops 127 Quitting Early 128 Infinite Loops 131

  Summary 132 Exercises 132

Chapter 5: Working with Data Structures 133 Understanding Arrays

  134 Using For Each . . . Next 137 Passing Arrays as Parameters 139 Sorting Arrays 142 Going Backwards 143 Initializing Arrays with Values 144

  Understanding Enumerations 145

  Using Enumerations 145 Determining the State 150 Setting Invalid Values 152

  133 Defining and Using Arrays

  Using Constants 153 Different Constant Types 155

  Structures 155 Building Structures

  156 Adding Properties to Structures 159

  Working with ArrayLists 160

  Using an ArrayList 160 Deleting from an ArrayList 164 Showing Items in the ArrayList 167

  Working with Collections 168

  Creating CustomerCollection 169 Adding an Item Property 170

  Understanding Constants 153 Building Lookup Tables with Hashtable 172

  Using Hashtables 172 Cleaning Up: Remove, RemoveAt, and Clear 176

  Setting Up a Button Event 212

  The About Dialog Box 251

  Using Multiple Forms 251

  The Text Editor Project 232 Creating the Toolbar 233 Creating the Status Bar 238 Creating an Edit Box 240 Clearing the Edit Box 242 Responding to Toolbar Buttons 244

  Creating More Complex Applications 232

  Building the Form 219 Counting Characters 223 Counting Words 226

  Building a Simple Application 219

  

Chapter 7: Building Windows Applications 211

Responding to Events 211

  Case Sensitivity 178

  Summary 209 Exercise 209

  Creating a Rich WPF User Interface 191 Using WPF Common Controls 197 Wiring Up Events 205

  XAML Syntax 187 Windows Presentation Foundation 190

  

Chapter 6: Extensible Application Markup Language (XAML) 185

What Is XAML? 185

  Summary 183 Exercises 184

  Dynamic Arrays 180 Using Preserve 182

  Advanced Array Manipulation 180

  Summary 255 Exercises 255

  Chapter 8: Displaying Dialog Boxes 257

  The Properties of ColorDialog 283 Using the ColorDialog Control 284

  301 Images

  301 Understanding Menu Features

  Summary 298 Exercises 299 Chapter 9: Creating Menus

  The Properties of FolderBrowserDialog 295 Using the FolderBrowserDialog Control 295

  The FolderBrowserDialog Control 294

  The Properties of PrintDialog 286 Using the PrintDialog Control 286 The PrintDocument Class 287 Printing a Document 287

  The PrintDialog Control 285

  The ColorDialog Control 282

  The MessageBox Dialog Box 257

  The Properties of FontDialog 278 The Methods of FontDialog 279 Using the FontDialog Control 279

  The FontDialog Control 278

  The Properties of SaveFileDialog 273 The Methods of SaveFileDialog 274 Using the SaveFileDialog Control 274

  The SaveDialog Control 273

  The OpenFileDialog Control 265 The Properties of OpenFileDialog 266 The Methods of OpenFileDialog 267 Using the OpenFileDialog Control 268

  The OpenDialog Control 265

  Available Icons for MessageBox 258 Available Buttons for MessageBox 259 Setting the Default Button 259 Miscellaneous Options 260 The Show Method Syntax 260 Example Message Boxes 262

  302 Access Keys 302 Shortcut Keys 302 Check Marks 302 The Properties Window 303

  Creating Menus 304

  Designing the Menus 304 Adding Toolbars and Controls 306 Coding Menus 308 Coding the View Menu and Toolbars 312 Testing Your Code 314

  Context Menus 316

  Creating Context Menus 317 Enabling and Disabling Menu Items and Toolbar Buttons 320

  Summary 324 Exercise 324

  

Chapter 10: Debugging and Error Handling 325

Major Error Types 326

  Syntax Errors 326 Execution Errors 329 Logic Errors 329

  Debugging 331 Creating a Sample Project

  331 Setting Breakpoints 347 Debugging Using the Watch Window 354 Debugging with the Locals Window 356

  Error Handling 358

  Using Structured Error Handling 359

  Summary 361 Exercises 362 Chapter 11: Building Objects

  363 Understanding Objects

  363 Encapsulation

  365 Methods and Properties 365 Events 365 Visibility 366 What Is a Class? 367

  Building Classes 367 Reusability 368

  Designing an Object 369

  State 370 Behavior 370 Storing State 371 Real Properties 374 Read/Write Properties 377 The IsMoving Method 380

  Constructors 382 Inheritance 384 Adding New Methods and Properties

  385 Adding a GetPowerToWeightRatio Method 387 Changing Defaults 389 Polymorphism: Scary Word, Simple Concept 391

  Overriding More Methods 392 Inheriting from the Object Class 394

  Objects and Structures 395 The Framework Classes 396

  Namespaces 396 The Imports Statement 398 Creating Your Own Namespace 399 Inheritance in the .NET Framework 401

  Summary 402 Exercises 402

Chapter 12: Advanced Object-Oriented Techniques 403 Building a Favorites Viewer

  403 Internet Shortcuts and Favorites

  An Alternative Favorite Viewer 422

  Building a Favorites Tray 422 Displaying Favorites 424

  Using Shared Properties and Methods 428

  Using Shared Procedures 428 Using Shared Methods 433

  Understanding Object-Oriented Programming and Memory Management 434 Garbage Collection

  435 Releasing Resources 436 Defragmentation and Compaction 437

  Summary 438 Exercise 438

  404 Using Classes 407 Scanning Favorites 413 Viewing Favorites 420 Chapter 13: Building Class Libraries 439

  Understanding Class Libraries 440

  

Chapter 14: Creating Windows Forms User Controls 457

Windows Forms Controls 458 Creating and Testing a User Control 458 Exposing Properties from User Controls 462

  Creating a Project with User Controls 486 How Drawing Programs Work 486 The GraphicsItem Class 488 Screen and Client Coordinates 490 Listening to the Mouse and Drawing GraphicsCircle Objects 491

  

Chapter 15: Programming Custom Graphics 485

Building a Simple Paint Program 485

  Summary 484 Exercise 484

  Building the Command Link Control 473 Using the Command Link Control 481

  Design Time or RunTime 470 Creating a Command Link Control 472

  Adding Properties 462 Exposing Methods from User Controls 464 Exposing Events from User Controls 465

  Summary 455 Exercise 455

  Creating a Class Library 440 Building a Class Library for Favorites Viewer 442

  Designing Class Libraries 452 Using Third-Party Class Libraries 453 Viewing Classes with the Object Browser 454

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

  Registering Assemblies 449

  Signing Assemblies 447 Assembly Versions 449

  Using Strong Names 446

  A Multitiered Application 445

  Invalidation 496

  Optimized Drawing 497 Choosing Colors 498 Responding to Clicks 504

  The SQL SELECT Statement 537 Queries in Access 539 Creating a Customer Query 539 Data Access Components 543

  ADO.NET Data Namespaces 557 The SqlConnection Class 558 SqlCommand 560 SqlDataAdapter 562

  

Chapter 17: Database Programming with SQL Server and ADO.NET 555

ADO.NET 556

  Exercises 553

  Data Binding 546 Summary 552

  TableAdapter 545

  DataSet 544 DataGridView 544 BindingSource 545 BindingNavigator 545

  Microsoft Access Objects 536 Tables 536 Queries 536

  Dealing with Two Colors 507

  What Is a Database? 535

  Chapter 16: Accessing Databases 535

  More Graphics Methods 533 Summary 533

  Drawing Images 526 Scaling Images 528 Preserving the Aspect Ratio 530

  Working with Images 525

  Indicating the Assigned Buttons 509 Using Advanced Colors 516 Using Different Tools 520 Implementing Hollow Circle 521

  The DataSet Class 566 DataView 567 The ADO.NET Classes in Action 570

  Examining a DataSet Example 570

  VBScript and JavaScript 621 Cascading Style Sheets 621

  653 Windows Authentication

  653 Web Site Authentication

  Summary 651 Exercises 651 Chapter 19: Web Projects

  Creating a Web Form for Client- and Server-Side Processing 623 Web Site Locations with VS 2008 628 Performing Data Entry and Validation 630 Designing the Site’s Look and Feel 635 Using the GridView to Build a Data-Driven Web Form 645

  Building Web Applications 623

  Benefits of ASP.NET Web Pages 622 Special Web Site Files 622 Development 622 Controls: The Toolbox 623

  Active Server Pages 621

  Web Servers 620 Browsers 620 HyperText Markup Language 620

  Data Binding 578

  Web Applications: The Basic Pieces 620

  Windows Forms Advantages 619 Web Forms Advantages 619

  Thin-Client Architecture 618 Web Forms versus Windows Forms 619

  Chapter 18: ASP.NET 617

  Exercises 615

  LINQ to SQL 610 Summary 614

  BindingContext and CurrencyManager 579 Binding Controls 580

  654 Forms Authentication 654 Web Site Administration Tool (WAT) 654 Login Controls 662

  Summary 675 Exercises 675

  

Chapter 20: Visual Basic 2008 and XML 677

Understanding XML 677

  What Does XML Look Like? 678

  XML for Visual Basic Newcomers 680

  The Address Book Project 681

  Creating the Project 681 The SerializableData Class 682 Loading the XML File 688 Changing the Data 691 Sending E-mail 692 Creating a List of Addresses 694 Ignoring Members 698 Loading Addresses 701 Adding New Addresses 702 Navigating Addresses 704 Deleting Addresses 705

  Integrating with the Address Book Application 707 Demonstrating the Principle of Integration

  708 Reading the Address Book from Another Application 709 Summary 714 Exercises 715

  Chapter 21: Distributed Computing with Windows Communication Foundation 717 What Is a Web Service? 717

  How Does a Web Service Work? 718 SOAP 719

  Building a Web Service 721

  A Web Services Demonstration 721 Adding More Methods 724

  Understanding WCF Services 726

  WCF services 726

  Summary 735 Exercises 735 Chapter 22: Building a Sequential Workflow Using the Windows Workflow Foundation 737

  Visual Studio Workflow Templates 739 Workflow Foundation Components 740 Sequential Workflow Activities 740 Creating a Sequential Worklow 741 Property Tax Listing Form Workflow 744 Summary 753

  Exercises 753

  

Chapter 23: Building Mobile Applications 755

Understanding the Environment 755

  Common Language Runtime 756 ActiveSync and Windows Mobile Device Center 756

  Common Types in the Compact Framework 758 The Compact Framework Classes 759

  Building a Pocket PC Game 761 Summary 773

  Exercise 773

  

Chapter 24: Deploying Your Application 775

What Is Deployment? 775

  ClickOnce Deployment 776

  XCOPY Deployment 781

  Creating a Visual Studio 2008 Setup Application 781 User Interface Editor 785 Deploying Different Solutions 788

  Private Assemblies 789 Shared Assemblies 789 Deploying Desktop Applications 790 Deploying Web Applications 790 Deploying XML Web Services 790 Useful Tools 791

  Summary 791 Exercises 792

Chapter 25: Where to Now?

  793 Online Resources

  794 P2P.Wrox.com

  794 Microsoft Resources 794 Other Resources 795

  Offline Resources (Books) 795

  Professional Visual Basic 2008 795 Visual Basic 2008 Programmer’s Reference 796

  Appendix A: Exercise Solutions 797

Appendix B: Using the Microsoft Solutions Framework 827

  

Appendix C: An Introduction to Code Security and SSL 835

Appendix D: An Introduction to Windows CardSpace 841

Appendix E: .NET Framework Differences 849

Index 853

  Introduction

  Visual Basic 2008 is Microsoft ’ s latest version of the highly popular Visual Basic .NET programming language, one of the many languages supported in Visual Studio 2008. Visual Basic 2008 ’ s strength lies in its ease of use and the speed at which you can create Windows Forms applications, WPF Windows applications, web applications, WPF Browser applications, mobile device applications, and web services.

  In this book, we introduce you to programming with Visual Basic 2008 and show you how to create these types of applications and services. Along the way you ’ ll also learn about object - oriented techniques and learn how to create your own business objects and Windows controls. Microsoft .NET Framework provides Visual Basic 2008 programmers with the capability 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 2008, which provides you with the same capability 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 2008; 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 2008 as quickly and easily 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 2008 as the place to start.

  That ’ s a great choice! Visual Basic 2008 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 2008.

  What Does This Book Cover?

  Visual Basic 2008 offers a great deal of functionality in both tools and language. No one book could ever cover Visual Basic 2008 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 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. To this end, the book is organized as follows: Chapters 1 through 9 provide an introduction to Visual Studio 2008 and Windows

  ❑ programming.

  Chapter 6 provides an introduction to XAML and Windows Presentation Foundation (WPF) ❑ programming.

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

  Chapters 11 through 13 provide an introduction to object - oriented programming and ❑ building objects.

  Chapter 14 provides an introduction to creating Windows Forms user controls. ❑ Chapter 15 provides an introduction to graphics in Windows applications.

  ❑ Chapters 16 and 17 provide an introduction to programming with databases and covers Access,

  ❑ SQL Server, ADO.NET and LINQ.

  Chapters 18 and 19 provide an introduction to ASP.NET and show you how to write ❑ applications for the Web.

  Chapter 20 provides a brief introduction to XML, a powerful tool for integrating your ❑ applications — regardless of the language they were written in.

  Chapter 21 introduces you to web services and the Windows Communication ❑ Foundation (WCF).

  Chapter 22 introduces you to sequential workflows using the Windows Workflow ❑ Foundation (WF).

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

  Chapter 24 introduces you to deploying applications using ClickOnce technology. ❑

  Chapter 25 provides some insight on where to go next in your journey to learn about ❑ Visual Basic 2008.

  Appendix A provides the answers to chapter exercises. ❑ Appendix B introduces the Microsoft Solution Framework.

  ❑ Appendix C provides some background on security. ❑ Appendix D provides insight into Windows CardSpace. ❑ Appendix E compares the differences between the latest versions of the .NET Framework. ❑

  What Do I Need to Run V isual Basic 2008?

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

  ❑ Microsoft Visual Basic 2008 Express ❑ Microsoft Visual Basic 2008 Profession Edition ❑ Microsoft Visual Basic 2008 Team System

  As the later chapters cover more advanced subject areas, you will need other software to get the most out of them. Also note that Visual Basic 2008 Express does not support creating web applications, mobile applications, or deployment projects.

  ❑

  Chapter 14 requires Microsoft Visual Basic 2008 Professional Edition or above in order to create Windows Forms User Controls. ❑ Chapter 16 requires Microsoft Access 2000. ❑ For Chapter 17 , you will need to have access to SQL Server 2005, SQL Server 2005 Express Edition, or SQL Server 2008.

  Don ’ t worry if you don ’ t have these products yet 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 used and an explanation of what they mean.

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

2. Follow the steps in sequence.

  How It Works

  If there ’ s more that you need to understand about what ’ s going on as you complete the steps, you will find a subsequent “ How It Works ” section that explains what ’ s going on behind the scenes.

   Background information, asides, and references appear in text 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

  For ... Next this font

  and run, it looks 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 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 2008 has automatically generated (in a Try It Out) or code you are already familiar with (in a How It Works); the lines highlighted in gray show a change or a new addition to the code.

  Source Code

  As you work through the examples in this book, you may choose either to type in all the code manually or to use the source code files that accompany the book. All of the source code used in this book is available for download at . When at the site, locate the book ’ s title (either by using the

  www.wrox.com

  Search box or by using one of the title lists) and click the Download Code link on the book ’ s detail page to obtain all the source code for the book.

  

Because many books have similar titles, you may find it easiest to search by ISBN; this book ’ s ISBN is

978 - 0 - 470 - 19134 - 7.

  After you have downloaded the code, decompress it with your favorite compression tool. Alternately, you can go to the main Wrox code download page at

  www.wrox.com/dynamic/books/download.aspx to see the code available for this book and all other Wrox books.

  Errata

  We make every effort to ensure 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 faulty piece of code, we would be very grateful for your feedback. By sending in errata you may save another reader hours of frustration and at the same time you will be helping us provide even higher quality information.

  To find the errata page for this book, go to and locate the title using the Search box or

  

www.wrox.com

  one of the title lists. Then, on the book details page, click the Book Errata link. On this page you can view all errata that have been submitted for this book and posted by Wrox editors. A complete book list including links to each book ’ s errata is also available at .

  www.wrox.com/misc-pages/booklist.shtml

  If you don ’ t spot your error on the Book Errata page, go to

  www.wrox.com/contact/techsupport

  and complete the form there to send us the error you have found. We ’ ll check the information

  .shtml

  and, if appropriate, post a message to the book ’ s errata page and fix the problem in subsequent editions of the book.

  p2p.wrox.com

  For author and peer discussion, join the P2P forums at . The forums are a web - based

  p2p.wrox.com

  system for you to post messages relating to Wrox books and related technologies and interact with other readers and technology users. The forums offer a subscription feature to e - mail you topics of interest of your choosing when new posts are made to the forums. Wrox authors, editors, other industry experts, and your fellow readers are present on these forums.

  At you will find a number of different forums that will help you not only as you read

  p2p.wrox.com

  this book, but also as you develop your own applications. To join the forums, just follow these steps: Go to and click the Register link.

  1. p2p.wrox.com Read the terms of use and click Agree.

2. Complete the required information to join as well as any optional information you wish to 3.

  provide and click Submit. You will receive an e - mail with information describing how to verify your account and complete 4. the joining process.

  

You can read messages in the forums without joining P2P but in order to post your own messages, you

must join.

  After you ’ ve joined, you can post new messages and respond to messages other users post. You can read messages at any time on the Web. If you would like to have new messages from a particular forum e - mailed to you, click the Subscribe to this Forum icon by the forum name in the forum listing. For more information about how to use the Wrox P2P, be sure to read the P2P FAQs for answers to questions about how the forum software works as well as many common questions specific to P2P and Wrox books. To read the FAQs, click the FAQ link on any P2P page.

1 Welcome to

  

V isual Basic 2008

  This is an exciting time to enter the world of programming with Visual Basic 2008 and Windows Vista. Windows Vista represents the first Windows operating system upgrade since Windows XP was first released in 2002. A lot has changed in the Windows user interface and Visual Basic 2008 makes it easy to write professional - looking Windows applications as well as web applications and web services. Haven ’ t upgraded to Windows Vista yet? No worries, Visual Basic 2008 also allows you to write professional - looking applications for Windows XP as well.

  The goal of this book is to help you use the Visual Basic 2008 programming language, even if you have never programmed before. You will start slowly and build on what you have learned in subsequent chapters. 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 is accomplished. Visual Basic 2008 is a language you can use to 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 can be. However, Visual Basic 2008 gives you an easy - to - use language to explain some complex tasks. Although it never hurts to have an understanding of what is happening at the lowest levels, Visual Basic 2008 frees the programmer from having to deal with the mundane complexities of writing Windows applications. You are free to concentrate on solving real problems. Visual Basic 2008 helps you create solutions that run on the Microsoft Windows operating systems, such as Windows Vista, Windows Server 2008, and Windows Mobile 6. If you are looking at this book, you might have already felt the need or 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 2008 language, as well as its foundations in the Microsoft .NET Framework. You will find that it is not nearly as difficult as you had imagined. Before you know it, you will feel quite comfortable creating a variety of different types of programs with Visual Basic 2008. Visual Basic 2008 can also be used to create web applications and web services as well as mobile applications that can run on Pocket PCs or SmartPhones. However, you will begin by focusing on Windows applications before extending your boundaries to other platforms. This chapter covers the following topics:

  ❑ Event - driven programming

  ❑ The installation of Visual Basic 2008

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

  How to create a simple Windows program ❑

  How to use the integrated Help system

  Event - Driven Programming

  A Windows program is quite different from yesteryear ’ s MS - DOS program. A DOS program follows a relatively strict path from beginning to end. Although this does not necessarily limit the functionality 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 clicking a button, resizing a window, or changing an entry in a text box. The code that you write responds to these events. In terms of the hallway analogy: In a Windows program, to get to the end of the hall, you just click 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 without returning to your starting point. The program reacts to your movements and takes the necessary actions to complete your desired tasks. 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 communicate 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), and the classes in the .NET Framework take care of communicating with those APIs.

  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 software 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 concentrate on the business problems they were trying to solve. When 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 market for reusable modules to aid developers. These modules, or controls , were originally referred to as

  VBXs (named after their file extension). Prior to Visual Basic 5.0, if you did not like the way a button behaved, you could either buy or create your own, but those controls had to be written in C or C++. Database access utilities were some of the first controls available. Version 5 of Visual Basic introduced the concept of ActiveX , which allowed developers to create their own ActiveX controls .

  When Microsoft introduced Visual Basic 3.0, the programming world changed significantly. Now you could build database applications directly accessible to users (so - called front - end applications ) completely with Visual Basic. There was no need to rely on third - party controls. Microsoft accomplished this task with the introduction of Data Access Objects (DAO), which allowed programmers to manipulate data with the same ease as manipulating the user interface. Versions 4.0 and 5.0 extended the capabilities of Version 3.0 to allow developers to target the new Windows 95 platform. They also made it easier for developers to write code, which could then be manipulated to make it usable to other language developers. Version 6.0 provided a new way to access databases with the integration of ActiveX Data Objects (ADO). The ADO feature was developed by Microsoft to aid web developers using Active Server Pages (ASP) to access databases. All of the improvements to Visual Basic over the years have ensured its dominant place in the programming world — it helps developers write robust and maintainable applications in record time. With the release of Visual Basic .NET in February 2002, most of the restrictions that used to exist have been obliterated. In the past, Visual Basic was criticized and maligned as a “ toy ” language, because it did not provide all of the features of more sophisticated languages such as C++ and Java. Now, Microsoft has removed these restrictions and made Visual Basic .NET a very powerful development tool. This trend has continued with the release of Visual Basic 2003, Visual Basic 2005, and the latest release, Visual Basic 2008. Each new release of the Visual Basic .NET programming language brings about many new trends, features, and improvements, making it a great choice for programmers of all levels.

  Installing V isual Basic 2008

  You may own Visual Basic 2008 in one of the following forms: As part of Visual Studio 2008, a suite of tools and languages that also includes C# (pronounced

  ❑ C - sharp ) and Visual C++. The Visual Studio 2008 product line includes Visual Studio Professional Edition or Visual Studio Tools Team Editions. The Team Edition versions come with progressively more tools for building and managing the development of larger, enterprise - wide applications.

  As Visual Basic 2008 Express Edition, which includes the Visual Basic 2008 language, and a ❑ reduced set of the tools and features that are available with Visual Studio 2008.