1. Trang chủ
  2. » Công Nghệ Thông Tin

Mastering Microsoft Visual Basic 2008 phần 1 ppt

116 321 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 116
Dung lượng 2,08 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Visual Basic has evolved from a small, limited programming environment to a first-class development tool for building all types of Windows and Web applications, from small hobbyist proje

Trang 4

Mastering Microsoft

Visual Basic 2008

Trang 7

Acquisitions Editor: Thomas Cirtin

Development Editor: Toni Zaccarini Ackley

Technical Editor: John Mueller

Production Editor: Daniel Scribner

Copy Editor: Sharon Wilkey

Production Manager: Tim Tate

Vice President and Executive Group Publisher: Richard Swadley

Vice President and Executive Publisher: Joseph B Wikert

Vice President and Publisher: Neil Edde

Book Designer: Maureen Forys and Judy Fung

Proofreader: Nancy Riddiough

Indexer: Ron Strauss

Cover Designer: Ryan Sneed

Cover Image: Pete Gardner / Digital Vision / Getty Images

Copyright © 2008 by Wiley Publishing, Inc., Indianapolis, Indiana

Published simultaneously in Canada

ISBN: 978-0-4701-8742-5

No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic,

mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States

Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate

per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750–8400, fax (978) 646–8600.

Requests to the Publisher for permission should be addressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint

Blvd., Indianapolis, IN 46256, (317) 572–3447, fax (317) 572–4355, or online at http://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 warranties, including without limitation

warranties of fitness for a particular purpose No warranty may be created or extended by sales or promotional materials The advice

and strategies contained herein may not be suitable for every situation This work is sold with the understanding that the publisher

is not engaged in rendering legal, accounting, or other professional services If professional assistance is required, the services of a

competent professional person should be sought Neither the publisher nor the author shall be liable for damages arising herefrom.

The fact that an organization or Website is referred to in this work as a citation and/or a potential source of further information does

not mean that the author or the publisher endorses the information the organization or Website may provide or recommendations it

may make Further, readers should be aware that Internet Websites listed in this work may have changed or disappeared between

when this work was written and when it is read.

For general information on our other products and services or to obtain technical support, please contact our Customer Care

Department within the U.S at (800) 762–2974, outside the U.S at (317) 572–3993 or fax (317) 572–4002.

Wiley also publishes its books in a variety of electronic formats Some content that appears in print may not be available in electronic

and/or its affiliates, in the United States and other countries, and may not be used without written permission All other trademarks

are the property of their respective owners Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this

book.

10 9 8 7 6 5 4 3 2 1

Trang 8

Dear Reader,

Thank you for choosing Mastering Microsoft Visual Basic 2008 This book is part of a family of

premium quality Sybex books, all written by outstanding authors who combine practical

experi-ence with a gift for teaching

Sybex was founded in 1976 More than thirty years later, we’re still committed to producing

consistently exceptional books With each of our titles we’re working hard to set a new standard

for the industry From the paper we print on, to the authors we work with, our goal is to bring you

the best books available

I hope you see all that reflected in these pages I’d be very interested to hear your comments

and get your feedback on how we’re doing Feel free to let me know what you think about this or

any other Sybex book by sending me an email at nedde@wiley.com, or if you think you’ve found

a technical error in this book, please visit http://sybex.custhelp.com Customer feedback is

critical to our efforts at Sybex

Best regards,

Neil Edde

Vice President and Publisher

Sybex, an Imprint of Wiley

Trang 10

To my dearest and most precious ones, Nefeli

and Eleni-Myrsini.

Trang 12

Many people contributed to this book, and I would like to thank them all I first want to express my

deep appreciation to Mark Ridgeway for contributing the Web-related chapters (Chapters 25, 26,

and 27) and Chapter 5, ‘‘The Vista Interface,’’ and to John Mueller for providing the technical edit of

this book I want to thank the programmers at Microsoft for their commitment to Visual Basic Visual

Basic has evolved from a small, limited programming environment to a first-class development tool

for building all types of Windows and Web applications, from small hobbyist projects to enterprise

scale applications

Special thanks to the talented people at Sybex — to all of them and to each one individually

Starting with editor Toni Zuccarini Ackley, who has taken this book under her wing and improved

it in numerous ways To acquisitions editor Tom Cirtin, who has followed the progress of the

book, its ups and downs, and managed to coordinate the entire team To production editor Daniel

Scribner, who kept this project in order and on schedule Thanks, Daniel To copyeditor Sharon

Wiley, proofreader Nancy Riddiough, indexer Ron Strauss and everyone else who added their

expertise and talent

Trang 14

About the Author

Evangelos Petroutsos works as a consultant on medium to large projects, teaches, and writes

articles — but he mostly writes code, VB code He specializes in VB and SQL, and from the new

technologies, he fancies XML He has authored many articles and more than 10 programming

books, including the best-selling titles Mastering Microsoft Visual Basic 2005 and Mastering Visual

Basic NET Database Programming, both published by Sybex.

Trang 16

Contents at a Glance

Introduction xxix

Chapter 1 • Getting Started with Visual Basic 2008 1

Chapter 2 • Variables and Data Types 35

Chapter 3 • Programming Fundamentals 85

