Visual basic

Petroutsos ftoc.tex V2 - 01/28/2008 6:12pm Page xiii
Contents at a Glance
Introduction ........................................................ xxix
Chapter 1 • Getting Started with Visual Basic 2008 ........................... 1
Chapter 2 • Variables and Data Types .................................... 35
Chapter 3 • Programming Fundamentals .................................. 85
Chapter 4 • GUI Design and Event-Driven Programming .................... 123
Chapter 5 • The Vista Interface ......................................... 151
Chapter 6 • Basic Windows Controls .................................... 173
Chapter 7 • Working with Forms ....................................... 217
Chapter 8 • More Windows Controls .................................... 267
Chapter 9 • The TreeView and ListView Controls .......................... 305
Chapter 10 • Building Custom Classes ................................... 349
Chapter 11 • Working with Objects ..................................... 395
Chapter 12 • Building Custom Windows Controls ......................... 429
Chapter 13 • Handling Strings, Characters, and Dates ....................... 461
Chapter 14 • Storing Data in Collections ................................. 499
Chapter 15 • Accessing Folders and Files ................................. 541
Chapter 16 • Serialization and XML ..................................... 591
Chapter 17 • Querying Collections and XML with LINQ .................... 621
Chapter 18 • Drawing and Painting with Visual Basic 2008 ................... 649
Chapter 19 • Manipulating Images and Bitmaps ........................... 693
Chapter 20 • Printing with Visual Basic 2008 .............................. 717Petroutsos f?rs.tex V3 - 01/28/2008 6:03pm Page iii
MasteringMicrosoft
Visual Basic 2008
Evangelos Petroutsos
Mark Ridgeway
Wiley Publishing, Inc.Petroutsos f?rs.tex V3 - 01/28/2008 6:03pm Page iiPetroutsos f?rs.tex V3 - 01/28/2008 6:03pm Page i
MasteringMicrosoft
Visual Basic 2008Petroutsos f?rs.tex V3 - 01/28/2008 6:03pm Page iiPetroutsos f?rs.tex V3 - 01/28/2008 6:03pm Page iii
MasteringMicrosoft
Visual Basic 2008
Evangelos Petroutsos
Mark Ridgeway
Wiley Publishing, Inc.Petroutsos f?rs.tex V3 - 01/28/2008 6:03pm Page iv
Acquisitions Editor: Thomas Cirtin
Development Editor: Toni Zaccarini Ackley
Technical Editor: John Mueller
Production Editor: Daniel Scribner
Copy Editor: Sharon Wilkey
Production Manager: Tim Tate
Vice President and Executive Group Publisher: Richard Swadley
Vice President and Executive Publisher: Joseph B. Wikert
Vice President and Publisher: Neil Edde
Book Designer: Maureen Forys and Judy Fung
Proofreader: Nancy Riddiough
Indexer: Ron Strauss
Cover Designer: Ryan Sneed
Cover Image: Pete Gardner / Digital Vision / Getty Images
Copyright © 2008 by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN: 978-0-4701-8742-5
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic,
mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States
Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate
per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750–8400, fax (978) 646–8600.
Requests to the Publisher for permission should be addressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint
Blvd., Indianapolis, IN 46256, (317) 572–3447, fax (317) 572–4355, or online at 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 speci?cally disclaim all warranties, including without limitation
warranties of ?tness for a particular purpose. No warranty may be created or extended by sales or promotional materials. The advice
and strategies contained herein may not be suitable for every situation. This work is sold with the understanding that the publisher
is not engaged in rendering legal, accounting, or other professional services. If professional assistance is required, the services of a
competent professional person should be sought. Neither the publisher nor the author shall be liable for damages arising herefrom.
The fact that an organization or Website is referred to in this work as a citation and/or a potential source of further information does
not mean that the author or the publisher endorses the information the organization or Website may provide or recommendations it
may make. Further, readers should be aware that Internet Websites listed in this work may have changed or disappeared between
when this work was written and when it is read.
For general information on our other products and services or to obtain technical support, please contact our Customer Care
Department within the U.S. at (800) 762–2974, outside the U.S. at (317) 572–3993 or fax (317) 572–4002.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic
books.
Library of Congress Cataloging-in-Publication Data
Petroutsos, Evangelos.
Mastering Microsoft Visual basic 2008 / Evangelos Petroutsos. — 1st ed.
p. cm.
ISBN 978-0-470-18742-5 (paper/website)
1. Microsoft Visual BASIC. 2. BASIC (Computer program language) I. Title.
QA76.73.B3P492285 2008
005.2
762 — dc22
2007051637
TRADEMARKS: Wiley, the Wiley logo, and the Sybex logo are trademarks or registered trademarks of John Wiley & Sons, Inc.
and/or its af?liates, 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.
10987654321Petroutsos f?rs.tex V3 - 01/28/2008 6:03pm Page v
Dear Reader,
Thank you for choosing Mastering Microsoft Visual Basic 2008. This book is part of a family of
premium quality Sybex books, all written by outstanding authors who combine practical experi-
ence with a gift for teaching.
Sybex was founded in 1976. More than thirty years later, we’re still committed to producing
consistently exceptional books. With each of our titles we’re working hard to set a new standard
for the industry. From the paper we print on, to the authors we work with, our goal is to bring you
the best books available.
I hope you see all that re?ected 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 WileyPetroutsos f?rs.tex V3 - 01/28/2008 6:03pm Page viPetroutsos f?rs.tex V3 - 01/28/2008 6:03pm Page vii
To my dearest and most precious ones, Nefeli
and Eleni-Myrsini.Petroutsos f?rs.tex V3 - 01/28/2008 6:03pm Page viiiPetroutsos fack.tex V3 - 01/28/2008 6:06pm Page ix
Acknowledgments
Many people contributed to this book, and I would like to thank themall. I ?rst want to expressmy
deep appreciation to Mark Ridgeway for contributing the Web-related chapters (Chapters 25, 26,
and 27) and Chapter 5, ‘‘The Vista Interface,’’ and to JohnMueller for providing the technical edit of
this book. Iwant to thank the programmers atMicrosoft for their commitment toVisual Basic.Visual
Basic has evolved froma small, limited programming environment to a ?rst-class development tool
for building all types ofWindows andWeb applications, fromsmall 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 talentPetroutsos fack.tex V3 - 01/28/2008 6:06pm Page xPetroutsos fauth.tex V3 - 01/28/2008 6:11pm Page xi
About the Author
Evangelos Petroutsos works as a consultant on medium to large projects, teaches, and writes
articles — but he mostly writes code, VB code. He specializes in VB and SQL, and from the new
technologies, he fancies XML. He has authored many articles and more than 10 programming
books, including the best-selling titles Mastering Microsoft Visual Basic 2005 and Mastering Visual
Basic .NET Database Programming, both published by Sybex.Petroutsos fauth.tex V3 - 01/28/2008 6:11pm Page xiiPetroutsos ftoc.tex V2 - 01/28/2008 6:12pm Page xiv
xiv CONTENTS AT A GLANCE
Chapter 21 • Basic Concepts of Relational Databases ........................ 753
Chapter 22 • Programming with ADO.NET ............................... 805
Chapter 23 • Building Data-Bound Applications ........................... 845
Chapter 24 • Advanced DataSet Operations .............................. 885
Chapter 25 • Building Web Applications ................................. 901
Chapter 26 • ASP.NET 3.5 ............................................ 937
Chapter 27 • ASP.NET Web Services .................................... 981
Appendix A • ’’The Bottom Line’’ ...................................... 997
Appendix B • ’’Debugging and Error Handling’’ .......................... 1045
Index ............................................................. 1075Petroutsos ftoc.tex V2 - 01/28/2008 6:12pm Page xv
Contents
Introduction ........................................................ xxix
Chapter 1 • Getting Started with Visual Basic 2008 .................... 1
Exploring the Integrated Development Environment ........................... 1
The Start Page ....................................................... 2
Starting a New Project ................................................ 3
Using the Windows Form Designer ...................................... 5
Creating Your First VB Application ....................................... 11
Making the Application More User-Friendly .............................. 15
Understanding the IDE Components ...................................... 18
The IDE Menu ...................................................... 18
ToolboxWindow ................................................... 23
Solution Explorer Window ............................................ 23
Properties Window .................................................. 23
Output Window .................................................... 24
Command and Immediate Windows .................................... 24
Error List Window .................................................. 25
Setting Environment Options ............................................ 25
Building a Console Application ........................................... 27
Using Code Snippets ................................................... 29
Using the My Object ................................................... 30
The Bottom Line ...................................................... 33
Chapter 2 • Variables and Data Types ............................ 35
Variables ............................................................ 35
Declaring Variables .................................................. 36
Types of Variables .................................................. 39
The Strict, Explicit, and Infer Options ................................... 54
Object Variables .................................................... 58
VariablesasObjects .................................................... 60
Converting Variable Types ............................................ 61
Formatting Numbers ................................................ 64
User-De?ned Data Types ............................................. 66
Examining Variable Types ............................................ 69
Why Declare Variables? .............................................. 71
AVariable’sScope .................................................. 71
A Variable’s Lifetime ................................................ 73
Constants ............................................................ 74Petroutsos ftoc.tex V2 - 01/28/2008 6:12pm Page xvi
xvi CONTENTS
Arrays .............................................................. 75
Declaring Arrays .................................................... 75
Initializing Arrays ................................................... 77
Array Limits ....................................................... 77
Multidimensional Arrays ............................................. 78
Dynamic Arrays .................................................... 81
The Bottom Line ...................................................... 82
Chapter 3 • Programming Fundamentals ......................... 85
Flow-Control Statements ................................................ 85
Decision Statements ................................................. 86
Loop Statements .................................................... 93
Nested Control Structures ............................................ 98
The Exit Statement ................................................. 100
Writing and Using Procedures .......................................... 100
Subroutines ....................................................... 100
Functions ........................................................ 101
Arguments .......................................................... 103
Argument-Passing Mechanisms ....................................... 104
Built-in Functions .................................................. 107
Custom Functions .................................................. 109
Passing Arguments and Returning Values ............................... 111
More Types of Function Return Values ................................. 113
Overloading Functions .............................................. 117
The Bottom Line ..................................................... 121
Chapter 4 • GUI Design and Event-Driven Programming .............. 123
On Designing Windows Applications ..................................... 123
Building a Loan Calculator ............................................. 124
Understanding How the Loan Calculator Application Works ................ 125
Designing the User Interface ......................................... 126
Programming the Loan Application .................................... 129
Validating the Data ................................................. 133
Building a Calculator .................................................. 137
Designing the User Interface ......................................... 137
Programming the MathCalculator ..................................... 139
Using Simple Debugging Tools ....................................... 145
Exception Handling ................................................ 147
The Bottom Line ..................................................... 149
Chapter 5 • The Vista Interface ............................... 151
Introducing XAML ................................................... 151
Introducing the WPF Controls .......................................... 153
Simple ‘‘Hello World’’ WPF Application ................................ 154
Simple Drawing Program ............................................ 156Petroutsos ftoc.tex V2 - 01/28/2008 6:12pm Page xvii
CONTENTS xvii
Data-Binding WPF Controls ............................................ 159
Data-Binding Example 2: Binding to a Database .......................... 164
Creating a WPF Browser Application ..................................... 166
Expression Blend Overview ............................................ 168
The Bottom Line ..................................................... 171
Chapter 6 • BasicWindows 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 7 • Working with Forms .............................. 217
The Appearance of Forms .............................................. 217
Properties of the Form Object ......................................... 218
Placing Controls on Forms ........................................... 223
Setting the TabOrder Property ......................................... 224
VB 2008 at Work: The Contacts Project .................................. 226
Anchoring and Docking ............................................. 229
Splitting Forms into Multiple Panes .................................... 232
The Form’s Events ................................................. 234
Loading and Showing Forms ........................................... 236
The Startup Form .................................................. 237
Controlling One Form from within Another ............................. 238
Forms versus Dialog Boxes ........................................... 240
Building Dynamic Forms at Runtime ..................................... 246
The Form’s Controls Collection ........................................ 247
Creating Event Handlers at Runtime ................................... 253
Designing Menus ..................................................... 255Petroutsos ftoc.tex V2 - 01/28/2008 6:12pm Page xviii
xviii CONTENTS
The Menu Editor ................................................... 255
The ToolStripMenuItem Properties .................................... 257
Manipulating Menus at Runtime ...................................... 260
Iterating a Menu’s Items ............................................. 263
The Bottom Line ..................................................... 265
Chapter 8 • MoreWindows Controls ............................ 267
The Common Dialog Controls ........................................... 267
Using the Common Dialog Controls ................................... 268
The ColorDialog Control ............................................ 270
The FontDialog Control ............................................. 272
The OpenDialog and SaveDialog Controls ............................... 274
The FolderBrowserDialog Control ..................................... 279
The RichTextBox Control ............................................... 283
The RTF Language ................................................. 284
Text Manipulation and Formatting Properties ............................ 286
Methods ......................................................... 289
Advanced Editing Features .......................................... 290
Cutting and Pasting ................................................ 291
Searching in a RichTextBox Control .................................... 291
Handling URLs in the Document ...................................... 292
Displaying a Formatted Directory Listing ............................... 293
VB 2008 at Work: The RTFPad Project .................................. 294
The Bottom Line ..................................................... 302
Chapter 9 • The TreeView and ListView Controls ................... 305
Understanding the ListView, TreeView, and ImageList Controls ............... 305
Tree and List Structures ............................................. 306
The ImageList Control .............................................. 309
The TreeView Control ................................................. 310
Adding Nodes at Design Time ........................................ 312
Adding Nodes at Runtime ........................................... 313
VB 2008 at Work: The TreeViewDemo Project ............................ 316
VB 2008 at Work: The Globe Project .................................... 320
Scanning the TreeView Control ....................................... 328
The ListView Control ................................................. 330
The Columns Collection .............................................. 332
ListView Items and Subitems ......................................... 334
The Items Collection ................................................ 336
The SubItems Collection ............................................. 336
VB 2008 at Work: The ListViewDemo Project ............................ 337
Sorting the ListView Control ......................................... 340
Processing Selected Items ............................................ 342
VB 2008 at Work: The CustomExplorer Project ........................... 343
Additional Topics .................................................. 346
The Bottom Line ..................................................... 347Petroutsos ftoc.tex V2 - 01/28/2008 6:12pm Page xix
CONTENTS xix
Chapter 10 • Building Custom Classes ........................... 349
Classes and Objects ................................................... 349
What Is a Class? ...................................................... 350
Classes Combine Code with Data ...................................... 351
Building the Minimal Class ............................................. 352
Adding Code to the Minimal Class .................................... 355
Using Property Procedures ........................................... 356
Customizing Default Members ........................................ 362
Custom Enumerations .............................................. 366
Object Constructors ................................................ 375
Using the SimpleClass in Other Projects ................................ 376
Firing Events ...................................................... 378
Instance and Shared Methods ......................................... 380
A ‘‘Real’’ Class ....................................................... 384
Parsing a Filename ................................................. 384
Converting Numbers to Strings ....................................... 385
Operator Overloading ................................................. 388
VB 2008 at Work: The LengthUnits Class ................................ 389
The Bottom Line ..................................................... 394
Chapter 11 • Working with Objects ............................. 395
Issues in Object-Oriented Programming ................................... 395
Classes versus Objects .............................................. 395
Objects versus Object Variables ....................................... 396
Properties versus Fields ............................................. 400
Shared versus Instance Members ...................................... 401
Type Casting ...................................................... 402
Early versus Late Binding ............................................ 403
Discovering a Variable’s Type ........................................ 404
Inheritance .......................................................... 404
How to Apply Inheritance ........................................... 405
Polymorphism ....................................................... 415
Building the Shape Class ............................................ 417
Who Can Inherit What? ................................................ 421
Parent Class Keywords .............................................. 422
Derived Class Keywords ............................................ 422
Parent Class Member Keywords ...................................... 423
Derived Class Member Keyword ...................................... 423
VB 2008 At Work: The InheritanceKeywords Project ....................... 424
MyBase and MyClass ............................................... 425
The Class Diagram Designer ......................................... 427
The Bottom Line ..................................................... 428
Chapter 12 • Building CustomWindows Controls ................... 429
On Designing Windows Controls ........................................ 429
Enhancing Existing Controls ............................................ 430Petroutsos ftoc.tex V2 - 01/28/2008 6:12pm Page xx
xx CONTENTS
Building the FocusedTextBox Control .................................. 431
Building Compound Controls ........................................... 438
VB 2008 at Work: The ColorEdit Control ................................ 439
Building User-Drawn Controls .......................................... 442
VB 2008 at Work: The Label3D Control ................................. 443
Raising Custom Events .............................................. 450
Using the Custom Control in Other Projects ............................. 452
Designing Irregularly Shaped Controls .................................... 453
Customizing List Controls .............................................. 456
Designing Owner-Drawn ListBox Controls .............................. 457
The Bottom Line ..................................................... 459
Chapter 13 • Handling Strings, Characters, and Dates ................ 461
Handling Strings and Characters ........................................ 461
The Char Class .................................................... 462
The String Class ................................................... 464
The StringBuilder Class ............................................. 473
VB 2008 at Work: The StringReversal Project ............................. 476
VB 2008 at Work: The CountWords Project .............................. 479
Handling Dates and Times ............................................. 481
The DateTime Class ................................................ 481
The TimeSpan Class ................................................ 492
The Bottom Line ..................................................... 497
Chapter 14 • Storing Data in Collections ......................... 499
Advanced Array Topics ................................................ 499
Sorting Arrays ..................................................... 499
Searching Arrays .................................................. 502
Performing Other Array Operations ................................... 506
Array Limitations .................................................. 509
The ArrayList Collection ............................................... 509
Creating an ArrayList ............................................... 509
Adding and Removing ArrayList Items ................................. 510
Sorting ArrayLists .................................................. 513
Searching ArrayLists ............................................... 515
Iterating an ArrayList ............................................... 515
The HashTable Collection .............................................. 516
VB 2008 at Work: The WordFrequencies Project .......................... 518
The SortedList Collection .............................................. 523
VB 2008 at Work: The SortedList Project ................................ 524
Other Collections ..................................................... 527
The IEnumerator and IComparer Interfaces ................................ 528
Enumerating Collections ............................................ 528
Custom Sorting .................................................... 531
Generic Collections ................................................... 537
The Bottom Line ..................................................... 539Petroutsos ftoc.tex V2 - 01/28/2008 6:12pm Page xxi
CONTENTS xxi
Chapter 15 • Accessing Folders and Files ......................... 541
The IO Namespace and the FileSystem Component .......................... 541
Using the My.Computer.FileSystem Component ............................ 542
Manipulating Folders and Files with the IO Namespace ...................... 546
The Directory Class ................................................. 547
The File Class ..................................................... 554
Drive, Folder, and File Properties ...................................... 560
The Path Class .................................................... 564
VB 2008 at Work: The CustomExplorer Project ........................... 566
Accessing Files ....................................................... 569
Using Streams ..................................................... 570
VB 2008 at Work: The RecordSave Project ............................... 580
The FileSystemWatcher Component ...................................... 585
Properties ........................................................ 585
Events ........................................................... 586
VB 2008 at Work: The FileSystemWatcher Project ......................... 587
The Bottom Line ..................................................... 589
Chapter 16 • Serialization and XML ............................ 591
Understanding Serialization Types ....................................... 591
Using Binary and SOAP Serialization ..................................... 592
Serializing Individual Objects ......................................... 592
Deserializing Individual Objects ...................................... 594
Serializing Collections .............................................. 595
Deserializing Collections ............................................ 596
Persisting a HashTable ................................................ 598
Persisting a TreeView’s Nodes .......................................... 601
Using XML Serialization ............................................... 607
Serializing and Deserializing Individual Objects .......................... 608
Serializing Custom Objects ........................................... 609
Serializing ArrayLists and HashTables ................................. 613
Working with XML Files ............................................... 615
Understanding XML Structure ........................................ 615
Editing XML Files .................................................. 617
The Bottom Line ..................................................... 620
Chapter 17 • Querying Collections and XML with LINQ ............... 621
What Is LINQ? ....................................................... 621
LINQ Components ................................................. 623
LINQ to Objects ...................................................... 625
Querying Collections ............................................... 627
Aggregating with LINQ ............................................. 630
LINQ to XML ........................................................ 631
Traversing XML Documents .......................................... 633
Adding Dynamic Content to an XML Document .......................... 634
LINQ to SQL ........................................................ 642Petroutsos ftoc.tex V2 - 01/28/2008 6:12pm Page xxii
xxii CONTENTS
Retrieving Data with the ExecuteQuery Method ........................... 646
The Bottom Line ..................................................... 647
Chapter 18 • Drawing and Painting with Visual Basic 2008 ............ 649
Displaying and Sizing Images ........................................... 649
Drawing with GDI+ ................................................... 652
The Basic Drawing Objects ........................................... 654
Drawing Shapes ................................................... 663
Drawing Methods .................................................. 667
Gradients ........................................................ 681
Clipping ......................................................... 685
Applying Transformations ............................................. 687
VB 2008 at Work: The ImageCube Project ............................... 690
VB 2008 at Work: Plotting Functions ................................... 691
The Bottom Line ..................................................... 691
Chapter 19 • Manipulating Images and Bitmaps ................... 693
Specifying Colors ..................................................... 693
The RGB Color Cube ............................................... 694
De?ning Colors .................................................... 695
The Image Object ..................................................... 699
Properties ........................................................ 699
Methods ......................................................... 699
VB 2008 at Work: The Thumbnails Project ............................... 702
Exchanging Images through the Clipboard .............................. 705
The Bitmap Object .................................................... 706
Processing Bitmaps ................................................. 708
VB 2008 at Work: The ImageProcessing Project ........................... 710
The Bottom Line ..................................................... 715
Chapter 20 • Printing with Visual Basic 2008 ...................... 717
The Printing Components .............................................. 717
The PrintDocument Control .......................................... 717
The PrintDialog Control ............................................. 720
The PageSetupDialog Control ........................................ 721
The PrintPreviewDialog Control ...................................... 723
Printer and Page Properties ............................................. 725
Retrieving the Printer Names ......................................... 726
Page Geometry .................................................... 728
VB 2008 at Work: The SimplePrintout Project ............................ 729
VB 2008 at Work: The PageSettings Project .............................. 732
Practical Printing Examples ............................................. 737
Printing Tabular Data ............................................... 738
Printing Plain Text ................................................. 744
Printing Bitmaps ................................................... 748
The Bottom Line ..................................................... 751Petroutsos ftoc.tex V2 - 01/28/2008 6:12pm Page xxiii
CONTENTS xxiii
Chapter 21 • Basic 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 22 • Programming 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 .......................................... 830Petroutsos ftoc.tex V2 - 01/28/2008 6:12pm Page xxiv
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 23 • Building 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 24 • Advanced 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 25 • BuildingWeb 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) ............................................ 911Petroutsos ftoc.tex V2 - 01/28/2008 6:12pm Page xxv
CONTENTS xxv
Formatting Styles with CSS .......................................... 912
Page Formatting with CSS ........................................... 913
JavaScript ........................................................... 916
AJAX ............................................................ 918
Microformats ........................................................ 918
Server-Side Technologies ............................................... 918
Creating a Web Application ............................................ 919
Controls ............................................................ 922
Standard Controls .................................................. 922
Data Controls ..................................................... 924
Validation Controls ................................................. 924
Navigation Controls ................................................ 925
Login Controls .................................................... 925
WebParts Controls ................................................. 926
AJAX Extensions Controls ........................................... 926
Reporting Controls ................................................. 928
HTML Controls .................................................... 928
Maintaining State ..................................................... 929
Master Pages ........................................................ 930
ASP.NET Objects ..................................................... 931
Application Object ................................................. 931
Context Object .................................................... 931
Request Object .................................................... 931
Response Object ................................................... 932
Server Object ...................................................... 932
Session Object ..................................................... 934
Trace Object ...................................................... 934
Postback ............................................................ 935
The Bottom Line ..................................................... 935
Chapter 26 • ASP.NET 3.5 ................................... 937
Planning the Demonstration Site ......................................... 937
Getting Started .................................................... 938
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
Con?guring the Menu Control for MasterPage.master ...................... 955Petroutsos ftoc.tex V2 - 01/28/2008 6:12pm Page xxvi
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 Con?guration of the GridView Control .......................... 971
Building the Computers.aspx Page ......................................... 974
Adding the DropDownList Control .................................... 975
Adding the DetailsView Control ...................................... 976
Further Con?guring the DetailsView Control ............................ 977
Building the Report.aspx page ............................................ 978
Adding the MicrosoftReportViewer Control ............................. 978
Creating the Report ................................................. 978
The Bottom Line ..................................................... 980
Chapter 27 • ASP.NETWeb 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 .......................................... 989Petroutsos ftoc.tex V2 - 01/28/2008 6:12pm Page xxvii
CONTENTS xxvii
Simple AJAX Implementation ........................................... 993
The Bottom Line ..................................................... 995
Appendix A • ............................................ 997
Appendix B • ........................................... 1045
Index .............................................................. 1075Petroutsos ftoc.tex V2 - 01/28/2008 6:12pm Page xxviiiPetroutsos ?ast.tex V3 - 01/28/2008 6:13pm Page xxix
Introduction
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
CreateDirectory method of the Directory class, and to retrieve the ?les in a folder you call the
GetFiles method 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 simpli?es 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 ?x
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. AWindows 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 ?le and folder manipulation, data storage, and so on, you’ll usePetroutsos ?ast.tex V3 - 01/28/2008 6:13pm Page xxx
xxx INTRODUCTION
the appropriate classes of the .NET Framework. A substantial segment of this book deals with the
most useful components of the Framework.
TheMastering 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 ?eld 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 abstract
concepts 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 basic
understanding 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 rich
programming tools, and I had to choose between a super?cial coverage of many topics and an
in-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 ?nd complete project listings or
form 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 you
don’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 principles
and techniques for developing applications with Visual Basic. Programming isn’t about new
keywords and functions. I chose the topics I felt every programmer should learn in order to master
the language. I was also motivated by my desire to present useful, practical examples. You will
not ?nd all topics equally interesting or important. My hope is that everyone will ?nd something
interesting and something of value for his or her daily work— whether it’s an application that
maps the folders and ?les of a drive to a TreeView control, an application that prints tabular
data, a data-driven application for editing customers or products, or an application that saves a
collection of objects to a ?le.
Many books offer their readers long, numbered sequences of steps to accomplish a task. Follow-
ing instructions simpli?es certain tasks, but programming isn’t about following instructions. It’s
about 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 language
such as Visual Basic 2008 is to understand its principles and its programming model.
In many cases, I provide a detailed, step-by-step procedure that will help you accomplish a
task, 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 connectPetroutsos ?ast.tex V3 - 01/28/2008 6:13pm Page xxxi
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 youmaster the basics of programmingWindows applications
with Visual Basic 2008 and you feel comfortable with the more advanced examples of the book,
you will ?nd it easy to catch up with the topics not discussed in this book. Of course, you will ?nd
information about the latest data access techniques,aswellasanintroductiontoLINQ(Language
Integrated Query), which is the hottest new component of the Framework.
Howabout theAdvanced 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 ?nd some examples to be more dif?cult 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 ?nd information about the File and
Directory objects. You can use these objects to access and manipulate the ?le 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 ?les 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 ?nd some material to be over your head at ?rst 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 ?les? 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 withPetroutsos ?ast.tex V3 - 01/28/2008 6:13pm Page xxxii
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 discuss
and 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 read
computer books this way. Each chapter is independent of the others, although all chapters contain
references to other chapters. Each topic is covered in depth; however, I make no assumptions
about the reader’s knowledge of the topic. As a result, you may ?nd the introductory sections
of a chapter too simple. The topics become progressively more advanced, and even experienced
programmers will ?nd some new information in most chapters. Even if you are familiar with
the topics in a chapter, take a look at the examples. I have tried to simplify many of the advanced
topics and demonstrate them with clear, practical examples.
This book tries to teach through examples. Isolated topics are demonstrated with short
examples, and at the end of many chapters you’ll build a large, practical application (a real-world
application) that ‘‘puts together’’ the topics and techniques discussed throughout the chapter.
You may ?nd some of the more advanced applications a bit more dif?cult to understand, but you
shouldn’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 design
visual interfaces with point-and-click operations and how to program a few simple events, such as
the click of the mouse on a button. After reading the ?rst two chapters, you’ll understand the
structure of a Windows application. Then you’ll explore the elements of the visual interface
(the basicWindows controls) and how to program them. You’ll also learn about theMy object and
code snippets, two features that make Visual Basic so simple and fun to use. These two objects will
also 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 most
common controls you’ll use in building Windows forms in detail, as well as how to work with
forms: how to design forms, how to design menus for your forms, how to create applications with
multiple forms, and so on. You will ?nd 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, in
your 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 and
more 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 learn
about inheritance and will see how easy it is to add custom functionality to existing classes
through inheritance.
The following few chapters deal with some of the most common classes of the .NET
Framework. 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 next
version of Windows. You’ll examine several extremely interesting topics such as collections (for
example, ArrayLists and HashTables), the classes for manipulating ?les and folders, the String-
Builder class that manipulates text, XML serialization, and a few more, including the Language
Integrated Query component (LINQ, which is brand new to the latest version of the Framework).
Then you will ?nd a few chapters on graphics. You’ll learn how to use the classes of the
Framework that generate graphics, and you’ll learn how to create vector drawings as well asPetroutsos ?ast.tex V3 - 01/28/2008 6:13pm Page xxxiii
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 ?rst twenty chapters deal with the fundamentals of the language and Windows applica-
tions. Following these chapters, you will ?nd 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 ?nd 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 andprojects canbedownloadedfromthe Sybexwebsite (www.sybex.com).
At the main page, you can ?nd 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 ?le, 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 ?x 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 ?x 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.Petroutsos ?ast.tex V3 - 01/28/2008 6:13pm Page xxxivPetroutsos c01.tex V2 - 01/28/2008 11:43am Page 1 

Make a Free Website with Yola.