karl moore's visual basic .net: the tutorials978-1-4302-1153-2/1.pdfkarl moore's visual...
TRANSCRIPT
Karl Moore's Visual Basic .NET:
The Tutorials KARL MOORE
APress Media, LLC
Karl Moore's Visual Basic .NET: The Tutorials Copyright © 2002 by Karl Moore Originally published by Apress in 2002
All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher.
ISBN 978-1-59059-021-8 ISBN 978-1-4302-1153-2 (eBook) DOI 10.1007/978-1-4302-1153-2
Trademarked names may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, we use the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark.
Technical Reviewers: Patricia Moore, Richard Costall, Ray Ellison, Erik Giggey, Donald Carter Editorial Directors: Steve Anglin, Dan Appleman, Ewan Buckingham, Gary Cornell, Tony Davis,
Iason Gilmore, Dominic Shakeshaft, Iim Sumser, Karen Watterson, Iohn Zukowski Managing Editor: Grace Wong Project Manager: Alexa Stuart Copy Editor: Tom Gillen Production Editors: IanetVail and Grace Wong Compositor: Impressions Book and Iournal Services, Inc. Indexer: Ann Rogers Cover Designer: Tom Debolski Marketing Manager: Stephanie Rodriguez
The information in this book is distributed on an "as is" hasis, without warranty. Although every precaution has been taken in the preparation of this work, neither the author nor Apress shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in this work.
Dedicated to my loving family: David, Patricia, and]o-Anne.
Oh, and my brain-without whom none of this would've been possible.
Brief Contents
Foreword ............................................................. . xiii
About the Author .................................................... . xv
About This Book .................................................... . xvii
Tutorial 1: Beginning VB . NET ................................ . I
1.1 Programming, Visual Basic, and Everything .................. . 3
1. 2 Exploring Controls and Making Decisions ................... .23
1. 3 Variables and the Coolest Code .............................. . 51
1. 4 Menus, Methods, Modules, and Multiple Forms ............... 71
1. 5 Errors, Setup, and Going from Here ......................... . 95
Tutorial 2: Doing Databases ................................ . 117
2.1 Introducing Databases ....................................... . 119
2. 2 Our Own Database and VB . NET ............................... . 137
2. 3 Doing It Completely in Code ................................ . 165
2.4 SQL Server, Web Applications, Transactions ••• Oh My! ..... 189
2. 5 Designing Reports and Going from Here .................... . 219
Tutorial 3: Working the Web ................................ . 241
3.1 The ASP. NET Revolution ...................................... . 243
3.2 Ten Top Code Snippets You Can't Live Without ............ . 277
3. 3 Authentication, Tips, Distribution, and More ............ . 293
v
Brief Contents
Tutorial 4: Going Mobile ..................................... . 319
4.1 Introducing the Mobile Internet Toolkit .................. . 321
4.2 Your Device, Filters, Images, Memory, and More .......... . 343
Tutorial 5: Using Objects .................................. .. 367
5.1 Why Objects Are Important .................................. .. 369
5.2 Objects in Real Life, Class Libraries, and More ........ .. 391
Tutorial 6: Services Rendered .............................. .417
6.1 Introducing the World of Web Services .................... .419
Tutorial 7: From VB6 to . NET ............................... .445
7.1 All the Changes, Quickly .................................... .447
Tutorial 8: Tips and Techinques ........................... .475
8.1 Beginner Tips and Techniques ............................... .477
8. 2 Intermediate Tips and Techniques .......................... .487
8.3 Advanced Tips and Techniques .............................. .. 505
Appendixes ........................................................ . 531
Appendix A Installing Visual Studio • NET ...................... . 533
Appendix B Project Defaults .................................... .. 536
Appendix C Standard Naming Conventions ........................ . 542
Appendix D Windows Form Controls .............................. .. 545
Appendix E VB • NET Data Types .................................. .. 548
Appendix F SQL Server Data Types .............................. .. 550
Index ................................................................ . 553
vi
Contents
Foreword ............................................................. . xiii
About the Author .................................................... . xv
About This Book .................................................... . xvii
Tutorial 1 Beginning VB . NET ........................ . 1
1.1 Programming, Visual Basic, and Everything ..... . 3
What Is VB . NET? .................................................... .4
Creating Your First Program ....................................... . 5
Conclusion .......................................................... . 19 Review Sheet ........................................................ . 21
1. 2 Exploring Controls and Making Decisions ....... .23
Exploring Controls ................................................. .23 Responding to Events .............................................. . 27
The Top Ten Controls .............................................. .29 Bringing It All Together .......................................... . 38
Making Decisions ................................................... .44 Conclusion .......................................................... . 46
Review Sheet ........................................................ . 49
1. 3 Variables and the Coolest Code ................... .. 51
Using Variables .................................................... . 51
Time for a Test .................................................... . 56 And Now, the Cool Stuff! .......................................... . 57 Conclusion .......................................................... . 67
Review Sheet ........................................................ . 69
vii
Contents
1.4 Menus, Methods, Modules, and Multiple Forms ............................................ . 71
Expanding with Menus .............................................. . 71
Expanding with Forms ............................................... 77 Expanding with Methods ............................................ . 81
Expanding with Functions .......................................... . 83
Methods, Modules, Mayhem-oh My! ................................. . 89
Conclusion .......................................................... . 92
Review Sheet ........................................................ . 93
1. 5 Errors, Setup, and Going from Here .............. . 95
Handling the Errors ............................................... . 95
Distributing Your Program ....................................... . 100
FAQ ................................................................. . 108
Where to Go from Here ............................................ . 111
Conclusion ......................................................... . 113
Review Sheet ....................................................... . 115
Tutorial 2 Doing Databases ........................ .. 117
2.1 Introducing Databases ................................ . 119
What Are Databases? .............................................. . 120
Choices, Choices .................................................. . 122
Exploring Northwind .............................................. . 122
Doing the Data Bind .............................................. . 126
Conclusion ......................................................... . 134
Review Sheet ........................................................ . 136
2. 2 Our Own Database and VB . NET ...................... . 137
Creating Our Own Database ....................................... . 137 Adding Relationships ............................................. . 141
Binding to a Windows Form ....................................... . 145
Binding on the Web ................................................ . 154
Using the Wizards ................................................. . 159
Conclusion ......................................................... . 161
Review Sheet ........................................................ . 163
viii
Contents
2. 3 Doing It Completely in Code ........................ . 165
Talking the Talk .................................................. . 165
Cheating at SQL ................................................... . 170
Accessing in Code ................................................. . 171
Our Completely-in-Code Program ................................. . 172
Expanding with Relationships .................................... . 181
Conclusion ......................................................... . 186
Review Sheet ........................................................ . 187
2.4 SQL Server, Web Applications, Transactions . .. Oh My! ...................................... . 189
Joining the Big Boys ............................................. . 189
Creating a Server Database ...................................... . 191
Creating a Transactional Database-Powered Web Application ............................................... . 200
And for My Next Trick ... Transactions! ......................... .210
Conclusion ......................................................... . 215
Review Sheet ........................................................ . 217
2. 5 Designing Reports and Going from Here ......... . 219
Reporting with Crystal ........................................... . 219
FAQ ................................................................. . 232 Where to Go from Here ............................................ .236
Conclusion ......................................................... . 237
Review Sheet ........................................................ . 139
Tutorial 3 Working the Web ......................... . 241
3 .1 The ASP. NET Revolution ............................... . 243
How It All Works .................................................. .244
Creating Your First Site ........................................ . 244
Getting Bigger and Better ....................................... .248
The Greatest Controls Ever Sold ................................ . 258
Conclusion ......................................................... . 272
Review Sheet ........................................................ . 273
ix
Contents
3.2 Ten Top Code Snippets You Can't Live Without ................................................... . 277
The Top Ten List .................................................. . 277 Quiz Time .......................................................... . 288
Conclusion ......................................................... . 290
Review Sheet ........................................................ . 291
3.3 Authentication, Tips, Distribution, and More ..................................... .293
Securing Your Sites .............................................. .293
Improving Your Site .............................................. . 303
Deployment ......................................................... . 309
FAQ ................................................................. . 311
Conclusion ......................................................... . 315
Review Sheet ........................................................ . 317
Tutorial 4 Going Mobile .............................. . 319
4.1 Introducing the Mobile Internet Toolkit ...... . 321
How Does It Work? ................................................. . 322 Creating Our First Mobile Application ......................... . 323
Exploring the Controls ........................................... . 330
I'm Playing Around ................................................ . 339
Conclusion ......................................................... . 340
Review Sheet ........................................................ . 341
4.2 Your Device, Filters, Images, Memory, and More ............................................. . 343
Finding Out about Your Device ................................... . 343
A Word about Filters ............................................. . 348
Displaying Images, Using Filters ............................... . 354
Do You Remember? .................................................. . 358
FAQ ................................................................. . 360
Conclusion ......................................................... . 363
Review Sheet ........................................................ . 365
X
Contents
Tutorial 5 Using Objects ........................... .. 367
5.1 Why Objects Are Important .......................... . 369
What Are Objects? ................................................. . 369
Starting Small .................................................... . 372 Adding Properties ................................................. . 376
Bettering Properties ............................................. . 378
Methods, Functions, Parameters-Oh My! ......................... . 382
Events .............................................................. . 383 Going Further ...................................................... . 386
Conclusion ......................................................... . 387
Review Sheet ........................................................ . 389
5.2 Objects in Real Life, Class Libraries, and More ......................................................... . 391
Creating a Customers Class ...................................... . 391
Adding a Test Project ............................................ . 397
Time for a Chat ................................................... . 401
Distributing Your DLL ............................................ .404
FAQ ................................................................. .405 Conclusion ......................................................... . 412
Review Sheet ........................................................ . 413
Tutorial 6 Services Rendered ..................... .417
6.1 Introducing the World of Web Services ......... .419
How It All Works .................................................. .419
Creating a Web Service ........................................... . 422
Imagining the Possibilities ..................................... . 429
Passing Smart Data ................................................ .430
The Top Five Distribution Tips ................................. .435
Deploying Your Web Service ...................................... .437
FAQ ................................................................. . 438
Where to Go from Here ............................................ .440 Conclusion ......................................................... . 441
Review Sheet ........................................................ . 443
xi
Contents
Tutorial 1 From VB6 to . NET ....................... .445
7.1 All The Changes, Quickly ............................ .447
What is • NET? ...................................................... . 447
Introducing Visual Studio . NET ................................. .450
How Your Code Changes ............................................ .456
They're Objects, Jim ••........................................... .462
Getting It Out .................................................... . 471
Upgrading Your Existing Applications .......................... .472
Where to Go from Here ............................................ .472
Conclusion ......................................................... . 474
Tutorial 8 Tips and Techniques .................. .475
8.1 Beginner Tips and Techniques ...................... .477
Making Your Form Transparent .................................... .478
Snapping to the Grid ............................................. .478
Resizing Controls at Runtime .................................... .478
Adding Menus to Your Program .................................... .479
Changing Your Window State ...................................... .479
Adding the With Keyword .......................................... .479
Using Visual Inheritance ........................................ .480
Typing the TODO: Statement ...................................... .480
Setting a Site Home page .......................................... .480
Adding Smart Navigation to Web Forms .......................... .481
Changing the Tab Order .......................................... .. 481
Generating Random Numbers ........................................ .481
Exiting Your Code ................................................. .482
Customizing the Cursor ........................................... .482
Using Special Code Characters ................................... .482
Creating a Number-Only Text Box ................................ .483
Reversing a String ................................................ .484
Rounding a Number ................................................. .484
Replacing Text the Easy Way .................................... .. 484
Listing and Setting Fonts ....................................... .485
Trimming a String ................................................. .485
Ending Your Application .......................................... .486
Retrieving a Number Using Val ................................... .486
Resetting the Windows ............................................ .486
Capitalizing Your Characters .................................... .486
xii
8. 2 Intermediate Tips and Techniques ................ .487
Finding the Application Directory .............................. .488
Formatting Dates .................................................. .488
Exploring the Command Window .................................... .490
Creating an MDI Application ..................................... .490
Adding Toolbars ................................................... .491
Reading an XML File .............................................. .492
Using DataSets and XML ........................................... .494
Creating Your Own Icons .......................................... .495
Reading and Writing to Files .................................... .495
Finding the Last Day of the Month .............................. .496
Using the Handles Keyword ....................................... .497
Converting Text to Proper Case ................................. .498
Storing to the Clipboard ........................................ .498
Working with Files ................................................ .498
Highlighting Form Errors ........................................ .499
Using the IIF Function ........................................... . 500
Validating an Email Address ..................................... . 500
Resetting a Form .................................................. . 503
8. 3 Advanced Tips and Techniques ...................... . 505
Introducing the VS. NET Command Prompt ......................... . 506
Using Keywords in Your Code ..................................... . 506
Declaring Static Variables ...................................... . 507
Checking for a Leap Year ........................................ . 507
Creating a GUID ................................................... . 507
Generating OLE DB Strings with Ease ........................... . 508
Checking for a Whole Number .................................... .. 509
Read the Command Line Parameters ............................... . 509
Getting Special Folder Locations ............................... . 510
Checking for a Previous Instance ............................... . 510
Saving to the Registry ........................................... . 511
Using COM Objects ................................................. . 512
Turning a Recordset into a DataSet ............................ .. 513
Exposing .NET to the COM World ................................ .. 513
Storing Often-Used Code .......................................... . 514
Saving Time with Macros ......................................... .. 514
Using Simple Encryption .......................................... . 514
Encrypting a File ................................................. . 516
Generating Memorable Passwords ................................. . 519
Printing from Your Program ...................................... . 520
xiii
Contents
Creating and Sorting Arrays ..................................... . 523
Using the Special Array Functions .............................. . 526
Collections in • NET .............................................. . 527
Finding MTS and MSMQ ............................................. . 528
Fine-Tuning Your ASP. NET Applications ......................... . 529
Appendixes .................................................... . 531
Appendix A Installing Visual Studio • NET .......... . 533
Appendix B Project Defaults ............................ .. 536
Appendix C Standard Naming Conventions ............. . 542
Appendix D Windows Form Controls ...................... . 545
Appendix E VB • NET Data Types .......................... . 548
Appendix F SQL Server Data Types ...................... . 550
Index ............................................................... . 553
xiv
Foreword
"The man who has no imagination has no wings."-MuhammadAli
NOT EVERYTHING IN LIFE IS EASY.
Nuclear physics. Advanced trigonometry. The Welsh language. Pushing a twenty-ton truck up a hill using your left pinkie. That's not easy.
But some things definitely are. Like programming, say. The problem is, if you've ever tried to learn how to program, you'll know most
of the books out there are about as exciting as Bill Gates' cardigan collection. They're full of annoying acronyms and confusing concepts. On every other page, they stick whopping great big tables containing "keywords to remember."
Yeah, like that's going to happen. When I decided to teach programming online some years ago, I decided to go
against the flow. I decided to use what I knew about the learning process to help my readers understand concepts quicker and to actually enjoy the whole process.
I wrote in plain English. I constantly linked new concepts back to stuff each reader already knew. I presented the big picture and kept asking questions. I regularly presented review sheets. I explained geek speak. I held the users' hands at first, pointed out potential pitfalls, then let each individual fly.
It worked, and the response blew me away. Thankfully, I managed to catch a plane back-and began writing the book
you're holding right now, all about the new .NET technologies. And this baby
works in just the same way as my online tutorials, only better. My mum is so proud. This book is split into eight separate tutorials, each of which teaches a real
to-life area of programming. From databases to the Web, it's all here, and each tutorial will turn you into a real guru, with suggestions as to how you can take your knowledge even further.
So, let's prepare to enter the nerd world. Grow a beard and apply a little EOand remember, don't worry and don't memorize. Just play and have fun!
Thank you for learning with me. Karl Moore, Apri/2002
XV
About the Author
KARL MooRE Is A TECHNOLOGY AUTHOR living in Yorkshire, England. He runs his own consultancy group, White Cliff Computing Ltd., and is senior editor behind the popular development site, VB-World. When he's not writing for magazines, speaking at conferences, or making embarrassing mistakes on live radio, Karl enjoys a complete lack of a social life.
Karl says his life goals include climbing out of bed, reaching the high notes in "Loving You", and learning to speak in hieroglyphics.
You can visit Karl on the Web at www. kar lmoore. com or email him at [email protected].
xvii
Acknowledgments
When I first plotted this book on a train home from Cardiff Central last year, I hadn't planned on including an Acknowledgments section. In fact, I'd only planned on three individual tutorials, one that never made it, and six extra that did.
But Acknowledgments? Hah, it was just me and my trusty fake-leather organizer. How very wrong I was. I've learned in the past months that writing a book is
a true culmination of efforts-and to all the people who have helped, I'd like to extend my sincere thanks.
First and foremost, thanks go to Tricia Moore, a family member and technical reviewer, for her patience and coordination skills-and for being one of the few people who didn't mind knocking me off my horse when things didn't work. Big appreciation also goes to project manager Alexa Stuart, who always managed to get me back on it.
Thanks to Tom Gillen, my editor, for recognizing that most of my best jokes were libelous and removing them before the lawyers did. Kudos to you, intelligent man. Also, my appreciation goes out to Grace Wong, who encountered all those last-minute typesetting hurdles-and survived. Plus I raise my hat to the best marketing queen of all, Stephanie Rodriguez.
Of course, the Apress editorial directors also need mentioning, not as a matter of course, but because they're real people. First and foremost, Dan Appleman, who kept me entertained with readers' stories in London and has since regretted ever giving me his e-mail address; Gary Cornell, whom I shared an ice cream with in Barcelona and who convinced me that VB6 books were a dying breed back in the year 2000; and Karen Watterson, who provided much-needed moral support and now has her electricity back.
A big thanks also goes out to Mark and Katrina, the BBC pals who constantly remind me sleep is actually good for you. Also, the team behind my own company, White Cliff, deserves a round of applause for their initiative and bright thinking-they're the people who continued to earn me a salary during the months I couldn't.
And, of course, the people who actually inspired the book: those who read my online scribblings and prompted me to go one step further. From the African King with an interest in programming, to the recently released Australian convict taking a long overdue career move, to Jenny in Auckland who has just passed her programming class with flying colors-you are the people who kept me burning the candle well into the midnight hours. Thank you.
Finally, to the most important people of all: Mum, Dad, and Jo-Anne. It is to these three I owe my life.
xix
About This Book
THIS BOOK IS SPLIT INTO EIGHT SEPARATE TUTORIALS, each designed tO get you Up tO speed with a different area of the .NET world:
'futoriall, "Beginning VB .NET": Who puts the fun into programming fundamentals? If you're new to VB .NET, this is your starting block. This five-chapter tutorial will provide you with a thorough grounding in programming with your soon-to-be favorite language. Covering everything from painting a form to error handling.
'futorial2, "Doing Databases": In the real world, databases are essential. This five-chapter tutorial is your ultimate survival guide, covering everything from creating your own simple Access database through to writing your own transactional SQL Server-powered transactional Web application. Corr blimey, miss us.
'futorial3, "Working the Web": No matter how little Internet experience you have, this three-chapter ASP. NET tutorial will show you how to create your own fully interactive, advanced Web sites in minutes. Covering everything from Web controls to user authentication.
'futorial4, "Going Mobile": Fancy writing applications that can run on anything from your cell phone to that wired microwave? Get your VB .NET code talking in the language of mobile devices, with the free Mobile Internet Toolkit and this two-chapter lifesaver. A real eye-opener.
'futorial5, "Using Objects": Create better, more-maintainable, bug-free applications, quicker, by using object -oriented programming techniques. This two-chapter tutorial gives you the full lowdown on how using classes can really improve both your code and salary.
'futorial6, "Services Rendered": It's DCOM on a longer wire, it's a groovy way of getting computers talking to each other, it's a cross-platform XMLbased communication method. It's cool, it's Web Services, and this single-chapter tutorial shows you how to get your own up and running within half an hour.
'futorial7, "From VB6 to .NET": If you've just moved to the world of .NET from Visual Basic 6, you need to get your head around a few changes. This
xxi
About This Book
xxii
one-chapter overview provides a quick rundown of the differences, plus advice on where to go from here.
Tutorial8, "Tips and Techniques": Split into Beginner, Intermediate, and Advanced chapters, this part provides reams of ready-to-run solutions to some of the most common .NET programming tasks. Whether you want to print from your program or generate OLE DB strings with ease, this nifty collection is a complete must-read for all developers.
Appendixes: Installing Visual Studio .NET, Project Defaults, Standard Naming Conventions, Windows Form Controls, VB .NET Data Types, and SQL Server Data Types.
If you're new to programming, it's recommended that you start with Thtoriall, "Beginning VB .NET", and then read through each tutorial sequentially. Every chapter builds upon the knowledge you acquired in the last. Also, ensure that you read the Review Sheets at the end of each chapter to help solidify your knowledge base.
If you have programmed in a previous version ofVisual Basic, start with Tutorial 7, "From VB6 to .NET", which should give you a grasp of changes in the new programming platform. After this, read the Review Sheets at the end of each chapter in Thtoriall "Beginning VB .NET", to ensure that you really grasp the key concepts. Once you've gotten an overview of the differences, start selectively reading the tutorials that interest you. Each includes special references for those coming from VB6.
Users of all levels will find it enormously beneficial to spend time browsing all the code samples in the three chapters ofThtorial8, "Tips and Techniques". They demonstrate real code in action and should help you grasp many of the techniques shown throughout the book.
Good luck!