Chapter 4 • GUI Design and Event-Driven Programming 123

Chapter 5 • The Vista Interface 151

Chapter 6 • Basic Windows Controls 173

Chapter 7 • Working with Forms 217

Chapter 8 • More Windows Controls 267

Chapter 9 • The TreeView and ListView Controls 305

Chapter 10 • Building Custom Classes 349

Chapter 11 • Working with Objects 395

Chapter 12 • Building Custom Windows Controls 429

Chapter 13 • Handling Strings, Characters, and Dates 461

Chapter 14 • Storing Data in Collections 499

Chapter 15 • Accessing Folders and Files 541

Chapter 16 • Serialization and XML 591

Chapter 17 • Querying Collections and XML with LINQ 621

Chapter 18 • Drawing and Painting with Visual Basic 2008 649

Chapter 19 • Manipulating Images and Bitmaps 693

Chapter 20 • Printing with Visual Basic 2008 717

Trang 17

xiv CONTENTS AT A GLANCE

Chapter 21 • Basic Concepts of Relational Databases 753

Chapter 22 • Programming with ADO.NET 805

Chapter 23 • Building Data-Bound Applications 845

Chapter 24 • Advanced DataSet Operations 885

Chapter 25 • Building Web Applications 901

Chapter 26 • ASP.NET 3.5 937

Chapter 27 • ASP.NET Web Services 981

Appendix A • ’’The Bottom Line’’ 997

Appendix B • ’’Debugging and Error Handling’’ 1045

Index 1075

Trang 18

Introduction xxix

Chapter 1Getting Started with Visual Basic 2008 1

Exploring the Integrated Development Environment 1

The Start Page 2

Starting a New Project 3

Using the Windows Form Designer 5

Creating Your First VB Application 11

Making the Application More User-Friendly 15

Understanding the IDE Components 18

The IDE Menu 18

Toolbox Window 23

Solution Explorer Window 23

Properties Window 23

Output Window 24

Command and Immediate Windows 24

Error List Window 25

Setting Environment Options 25

Building a Console Application 27

Using Code Snippets 29

Using the My Object 30

The Bottom Line 33

Chapter 2Variables and Data Types 35

Variables 35

Declaring Variables 36

Types of Variables 39

The Strict, Explicit, and Infer Options 54

Object Variables 58

Variables as Objects 60

Converting Variable Types 61

Formatting Numbers 64

User-Defined Data Types 66

Examining Variable Types 69

Why Declare Variables? 71

A Variable’s Scope 71

A Variable’s Lifetime 73

Constants 74

Trang 19

xvi CONTENTS

Arrays 75

Declaring Arrays 75

Initializing Arrays 77

Array Limits 77

Multidimensional Arrays 78

Dynamic Arrays 81

The Bottom Line 82

Chapter 3Programming Fundamentals 85

Flow-Control Statements 85

Decision Statements 86

Loop Statements 93

Nested Control Structures 98

The Exit Statement 100

Writing and Using Procedures 100

Subroutines 100

Functions 101

Arguments 103

Argument-Passing Mechanisms 104

Built-in Functions 107

Custom Functions 109

Passing Arguments and Returning Values 111

More Types of Function Return Values 113

Overloading Functions 117

The Bottom Line 121

Chapter 4GUI Design and Event-Driven Programming 123

On Designing Windows Applications 123

Building a Loan Calculator 124

Understanding How the Loan Calculator Application Works 125

Designing the User Interface 126

Programming the Loan Application 129

Validating the Data 133

Building a Calculator 137

Designing the User Interface 137

Programming the MathCalculator 139

Using Simple Debugging Tools 145

Exception Handling 147

The Bottom Line 149

Chapter 5The Vista Interface 151

Introducing XAML 151

Introducing the WPF Controls 153

Simple ‘‘Hello World’’ WPF Application 154

Simple Drawing Program 156

Trang 20

CONTENTS xvii

Data-Binding WPF Controls 159

Data-Binding Example 2: Binding to a Database 164

Creating a WPF Browser Application 166

Expression Blend Overview 168

The Bottom Line 171

Chapter 6Basic Windows Controls 173

The TextBox Control 173

Basic Properties 174

Text-Manipulation Properties 176

Text-Selection Properties 179

Text-Selection Methods 180

Undoing Edits 181

VB 2008 at Work: The TextPad Project 181

Capturing Keystrokes 188

Auto-complete Properties 190

The ListBox, CheckedListBox, and ComboBox Controls 195

Basic Properties 196

Manipulating the Items Collection 197

Selecting Items 200

VB 2008 at Work: The ListBox Demo Project 200

Searching the ListBox 203

The ComboBox Control 205

The ScrollBar and TrackBar Controls 210

The ScrollBar Control 210

The TrackBar Control 213

The Bottom Line 214

Chapter 7Working with Forms 217

The Appearance of Forms 217

Properties of the Form Object 218

Placing Controls on Forms 223

Setting the TabOrder Property 224

VB 2008 at Work: The Contacts Project 226

Anchoring and Docking 229

Splitting Forms into Multiple Panes 232

The Form’s Events 234

Loading and Showing Forms 236

The Startup Form 237

Controlling One Form from within Another 238

Forms versus Dialog Boxes 240

Building Dynamic Forms at Runtime 246

The Form’s Controls Collection 247

Creating Event Handlers at Runtime 253

Designing Menus 255

Trang 21

xviii CONTENTS

The Menu Editor 255

The ToolStripMenuItem Properties 257

Manipulating Menus at Runtime 260

Iterating a Menu’s Items 263

The Bottom Line 265

Chapter 8More Windows Controls 267

The Common Dialog Controls 267

Using the Common Dialog Controls 268

The ColorDialog Control 270

The FontDialog Control 272

The OpenDialog and SaveDialog Controls 274

The FolderBrowserDialog Control 279

The RichTextBox Control 283

The RTF Language 284

Text Manipulation and Formatting Properties 286

Methods 289

Advanced Editing Features 290

Cutting and Pasting 291

Searching in a RichTextBox Control 291

Handling URLs in the Document 292

Displaying a Formatted Directory Listing 293

VB 2008 at Work: The RTFPad Project 294

The Bottom Line 302

Chapter 9The TreeView and ListView Controls 305

Understanding the ListView, TreeView, and ImageList Controls 305

Tree and List Structures 306

The ImageList Control 309

The TreeView Control 310

Adding Nodes at Design Time 312

Adding Nodes at Runtime 313

VB 2008 at Work: The TreeViewDemo Project 316

VB 2008 at Work: The Globe Project 320

Scanning the TreeView Control 328

The ListView Control 330

The Columns Collection 332

ListView Items and Subitems 334

The Items Collection 336

The SubItems Collection 336

VB 2008 at Work: The ListViewDemo Project 337

Sorting the ListView Control 340

Processing Selected Items 342

VB 2008 at Work: The CustomExplorer Project 343

Additional Topics 346

The Bottom Line 347

Trang 22

CONTENTS xix

Chapter 10Building Custom Classes 349

Classes and Objects 349

What Is a Class? 350

Classes Combine Code with Data 351

Building the Minimal Class 352

Adding Code to the Minimal Class 355

Using Property Procedures 356

Customizing Default Members 362

VB 2008 at Work: The LengthUnits Class 389

The Bottom Line 394

Chapter 11Working with Objects 395

Issues in Object-Oriented Programming 395

Classes versus Objects 395

Objects versus Object Variables 396

Properties versus Fields 400

Shared versus Instance Members 401

Type Casting 402

Early versus Late Binding 403

Discovering a Variable’s Type 404

Inheritance 404

How to Apply Inheritance 405

Polymorphism 415

Building the Shape Class 417

Who Can Inherit What? 421

Parent Class Keywords 422

Derived Class Keywords 422

Parent Class Member Keywords 423

Derived Class Member Keyword 423

VB 2008 At Work: The InheritanceKeywords Project 424

MyBase and MyClass 425

The Class Diagram Designer 427

The Bottom Line 428

Chapter 12Building Custom Windows Controls 429

On Designing Windows Controls 429

Enhancing Existing Controls 430

Trang 23

Chapter 13Handling Strings, Characters, and Dates 461

Handling Strings and Characters 461 The Char Class 462 The String Class 464 The StringBuilder Class 473

VB 2008 at Work: The StringReversal Project 476

VB 2008 at Work: The CountWords Project 479 Handling Dates and Times 481 The DateTime Class 481 The TimeSpan Class 492 The Bottom Line 497

Chapter 14Storing Data in Collections 499

Advanced Array Topics 499 Sorting Arrays 499 Searching Arrays 502 Performing Other Array Operations 506 Array Limitations 509 The ArrayList Collection 509 Creating an ArrayList 509 Adding and Removing ArrayList Items 510 Sorting ArrayLists 513 Searching ArrayLists 515 Iterating an ArrayList 515 The HashTable Collection 516

VB 2008 at Work: The WordFrequencies Project 518 The SortedList Collection 523

VB 2008 at Work: The SortedList Project 524 Other Collections 527 The IEnumerator and IComparer Interfaces 528 Enumerating Collections 528 Custom Sorting 531 Generic Collections 537 The Bottom Line 539

Trang 24

CONTENTS xxi

Chapter 15Accessing Folders and Files 541

The IO Namespace and the FileSystem Component 541

Using the My.Computer.FileSystem Component 542

Manipulating Folders and Files with the IO Namespace 546

The Directory Class 547

The File Class 554

Drive, Folder, and File Properties 560

The Path Class 564

VB 2008 at Work: The CustomExplorer Project 566

Accessing Files 569

Using Streams 570

VB 2008 at Work: The RecordSave Project 580

The FileSystemWatcher Component 585

Properties 585

Events 586

VB 2008 at Work: The FileSystemWatcher Project 587

The Bottom Line 589

Chapter 16Serialization and XML 591

Understanding Serialization Types 591

Using Binary and SOAP Serialization 592

Serializing Individual Objects 592

Deserializing Individual Objects 594

Serializing and Deserializing Individual Objects 608

Serializing Custom Objects 609

Serializing ArrayLists and HashTables 613

Working with XML Files 615

Understanding XML Structure 615

Editing XML Files 617

The Bottom Line 620

Chapter 17Querying Collections and XML with LINQ 621

Trang 25

xxii CONTENTS

Retrieving Data with the ExecuteQuery Method 646 The Bottom Line 647

Chapter 18Drawing and Painting with Visual Basic 2008 649

Displaying and Sizing Images 649 Drawing with GDI+ 652 The Basic Drawing Objects 654 Drawing Shapes 663 Drawing Methods 667 Gradients 681 Clipping 685 Applying Transformations 687

VB 2008 at Work: The ImageCube Project 690

VB 2008 at Work: Plotting Functions 691 The Bottom Line 691

Chapter 19Manipulating Images and Bitmaps 693

Specifying Colors 693 The RGB Color Cube 694 Defining Colors 695 The Image Object 699 Properties 699 Methods 699

VB 2008 at Work: The Thumbnails Project 702 Exchanging Images through the Clipboard 705 The Bitmap Object 706 Processing Bitmaps 708

VB 2008 at Work: The ImageProcessing Project 710 The Bottom Line 715

Chapter 20Printing with Visual Basic 2008 717

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

VB 2008 at Work: The SimplePrintout Project 729

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

Trang 26

CONTENTS xxiii

Chapter 21Basic Concepts of Relational Databases 753

What Is a Database? 753

Using Relational Databases 754

Obtaining the Northwind and Pubs Sample Databases 755

Exploring the Northwind Database 756

Exploring the Pubs Database 760

Understanding Relations 761

Server Explorer 763

Working with Tables 767

Working with Relationships, Indices, and Constraints 770

Structured Query Language 773

Executing SQL Statements 775

Using Selection Queries 776

Working with Calculated Fields 783

Calculating Aggregates 783

Using SQL Joins 785

Grouping Rows 788

Limiting Groups with HAVING 790

Selecting Groups with IN and NOT IN 791

Selecting Ranges with BETWEEN 791

Action Queries 791

Deleting Rows 792

Inserting New Rows 793

Editing Existing Rows 794

The Query Builder 794

The Query Builder Interface 795

SQL at Work: Calculating Sums 796

SQL at Work: Counting Rows 797

Parameterized Queries 798

Calculated Columns 799

Stored Procedures 800

The SalesByCategory Stored Procedure 801

The Bottom Line 802

Chapter 22Programming with ADO.NET 805

Stream- versus Set-Based Data Access 805

The Basic Data-Access Classes 806

The Connection Class 807

The Command Class 809

The DataReader Class 819

Storing Data in DataSets 822

Filling DataSets 823

Accessing the DataSet’s Tables 828

Working with Rows 828

Handling Null Values 829

Adding and Deleting Rows 830

Trang 27

xxiv CONTENTS

Navigating through a DataSet 831 Update Operations 834 Updating the Database with the DataAdapter 835 Handling Identity Columns 836

VB 2008 at Work: The SimpleDataSet Project 837 The Bottom Line 843

Chapter 23Building Data-Bound Applications 845

Working with Typed DataSets 845 Generating a Typed DataSet 846 Exploring the Typed DataSet 850 Data Binding 855 Using the BindingSource Class 857 Designing Data-Driven Interfaces the Easy Way 863 Enhancing the Navigational Tools 866 Binding Hierarchical Tables 867 Adjusting the Appearance of the DataGridView Control 870 Building More-Functional Interfaces 877 The Bottom Line 883

Chapter 24Advanced DataSet Operations 885

Working with SQL Expressions 885 Selecting Rows 886 Simple Calculated Columns 887 Calculated Columns with Aggregates 888

VB 2008 at Work: The SQL Expressions Project 890 Selecting and Viewing an Order’s Details 895 The Bottom Line 900

Chapter 25Building Web Applications 901

Developing for the Web 901 Understanding HTML and XHTML 902 Working with HTML 903 Page Construction 904 Text Management 905 Horizontal Rules 905 Images 905 Links 906 Embedding Media 906 Comments 906 Scripts 907 Lists 907 Tables 907 Page Formatting 909 Forms and Form Elements 909 Cascading Style Sheets (CSS) 911

Trang 28

CONTENTS xxv

Formatting Styles with CSS 912

Page Formatting with CSS 913

Building the Style Sheet for MasterPage.master 939

Creating the Style Sheet 940

Attaching the Style Sheet to the Master Page 942

Creating the Content Master Page 944

Creating ContentStyleSheet.css 945

Completing ContentMasterPage.master 947

Adding Elements to the Main Master Page 948

Creating the Web User Control 949

Adding the Web User Control to Your Page 952

Creating the Footer.ascx Web User Control 953

Building the Site Navigation 955

Creating a SiteMap 955

Configuring the Menu Control for MasterPage.master 955

Trang 29

xxvi CONTENTS

Creating the Navbar in ContentsMasterPage.master 956 Adding Authentication 957 Using the Login Control 957 Establishing Forms-Based Authentication 957 Adding an Access Rule 958 Adding a LoginName Control to MasterPage.master 959 Adding a LoginName Control to ContentMasterPage.master 960 Adding Content Pages 960 Adding an Entry to the SiteMap 961 Updating the SiteMapDataSource Control 961 Running the Application 961 Adding Further Content Pages 963 Adding Items to the SiteMap 963 Using Buttons for Navigation 963 Building the Password Page 965 Building the NewUser.aspx page 967 Working with Data 967 Creating the XML Database 968 Working with the GridView Control 970 Further Configuration of the GridView Control 971 Building the Computers.aspx Page 974 Adding the DropDownList Control 975 Adding the DetailsView Control 976 Further Configuring the DetailsView Control 977 Building the Report.aspx page 978 Adding the MicrosoftReportViewer Control 978 Creating the Report 978 The Bottom Line 980

Chapter 27ASP.NET Web Services 981

Using ASP.NET Web Services and WCF 981 ASP.NET Web Services 981 Windows Communication Foundation (WCF) 982 Understanding Technologies Associated with Web Services 982 SOAP 983 Web Services Description Language (WSDL) 983 SOAP Discovery 983 Universal Description, Discovery, and Integration (UDDI) 983 Creating a Simple ASP.NET Web Service 984 Setting Up the Web Service 984 Testing the Web Service 985 Consuming the Web Service 986 Developing a Stand-Alone Web Service 986 Building MyWebService 987 Deploying MyWebService 989 Consuming MyWebService 989

Trang 30

CONTENTS xxvii

Simple AJAX Implementation 993

The Bottom Line 995

Appendix A 997

Appendix B 1045

Index 1075

Trang 32

Welcome to Visual Basic 2008, the most mature version yet of the most popular programming

language for building Windows and web applications In modern software development,

how-ever, the language is only one of the components we use to build applications The most important

component is the NET Framework, which is an indispensable component of every application; it’s

actually more important than the language itself You can think of the Framework as an enormous

collection of functions for just about any programming task All drawing methods, for example,

are part of the System.Drawing class To draw a rectangle, you call the DrawRectangle method of

the System.Drawing class, passing the appropriate arguments To create a new folder, you call the

CreateDirectorymethod of the Directory class, and to retrieve the files in a folder you call the

GetFilesmethod of the same class

The Framework contains all the functionality of the operating system and makes it available to

your application through methods The language and the Framework are the two ‘‘programming’’

components, absolutely necessary to build Windows applications It’s possible to develop

appli-cations with these two components alone, but the process would be awfully slow The software

development process relies on numerous tools that streamline the coding experience, and these

tools are provided for us by Visual Studio 2008

The third component is an integrated environment that hosts a number of tools enabling you

to perform many common tasks with point-and-click operations It’s basically an environment

in which you can design your forms with visual tools and write code as well This environment,

provided by Visual Studio 2008, is known as an integrated development environment, or IDE

You’ll be amazed by the functionality provided by the tools of Visual Studio 2008: you can actually

design a functional data-driven application without writing a single line of code You can use

similar tools in the same environment to design a fancy data-driven web page without a single line

of code Visual Studio even provides tools for manipulating databases and allows you to switch

between tasks, all in the same, streamlined environment You realize, of course, that Visual Studio

isn’t about writing applications without code; it just simplifies certain tasks through wizards and,

more often than not, we step in and provide custom code to write a functional application Even

so, Visual Studio 2008 provides numerous tools, from debugging tools to help you track and fix

all kinds of bugs in your code, to database manipulation tools

This book shows you how to use Visual Studio 2008 and Visual Basic 2008 to design rich

Win-dows and web applications We’ll start with the visual tools and then we’ll explore Visual Basic

and the Framework A Windows application consists of a visual interface and code behind the

ele-ments of the interface (The code handles the user actions on the visual interface, such as the click

of a button, the selection of a menu item, and so on.) You’ll use the tools of Visual Studio to build

the visual interface and then you’ll program the elements of the application with Visual Basic For

any nontrivial processing, such as file and folder manipulation, data storage, and so on, you’ll use

Trang 33

xxx INTRODUCTION

the appropriate classes of the NET Framework A substantial segment of this book deals with themost useful components of the Framework

The Mastering Series

The Mastering series from Sybex provides outstanding instruction for readers with intermediate

and advanced skills, in the form of top-notch training and development for those already working

in their field and clear, serious education for those aspiring to become pros Every Mastering book

includes the following:

◆ Real-World Scenarios, ranging from case studies to interviews, that show how the tool,technique, or knowledge presented is applied in actual practice

◆ Skill-based instruction, with chapters organized around real tasks rather than abstractconcepts or subjects

◆ Self-review test questions, so you can be certain you’re equipped to do the job right

Who Should Read This Book?

You don’t need a solid knowledge of Visual Basic to read this book, but you do need a basicunderstanding of programming You need to know the meaning of variables and functions and

how an If .Then structure works This book is aimed at the typical programmer who wants to

get the most out of Visual Basic It covers the topics I felt are of use to most VB programmers,and it does so in depth Visual Basic 2008 and the NET Framework 3.5 are two extremely richprogramming tools, and I had to choose between a superficial coverage of many topics and anin-depth coverage of fewer topics To make room for more topics, I have avoided including a lot

of reference material and lengthy listings For example, you won’t find complete project listings orform descriptions I assume that you can draw a few controls on a form and set their properties,and that you don’t need long descriptions of the controls’ properties I’m also assuming that youdon’t want to read the trivial segments of each application Instead, the listings concentrate on the

‘‘meaty’’ part of the code: the procedures that explain the topic at hand

The topics covered in this book were chosen to provide a solid understanding of the principlesand techniques for developing applications with Visual Basic Programming isn’t about newkeywords and functions I chose the topics I felt every programmer should learn in order to masterthe language I was also motivated by my desire to present useful, practical examples You willnot find all topics equally interesting or important My hope is that everyone will find somethinginteresting and something of value for his or her daily work — whether it’s an application thatmaps the folders and files of a drive to a TreeView control, an application that prints tabulardata, a data-driven application for editing customers or products, or an application that saves acollection of objects to a file

Many books offer their readers long, numbered sequences of steps to accomplish a task ing instructions simplifies certain tasks, but programming isn’t about following instructions It’sabout being creative; it’s about understanding principles and being able to apply the same tech-niques in several practical situations And the way to creatively exploit the power of a languagesuch as Visual Basic 2008 is to understand its principles and its programming model

Follow-In many cases, I provide a detailed, step-by-step procedure that will help you accomplish atask, such as designing a menu, for example But not all tasks are as simple as designing menus

I explain why things must be done in a certain way, and I present alternatives and try to connect

Trang 34

INTRODUCTION xxxi

new topics to those explained earlier in the book In several chapters, I expand on applications

developed in earlier chapters Associating new knowledge with something you have mastered

already provides positive feedback and a deeper understanding of the language

This book isn’t about the hottest features of the language; it’s about solid programming

tech-niques and practical examples After you master the basics of programming Windows applications

with Visual Basic 2008 and you feel comfortable with the more advanced examples of the book,

you will find it easy to catch up with the topics not discussed in this book Of course, you will find

information about the latest data access techniques, as well as an introduction to LINQ (Language

Integrated Query), which is the hottest new component of the Framework

How about the Advanced Topics?

Some of the topics discussed in this book are nontrivial, and quite a few topics can be considered

advanced The TreeView control, for example, is not a trivial control, like the button or text box

control, but it’s ideal for displaying hierarchical information (This is the control that displays

the hierarchy of folders in Windows Explorer.) If you want to build an elaborate user interface,

you should be able to program controls such as the TreeView and ListView controls, which are

discussed in Chapter 9, ‘‘The TreeView and ListView Controls.’’

You may also find some examples to be more difficult than you expected I have tried to

make the text and the examples easy to read and understand, but not unrealistically simple

In Chapter 15, ‘‘Accessing Folders and Files,’’ you will find information about the File and

Directory objects You can use these objects to access and manipulate the file system from within

your application, but this chapter wouldn’t be nearly as useful without an application that shows

you how to scan a folder recursively (scan the folder’s files and then its subfolders, to any depth)

To make each chapter as useful as I could, I’ve included nontrivial examples, which will provide a

better understanding of the topics In addition, many of these examples can be easily incorporated

into your applications

You can do a lot with the TreeView control with very little programming, but to make

the most out of this control, you must be ready for some advanced programming — nothing

terribly complicated, but some things just aren’t trivial Programming most of the operations

of the TreeView control, for instance, is not complicated, but if your application calls for

populating a TreeView control with an arbitrary number of branches (such as mapping a

direc-tory structure to a TreeView control), the code can get complex The same goes for printing; it’s

fairly straightforward to write a program that prints some text, but printing tabular reports takes

substantial coding effort

The reason I’ve included the more advanced examples is that the corresponding chapters

would be incomplete without them If you find some material to be over your head at first

read-ing, you can skip it and come back to it after you have mastered other aspects of the language

But don’t let a few advanced examples intimidate you Most of the techniques are well within

the reach of an average VB programmer The few advanced topics were included for the readers

who are willing to take that extra step and build elaborate interfaces by using the latest tools and

techniques

There’s another good reason for including advanced topics Explaining a simple topic, such as

how to populate a collection with items, is very simple But what good is it to populate a collection

if you don’t know how to save it to disk and read back its items in a later session? Likewise, what

good is it to learn how to print simple text files? In a business environment, you will most likely

be asked to print a tabular report, which is substantially more complicated than printing text In

Chapter 20, ‘‘Printing with Visual Basic 2008,’’ you will learn how to print business reports with

Trang 35

xxxii INTRODUCTION

headers, footers, and page numbers, and even how to draw grids around the rows and columns

of the report One of my goals in writing this book was to exhaust the topics I’ve chosen to discussand present all the information you need to do something practical

The Structure of the Book

This book isn’t meant to be read from cover to cover, and I know that most people don’t readcomputer books this way Each chapter is independent of the others, although all chapters containreferences to other chapters Each topic is covered in depth; however, I make no assumptionsabout the reader’s knowledge of the topic As a result, you may find the introductory sections

of a chapter too simple The topics become progressively more advanced, and even experiencedprogrammers will find some new information in most chapters Even if you are familiar withthe topics in a chapter, take a look at the examples I have tried to simplify many of the advancedtopics and demonstrate them with clear, practical examples

This book tries to teach through examples Isolated topics are demonstrated with shortexamples, and at the end of many chapters you’ll build a large, practical application (a real-worldapplication) that ‘‘puts together’’ the topics and techniques discussed throughout the chapter

You may find some of the more advanced applications a bit more difficult to understand, but youshouldn’t give up Simpler applications would have made my job easier, but the book wouldn’t

deserve the Mastering title, and your knowledge of Visual Basic wouldn’t be as complete.

The book starts with the fundamentals of Visual Basic 2008 You’ll learn how to designvisual interfaces with point-and-click operations and how to program a few simple events, such asthe click of the mouse on a button After reading the first two chapters, you’ll understand thestructure of a Windows application Then you’ll explore the elements of the visual interface(the basic Windows controls) and how to program them You’ll also learn about the My object andcode snippets, two features that make Visual Basic so simple and fun to use These two objects willalso ease the learning process and make it much simpler to learn the features of the language

I then discuss in detail the basic components of Windows applications I explain the mostcommon controls you’ll use in building Windows forms in detail, as well as how to work withforms: how to design forms, how to design menus for your forms, how to create applications withmultiple forms, and so on You will find detailed discussions of many Windows controls, as well

as how to take advantage of the built-in dialog boxes, such as the Font and Color dialog boxes, inyour applications

Visual Basic 2008 is a truly object-oriented language, and objects are the recurring theme

in every chapter The three following chapters (chapter 10, 11 and 12) contain a formal andmore systematic treatment of objects You will learn how to build custom classes and controls,which will help you understand object-oriented programming a little better You will also learnabout inheritance and will see how easy it is to add custom functionality to existing classesthrough inheritance

The following few chapters deal with some of the most common classes of the NETFramework The Framework is at the very heart of Windows programming; it’s your gateway

to the functionality of the operating system itself, and it’s going to be incorporated into the nextversion of Windows You’ll examine several extremely interesting topics such as collections (forexample, ArrayLists and HashTables), the classes for manipulating files and folders, the String-Builder class that manipulates text, XML serialization, and a few more, including the LanguageIntegrated Query component (LINQ, which is brand new to the latest version of the Framework)

Then you will find a few chapters on graphics You’ll learn how to use the classes of theFramework that generate graphics, and you’ll learn how to create vector drawings as well as

Trang 36

INTRODUCTION xxxiii

how to manipulate bitmaps In Chapter 20, you’ll learn everything you need to create printouts

with Visual Basic 2008 and see a few practical examples

The first twenty chapters deal with the fundamentals of the language and Windows

applica-tions Following these chapters, you will find an overview of the data-access tools The emphasis

is on the visual tools, and you will learn how to query databases and present data to the user

You will also find information on programming the basic objects of ADO.NET and write simple

data-driven Windows applications

In the last few chapters of this book you will learn about web applications, the basics of

ASP.NET 2, how to develop data-bound web applications, and how to write web services

Downloading This Book’s Code

The code for the examples and projects can be downloaded from the Sybex website (www.sybex.com)

At the main page, you can find the book’s page by searching for the author, the title, or the ISBN

(9780470187425), and then clicking the book’s link listed in the search results On the book’s page,

click the Download link It will take you to the download page The downloaded source code is a

zip file, which you can unzip with the WinZip utility

How to Reach the Author

Despite our best efforts, a book of this size is bound to contain errors Although a printed medium

isn’t as easy to update as a website, I will spare no effort to fix every problem you report (or I

dis-cover) The revised applications, along with any other material I think will be of use to the readers of

this book, will be posted on the Sybex website If you have any problems with the text or the

applica-tions in this book, you can contact me directly at pevangelos@yahoo.com

Although I can’t promise a response to every question, I will fix any problems in the examples and

provide updated versions I would also like to hear any comments you may have on the book, about

the topics you liked or did not like, and how useful the examples are Your comments will be taken

into consideration in future editions

Trang 38

Chapter 1

Getting Started with

Visual Basic 2008

I’m assuming that you have installed one of the several versions of Visual Studio 2008 For this

book, I used the Professional Edition of Visual Studio, but just about everything discussed in

this book applies to the Standard Edition as well Some of the features of the Professional Edition

that are not supported by the Standard Edition concern database tools, which are discussed in

Chapters 21 through 24 of this book

You may have even already explored the new environment on your own, but this book starts

with an overview of Visual Studio and its basic tools It doesn’t even require any knowledge of

VB 6, just some familiarity with programming at large As you already know, Visual Basic 2008

is just one of the languages you can use to build applications with Visual Studio 2008 I happen

to be convinced that it is also the simplest, most convenient language, but this isn’t really the

issue; I’m assuming you have your reasons to code in VB, or else you wouldn’t be reading this

book What you should keep in mind is that Visual Studio 2008 is an integrated environment for

building, testing, debugging, and deploying a variety of applications: Windows applications, web

applications, classes and custom controls, and even console applications It provides numerous

tools for automating the development process, visual tools for performing many common design

and programming tasks, and more features than any author would hope to cover

In this chapter, you’ll learn how to do the following:

◆ Navigate the integrated development environment of Visual Studio

◆ Understand the basics of a Windows application

Exploring the Integrated Development Environment

Visual Basic 2008 is just one of the languages you can use to program your applications The

language is only one aspect of a Windows application The visual interface of the application isn’t

tied to a specific language, and the same tools you’ll use to develop your application’s interface

will also be used by all programmers, regardless of the language they’ll use to code the application

To simplify the process of application development, Visual Studio provides an environment

that’s common to all languages, which is known as an integrated development environment (IDE).

The purpose of the IDE is to enable the developer to do as much as possible with visual tools,

before writing code

The IDE provides tools for designing, executing, and debugging your applications It will be

a while before you explore all the elements of the IDE, and I will explain the various items as

needed in the course of the book In this section, you’ll look at the basic components of the IDE

Trang 39

2 CHAPTER 1 GETTING STARTED WITH VISUAL BASIC 2008

needed to build simple Windows applications You’ll learn how its tools allow you to quicklydesign the user interface of your application, as well as how to program the application

The IDE is your second desktop, and you’ll be spending most of your productive hours in thisenvironment

The Start Page

When you run Visual Studio 2008 for the first time, you will be prompted to select the type ofprojects you plan to build with Visual Studio, so that the environment can be optimized for thatspecific type of development I’m assuming that you have initially selected the Visual Basic Devel-opment settings, which will optimize your copy of Visual Studio for building Windows and webapplications with Visual Basic 2008 You can always change these settings, as explained at the end

of this section

After the initial configuration, you will see a window similar to the one shown in Figure 1.1 TheRecent Projects pane will be empty, of course, unless you have already created some test projects

Visual Studio 2008 will detect the settings of a previous installation, so if you’re upgrading from

an earlier version of Visual Studio, the initial screen will not be identical to the one shown inFigure 1.1

Figure 1.1

This is what you’ll see

when you start Visual

Studio for the first time

On the Start Page of Visual Studio, you will see the following panes:

Recent Projects Here you see a list of the projects you opened most recently with VisualStudio, and you can select the one you want to open again — chances are that you will con-tinue working on the same project as the last time Each project’s name is a hyperlink, and youcan open it by clicking its name At the bottom of the Recent Projects section are two hyper-links, for opening or creating another project

MSDN: Visual Studio This section is a browser window that displays an MSDN(the Microsoft Developer Network, which is the definitive resource for all Microsoft tech-nologies and products) page when the computer is connected to the Internet In this section,

Trang 40

EXPLORING THE INTEGRATED DEVELOPMENT ENVIRONMENT 3

you will see news about Visual Studio, the supported languages, articles, and other

inter-esting bits of information

Getting Started This section contains links to basic programming tasks in the product’s

documentation

Visual Studio Headlines This section contains links to announcements and other news

of interest to VB developers

Most developers will skip the Start Page To do so, open the Tools menu and choose the

Import And Export Settings command to start a configuration wizard In the first dialog box of

the wizard, select the Reset All Settings check box and click the Next button The next screen

of the wizard prompts you for the location where the new settings will be saved, so that Visual

Studio can read them every time it starts Leave the default location as is and click Next again to

see the last screen of the wizard, in which you’re prompted to select a default collection of settings

This collection depends on the options you’ve installed on your system I installed Visual

Studio 2008 with Visual Basic only on my system, and I was offered the following options: General

Development Settings, Visual Basic Development Settings, and Web Development Settings

For the default configuration of my copy of Visual Studio, and for the purposes of this book, I

chose the Visual Basic Development Settings, so that Visual Studio could optimize the

environ-ment for a typical VB developer Click the Finish button to see a summary of the process and then

close the wizard

Starting a New Project

At this point, you can create a new project and start working with Visual Studio To best explain

the various items of the IDE, we will build a simple form The form is the window of your

application — it’s what users will see on their Desktop when they run your application

Open the File menu and choose New Project, or click Create Project/Solution in the Start Page

In the New Project dialog box that pops up (see Figure 1.2), you’ll see a list of project types you can

create with Visual Studio The most important ones are Windows Forms Applications, which are

typical Windows applications with one or more forms (windows); Console Applications, which

are simple applications that interact with the user through a text window (the console); Windows

Forms Control Libraries, which are collections of custom controls; and Class Libraries, which are

collections of classes These are the project types we’ll cover in depth in this book

If you have installed Visual Basic 2008 Express Edition, you will see fewer project types in the

New Project dialog box, but the projects discussed in this book are included

Notice the Create Directory For Solution check box in the dialog box of Figure 1.2 By default,

Visual Studio creates a new folder for the project under the folder you have specified in the

Loca-tion box If you want to put together a short applicaLoca-tion to test a feature of the language, or perform

some trivial task, you may not wish to save the project In this case, just clear the check box to skip

the creation of a new project folder

You can always save a project at any time by choosing the Save All command from the File

menu You’ll be prompted at that point about the project’s folder, and Visual Studio will save

the project under the folder you specified If you decide to discard the project, you can create

a new project or close Visual Studio Visual Studio will prompt you about an open project that

hasn’t been saved yet, and you can choose not to save it

You may discover at some point that you have created too many projects, which you don’t

really need You can remove these projects from your system by deleting the corresponding

folders — no special action is required You’ll know it’s time to remove the unneeded project

folder when Visual Studio suggests project names such as WindowsApplication9 or

Windows-Application49

Ngày đăng: 12/08/2014, 21:20

TỪ KHÓA LIÊN QUAN