Visual Basic 2017 Made Easy and Excel VBA Made Easy Dr Liew's Visual Basic 6 is a user-friendly programming language designed for beginners It You can download the free version of Visual Studio 2019 from the following link:
Visual Studio is free for learning and individual use. First please make sure to download and install the latest version of Visual Studio. You can save installation time and disk space by selecting just the components needed. You can always incrementally add more components later at any time as needed.
visual basic for dummies pdf free download
Excel Data Analysis For Dummies, 2nd Edition is the ultimate guide to getting the most out of your data. Veteran Dummies author Stephen L. Nelson guides you through the basic and not-so-basic features of Excel to help you discover the gems hidden in your rough data. From input, to analysis, to visualization, the book walks you through the...
2. Visual Basic 2008FORDUMmIESby Bill Sempf 3. Visual Basic 2008For DummiesPublished byWiley Publishing, Inc.111 RiverStreetHoboken, NJ 07030-5774www.wiley.comCopyright 2008 by WileyPublishing, Inc., Indianapolis, IndianaPublished by WileyPublishing, Inc., Indianapolis, IndianaPublished simultaneously inCanadaNo part of this publication may be reproduced, stored in aretrieval system or transmitted in any form orby any means,electronic, mechanical, photocopying, recording, scanning orotherwise, except as permit-tedunder Sections 107 or 108 of the1976 United States Copyright Act, without either the priorwrittenpermission of the Publisher, or authorization throughpayment of the appropriate per-copy fee to theCopyright ClearanceCenter, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax(978) 646-8600.Requests to the Publisher for permission should beaddressed to the Legal Department, Wiley Publishing,Inc., 10475Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317)572-4355, or onlineat : Wiley, the WileyPublishing logo, For Dummies, the Dummies Man logo, A Reference fortheRest of Us!, The Dummies Way, Dummies Daily, The Fun and EasyWay, Dummies.com, and related tradedress are trademarks orregistered trademarks of John Wiley & Sons, Inc. and/or itsaffiliates in the UnitedStates and other countries, and may not beused without written permission. Visual Basic and Visual Studioareregistered trademarks of Microsoft Corporation in the United Statesand/or other countries. All othertrademarks are the property oftheir respective owners. Wiley Publishing, Inc., is not associatedwith anyproduct or vendor mentioned in this book.LIMIT OFLIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKENO REP-RESENTATIONSOR WARRANTIES WITH RESPECT TO THE ACCURACY ORCOMPLETENESS OF THE CON-TENTSOF THIS WORK AND SPECIFICALLY DISCLAIMALL WARRANTIES, INCLUDING WITHOUTLIMITATION WARRANTIES OF FITNESSFOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CRE-ATEDOR EXTENDED BYSALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIESCON-TAINEDHEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORKIS SOLD WITH THEUNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED INRENDERING LEGAL, ACCOUNTING, OROTHER PROFESSIONAL SERVICES. IFPROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF ACOMPETENTPROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NORTHEAUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACTTHAT AN ORGANIZATIONOR WEBSITE IS REFERRED TO IN THIS WORK AS ACITATION AND/OR A POTENTIAL SOURCE OF FUR-THERINFORMATION DOES NOTMEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFOR-MATIONTHEORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAYMAKE.FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTEDIN THIS WORK MAY HAVECHANGED OR DISAPPEARED BETWEEN WHEN THIS WORKWAS WRITTEN AND WHEN IT IS READ.For general information on ourother products and services, please contact our CustomerCareDepartment within the U.S. at 800-762-2974, outside the U.S. at317-572-3993, or fax 317-572-4002.For technical support, pleasevisit www.wiley.com/techsupport.Wiley also publishes its books in avariety of electronic formats. Some content that appears in printmaynot be available in electronic books.Library of Congress ControlNumber: 2008923124ISBN: 978-0-470-18238-3Manufactured in the UnitedStates of America10 9 8 7 6 5 4 3 2 1 4. About the AuthorI am BillSempf, and youll notice that I dont write in third person. Ihavespent an inordinate amount of time in the last several yearswriting about,thinking about, and coding in VB.NET. I am a coauthorof Professional VisualStudio.NET, Effective Visual Studio.NET,Professional ASP.NET Web Servicesand Professional VB.NET (amongothers), and a frequent contributor to theMicrosoft DeveloperNetwork, Builder.com, Hardcore Web Services, InsideWeb DevelopmentJournal, and Intranet Journal. I have recently been aninvitedspeaker for DevEssentials, the International XML Web ServicesExpo,and the Association of Information Technology Professionals.As a graduate ofOhio State University with a Bachelor of Science inBusiness Administration,Microsoft Certified Professional, CertifiedInternet Business Strategist, andCertified Internet Webmaster, Ihave developed over one hundred Webapplications for startups andFortune 500 companies alike.I began my career in 1985 by helping myfather (also named Bill) manageApple IIe systems for the locallibrary. Since then, I have built applications forthe likes ofLucent Technologies, Bank One, the State of Ohio,NationwideInsurance, and Sears, Roebuck and Co. I specialized indata-driven Webapplications of all types, both public and private.Currently, I am the SeniorTechnology Consultant at Products ofInnovative New Technology in GroveCity, Ohio, a Microsoft CertifiedPartner, working on a Learning ManagementSystem for OmniPath, inc.(www.omnipath.com). I can be reached [email protected] 5.DedicationThis edition of the book was heavily influenced by thethousands of readersall over the world who took the time to e-mailwith thoughts, questions, com-plaints,criticism, praise and ideas.To be honest, they are why I write. Themajority of my good projectshave come from people who read my books andcall to collaborate.Thisbook is dedicated to those readers. If you have taken the time toe-mailme or review the book or contact Wiley good or bad about thisbookseries, thank you. Even if you are peeved because of a problemor error, youare helping make this a better product and that helpseveryone.Despite what people often think, even with the best ofediting and authoring,these books arent perfect they are acommunity effort. Without that com-munity,the books wouldnt be goodor necessary. Its a self-replicating cycle,and I love it. 6.Authors AcknowledgmentsI cannot begin to thank the amazing team atWiley who led me ever so care-fullythrough the process of updatingthis book. Katie Feltman kept on me torevise the ideas I presented,and Mark Enochs saw to it that I stuck to sched-ule.The entireWiley team, in fact, is the best an author could ever hope tohave.I have gotten to know them well over the last several years, and Ilovethem all.A project at Wendys International led me to ask themost detail-orientedperson I have ever met Mike Spivey to reviewthe technical details ofthis edition. Jeff Simmons reviewed theoriginal code, and did a good job, butthis book is all the betterfor multiple sets of eyes.My army of peer reviewers from theoriginal edition was fantastic: TheresaAlexander, Jim Andrews,David Deloveh, Rex Mahel, Greg McNamara, RobMorgan, Blake Sparkes,and Gary Spencer. Heres a special note about myfather, William E.Sempf, whose education background was of inestimablehelp inreviewing the early concepts for the book. Then, he let me use himasa guinea pig for Part I! What a trooper!Finally, a shout to themany Microsoft people who gave me a hand with spe-cificquestionsabout VB, Visual Studio, and the framework in general: JanShanahanand Susann Ragsdale in the Author Support Group, and BradMcCabe,Daniel Roth, Jay Roxe, and Steve Lasker, among many others, onthedevelopment teams. 7. Publishers AcknowledgmentsWere proud ofthis book; please send us your comments through our onlineregistration formlocated at www.dummies.com/register/.Some of thepeople who helped bring this book to market include thefollowing:Acquisitions, Editorial, and MediaDevelopmentSeniorProject Editor: Mark EnochsSenior Acquisitions Editor: KatieFeltmanCopy Editor: John EdwardsTechnical Editor: MikeSpiveyEditorial Manager: Leah CameronMedia Development ProjectManager:Laura AtkinsonEditorial Assistant: Amanda FoxworthSr.Editorial Assistant: Cherie CaseCartoons: RichTennant(www.the5thwave.com)Composition ServicesProject Coordinator:Kristie ReesLayout and Graphics: Alissa D. Ellet,Shane Johnson,Christine Williams,Erin ZeltnerProofreaders: John Greenough, CaitieKellyIndexer: Potomac Indexing, LLCPublishing and Editorial forTechnology DummiesRichard Swadley, Vice President and ExecutiveGroup PublisherAndy Cummings, Vice President and PublisherMaryBednarek, Executive Acquisitions DirectorMary C. Corder, EditorialDirectorPublishing for Consumer DummiesDiane Graves Steele, VicePresident and PublisherJoyce Pepple, AcquisitionsDirectorComposition ServicesGerry Fahey, Vice President ofProduction ServicesDebbie Stailey, Director of Composition Services8. Contents at a GlanceIntroduction.................................................................1PartI: Getting to Know .NET Using Visual Basic.............9Chapter 1:Wading into Visual Basic..............................................................................11Chapter2: Using Visual Studio 2008..............................................................................23Chapter3: Designing Applications in VB2008..............................................................43PartII: Building Applications with VB 2008 ................59Chapter 4:Building Windows Applications..................................................................61Chapter5: Building Web Applications...........................................................................83Chapter6: Building ClassLibraries..............................................................................107Chapter7: Building Web Services................................................................................123Chapter8: Debugging in VB 2008.................................................................................139PartIII: Making Your Programs Work ........................155Chapter9: Interpreting Strings andThings.................................................................157Chapter10: Making Decisions in Code........................................................................175Chapter11: Getting Loopy............................................................................................187Chapter12: Reusing Code.............................................................................................197Chapter13: Making Arguments, Earning Returns......................................................219Part IV:Digging into the Framework ..........................237Chapter 14:Writing SecureCode..................................................................................239Chapter15: AccessingData...........................................................................................253Chapter16: Working with the FileSystem...................................................................271Chapter17: Accessing theInternet..............................................................................283Chapter18: Creating Images.........................................................................................297PartV: The Part of Tens............................................309Chapter 19: Ten Tipsfor Using the VB User Interface...............................................311Chapter 20: TenIdeas for Taking Your Next Programming Step..............................325Chapter 21: Ten Resources on theInternet................................................................337Index.......................................................................3439. Table ofContentsIntroduction..................................................................1AboutThisBook...............................................................................................2ConventionsUsed in This Book.....................................................................2WhatYou Dont Have to Read........................................................................3FoolishAssumptions.......................................................................................4HowThis Book IsOrganized...........................................................................4PartI: Getting to Know .NET Using Visual Basic................................4Part II: Building Applicationswith VB 2008 ........................................5Part III:Making Your ProgramsWork...................................................5Part IV:Digging into the Framework....................................................5Part V: ThePart ofTens.........................................................................5IconsUsed in ThisBook..................................................................................6Whereto Go fromHere....................................................................................6PartI: Getting to Know .NET Using Visual Basic .............9Chapter 1:Wading into Visual Basic . . . . . . . . . . . . . . . . . . . . .. . . . . . .11Visual Basics Role in theFramework..........................................................11SayingHello to VB 2008!................................................................................13InstallingVisual Studio........................................................................14Startinga Windows Formsproject.....................................................15Addingfunctionality to the form with VBcode................................18Running and operating yourWindows form.....................................19Finding MorePower in VisualStudio...........................................................20VisualStudio doesnt just do Windows!............................................20Visual Basic goesmobile.....................................................................21VBas your one-stop development shop...........................................22Chapter 2: UsingVisual Studio 2008 . . . . . . . . . . . . . . . . . . . . . . . .. . . . .23Understanding Visual StudioTools..............................................................23Touringthe DesignView......................................................................24Accessingcontrols with the Toolbox................................................26Changing detailswith the Propertieswindow..................................27Organizing your projectwith the Solution Explorer........................29Accessingoutside resources with the ServerExplorer...................30Dynamically editing data with the DataSources window...............33Moving a ToolWindow..................................................................................3510. xiv Visual Basic 2008 For DummiesWorking withCode.........................................................................................36Gettingto Code View...........................................................................36UsingIntelliSense.................................................................................37Readingthedocumentation................................................................38CustomizingwithOptions.............................................................................40IncreasingEfficiency with Third-Party Tools.............................................41Chapter 3: DesigningApplications in VB 2008 . . . . . . . . . . . . . . . . . . ..43Making Software Simple Using the .NETFramework.................................44Getting to theoperatingsystem.........................................................46Integratingservers andservices........................................................47Interactingwith the user.....................................................................48ComparingAbstract Concepts with the RealWorld..................................48Classes...................................................................................................48Objects...................................................................................................49Planningfor a Project Using the ProjectLifecycle.....................................49Scoping out thesystem.......................................................................51Gatheringrequirements.......................................................................51Designingthe Date Calculator......................................................................52Storingdata...........................................................................................53Designingscreens.................................................................................54Defininglogic........................................................................................56Writinga test plan................................................................................57Stickingto the plan..............................................................................58PartII: Building Applications with VB 2008.................59Chapter 4:Building Windows Applications . . . . . . . . . . . . . . . . . . .. . .61A Quick Look Back at VisualBasic...............................................................61DiscoveringWindows Controls....................................................................63Makinga Windows Application....................................................................65AddingFunctionality to a WindowsForm...................................................68AddingFeatures to WindowsForms............................................................70Managingtext input with theTextBox...............................................71Communicatingwith the user using the status strip.......................73Givinghints with the ToolTipcontrol................................................75Navigatingwith the MenuStrip control.............................................78Activating theright-click with the ContextMenuStrip.....................80Chapter5: Building Web Applications . . . . . . . . . . . . . . . . . . .. . . . . . .83Seeing How ASP.NET Works with Your Web App.......................................84PostBack: Not a returnedpackage .....................................................85Amatter ofState...................................................................................85Discoveringthe WebControls......................................................................8611. Table of Contents xvBuilding Your First WebApplication............................................................89Viewingthe extras in Web Forms.......................................................89Constructingthe Web Formsapplication..........................................90Viewing theresults in Source View....................................................93Running yourWeb application...........................................................95LookingBelow the Surface of WebForms...................................................97Validatinguser input............................................................................98DealingwithState...............................................................................101CheckingOut Some Cool Web Tricks........................................................102Gettingfrom one page to another....................................................103Addingpretties...................................................................................104Gettinginformation about the user.................................................104Chapter 6:Building Class Libraries . . . . . . . . . . . . . . . . . . . . .. . . . . . .107Past to Present: DLLs Defined....................................................................108DesigningaLibrary......................................................................................109Objectsandclasses............................................................................110Theparts of a class library...............................................................110Codinga class library........................................................................112Creatinga ClassLibrary..............................................................................113Gettingstarted....................................................................................114Buildingthe Date Calculator.............................................................114Doingmath with a subroutine..........................................................115Runninga DLL file..............................................................................116DelvingDeeper intoDLLs............................................................................118Tellingbetween friends andfoes......................................................119Benice and share...............................................................................119Gettingmore out of less....................................................................120Chapter7: Building Web Services . . . . . . . . . . . . . . . . . . . . .. . . . . . . .123Getting to Know XML Web Services..........................................................123Webservices: Characteristics..........................................................125Webservices: Quirks.........................................................................125Designingfor WebServices.........................................................................126Planningthe designstrategy.............................................................126Gettinga grip on thetactics..............................................................127Buildinga Web Service................................................................................127Buildingthe DateCalc Web service..................................................129Viewing theDateCalc service in action...........................................130Consuming a WebService...........................................................................132WebServices in MoreDepth.......................................................................135Chapter8: Debugging in VB 2008 . . . . . . . . . . . . . . . . . . . . . .. . . . . . . .139Cool Visual Tools for Debugging................................................................139Breakpoints.........................................................................................140TheWatchwindow.............................................................................143TheImmediateWindow.....................................................................14412. xvi Visual Basic 2008 For DummiesUsing the Debugging Tools inthe .NET Framework ................................145The Debugclass.................................................................................146Errorhandling.....................................................................................147Debuggingthe Projects...............................................................................148WindowsForms..................................................................................149WebForms...........................................................................................150Classlibraries.....................................................................................152Webservices.......................................................................................153PartIII: Making Your Programs Work .........................155Chapter9: Interpreting Strings and Things . . . . . . . . . . . . . . . .. . . . . .157Types of Information in Visual Basic.........................................................158Understandingtypes in Visual Basic...............................................158Changing typeswith CType..............................................................159Controllingtypes withvalidation.....................................................163MakingWords Work with the StringType.................................................164Thefantastic tools built intostrings................................................164Emptinesshandling nulls.............................................................165FindingTools for Managing User Input.....................................................167Constructingstrings with the StringBuilder class.........................167Manipulating strings with regularexpressions ..............................168Things That ArentStrings Numbers andDates..................................170Integers and reals andimaginaries, oh my! ....................................170Workingwith dates and date math..................................................171Changing Typeswith Parse and TryParse................................................173Chapter 10:Making Decisions in Code . . . . . . . . . . . . . . . . . . . . .. . . .175Designing BusinessLogic............................................................................175DepictingLogic with Flowchart Components..........................................176Communicating with theuser...........................................................176Definingthe process..........................................................................178Makingadecision...............................................................................178ImplementingThese Processes in Visual Basic.......................................180Single process.....................................................................................180Multiplechoice...................................................................................182Exception.............................................................................................183Chapter11: Getting Loopy . . . . . . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . .187Dealing with Zero.........................................................................................188Startingat zero...................................................................................188Comparingspecific loops and indefinite loops..............................188Writing Loops withFor-Next.......................................................................190Usingthe For-Each Listing withCollections.............................................191 13.Table of Contents xviiWriting Indefinite Loops with Do-Loop.....................................................193Do-Whileloop, checked at start.......................................................194Do-Whileloop, checked atend.........................................................194Do-Untilloop, checked atstart.........................................................195Do-Untilloop, checked atend...........................................................195Checkingat the Beginning withWhile.......................................................196Chapter12: Reusing Code . . . . . . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . .197Reusing Code to Build Software.................................................................197Buildingfunctions with reuse inmind.............................................198Extendingreusability with class files..............................................201Avoiding theCode-ComplexityTrap..........................................................203Protectingthe values ofparameters................................................204Handlingerrors effectively in an abstract environment...............205Finding Other Ways to ReuseCode............................................................207Creatingcustom controls..................................................................207Addingusercontrols..........................................................................209Makingmaster pages.........................................................................210ReusingPrograms Outside of theFramework..........................................211Referencingthe old Component Object Model..............................212Calling methods in COM objects......................................................213Usingother programs with the Process class................................213Accessing DOS: But Only as aLastResort................................................216Runningcommand-line programs withShell..................................216Getting focus withAppActivate........................................................217Chapter13: Making Arguments, Earning Returns . . . . . . . . . . . . . . ..219Using ClassesEffectively.............................................................................220Makingand destroying objects........................................................220Resourceutilization...........................................................................221WithandUsing....................................................................................221UsingEvent Handlers..................................................................................222Eventhandling using the Propertieswindow.................................222Event handling usingIntelliSense.....................................................224Relaxedevent handlers.....................................................................224MakingSensible Procedures withOverloading........................................226Reusing yourprocedurenames........................................................226Changingbuilt-in functions with operator overloading................227Designing for overloading.................................................................228Optionalparameters..........................................................................229FlexibleObjects withGenerics...................................................................230Buildinggenerics................................................................................230Designingfor generics.......................................................................231ControllingObjects with Threading..........................................................232Designingfor threading.....................................................................232Implementingthreading....................................................................23314. xviii Visual Basic 2008 For DummiesPart IV: Digging into theFramework...........................237Chapter 14: Writing SecureCode . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..239Designing SecureSoftware..........................................................................240Determiningwhat toprotect.............................................................240Documentingthe components of the program..............................240Decomposing the components intofunctions................................241Identifying potentialthreats in those functions .............................241Ratingtherisk.....................................................................................242BuildingSecure Windows FormsApplications.........................................242Authenticationusing Windowslogon..............................................243Encryptinginformation.....................................................................245Deploymentsecurity..........................................................................246BuildingSecure Web Forms Applications.................................................247SQL Injectionattacks.........................................................................247UnderstandingSQL Injection............................................................247Scriptexploits.....................................................................................248Bestpractices for securing your Web Forms applications...........250Using System.Security.................................................................................251Chapter15: Accessing Data . . . . . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . .253Getting to Know System.Data.....................................................................254Howthe Data Classes Fit into theFramework..........................................256Getting toYour Data....................................................................................256Usingthe System.DataNamespace............................................................257Connectingto a data source.............................................................257Workingwith the visual tools...........................................................262Writingdata code...............................................................................266UsingLINQ....................................................................................................269Chapter16: Working with the File System . . . . . . . . . . . . . . . . .. . . . .271Getting to Know System.IO.........................................................................271Usingthe System.IONamespace................................................................273Openinga file......................................................................................274Changingthe contents of a file.........................................................277Savingafile..........................................................................................277Listingdirectories andfiles...............................................................279Viewingfileinformation.....................................................................279Keepingan eye on files......................................................................280Chapter17: Accessing the Internet . . . . . . . . . . . . . . . . . . . .. . . . . . . .283Getting to Know System.Net.......................................................................284Howthe Net Classes Fit into the Framework...........................................285 15. Table ofContents xixUsing the System.NetNamespace..............................................................286Checkingthe network status............................................................287Downloadinga file from the Internet...............................................288E-mailing astatus report...................................................................290Loggingnetwork activity...................................................................293Chapter18: Creating Images . . . . . . . . . . . . . . . . . . . . . . . .. . . . . . . . . .297Getting to KnowSystem.Drawing...............................................................298Graphics..............................................................................................298Pens......................................................................................................299Brushes................................................................................................299Text.......................................................................................................300Howthe Drawing Classes Fit into the Framework...................................300Using the System.DrawingNamespace.....................................................302Gettingstarted....................................................................................302Settingup the project........................................................................304Drawingtheboard..............................................................................305PartV: The Part of Tens.............................................309Chapter 19: TenTips for Using the VB User Interface . . . . . . . . . . . ..311Generating Event Handlers from the PropertiesWindow.......................311Generating Event Handlers from theCode View......................................313Pasting Text asHTML..................................................................................314CustomizingYour Toolbars for Every File Type......................................315Adding ExtenderProviders.........................................................................316UsingVisual Components That Are Not SoVisual...................................317Recording Macros........................................................................................319Usingthe Task List.......................................................................................322InsertingSnippets in YourCode.................................................................323Chapter20: Ten Ideas for TakingYour Next Programming Step . . . . . . . .. . . . . . . . . . . . . . . . . . . . . . . . .325Get VisualBasic 2008 for Home Use..........................................................325UpdateCode to Use New Tools..................................................................326Joinan Online Competition atTopCoder..................................................326Participatein an Open Source Project......................................................327UseThird-Party Tools in YourProjects.....................................................328Integratea Public WebService...................................................................329TryOut CodeRush and Other Code Generators......................................331Write a WebPart...........................................................................................332Usethe DTE..................................................................................................334Writean Article about What You Have Discovered.................................335 16. xx Visual Basic 2008 ForDummiesChapter 21: Ten Resources on the Internet . . . . . . . . .. . . . . . . . . . . . .337MSDN Library...............................................................................................337VBForDummies.net......................................................................................337Channel9.......................................................................................................338ASP.NETWeb.................................................................................................338TheMicrosoft PublicNewsgroups.............................................................339.NET247.........................................................................................................339GoogleCodeSearch......................................................................................339kbAlertz.........................................................................................................340CodePlex........................................................................................................340Google forSearching..............................................................340Index........................................................................34317. IntroductionWelcome to the new version of Visual Basic for2008. As its name implies,Visual Basic is a visual way to createnew programs for the MicrosoftWindows family of operatingsystems.And though it is basic in many ways, the Visual Basiclanguage is also verypowerful. You can create new class librariesand XML Web services, as wellas programs that you can use on yourPC or your Web browser, or even yourphone or PDA. Anything that canbe done in Windows can be done in VisualBasic.Programming in VisualBasic is easier than you might think, thanks to thevisual toolssupplied by Visual Studio. You dont have to type line after lineofcode to create a working program Visual Studio automaticallygeneratessome code for you when you drag and drop components withthe visual tools.Of course, being able to read and write code isimportant, too, and this bookprovides plenty of code samples sothat you can understand the inner work-ingsof your programs.Thisbook also shows you some best practices to keep in mind as you getfur-theralong in your programming. Your first programs may be verysimple, butwhen you start getting into more complicatedapplications, you really need toplan out your program before youstart writing the code.Previous versions of Visual Basic werecomplete development environments.The latest version of VisualBasic is really only one part of a three-part pro-grammingstrategy:A language: For this book, it is Visual Basic 2008. Other popularlanguagesinclude C#, J#, Perl, and 24 others. An IntegratedDevelopment Environment (IDE): For this book, it isVisual Studio2008. Other IDEs include Borland, Adobe, and severalother tools. Aproject: In this book, I cover four types of projects: WindowsForms,Web Forms, class libraries, and XML Web services. You canalso use VBto build Windows services, console applications, SmartDevice applica-tions,Mobile Web Forms, and many other projecttypes. 18. 2 Visual Basic 2008 For DummiesAbout This BookNo matterwho you are or what your background is, you are not a dummy ifyourereading this book. You might, however, be a dummy about whatVisualBasic is, how to use it, or why it can help you do your jobbetter.This book is expressly designed to make you a good VisualBasic programmer.As such, I dont spend every page talking about thefeatures of the language,how to use Visual Studio, or how toconnect to a database. I spend a fairamount of time talking abouthow to make good decisions, build the rightsoftware for the problemyou need to solve, and not make common mistakes.Visual Basicdespite all appearances is really very easy to use. Much ofthecomplexity of the language is hidden in tools provided to you byMicrosoft.Many of these tools are not expressly for Visual Basic,but they will becomevery important to your success as a programmer.This book is also aboutthose tools, because they make writing good,working programs faster andeasier.This book is also about you, theprogrammer. Im a programmer like you. Ihave been writing in BASICsince 1981, and Ive lived through all the ups anddowns. For about15 years, Visual Basic was a program, not a language, and Ilivedthrough that. Now the tables have turned Visual Basic is again alan-guage(Visual Studio is the program). In this book, I help youbecome a goodVisual Basic programmer.Conventions Used in This BookIhave written this book to be easy to read while you areprogramming. Assuch, I use certain conventions to make for easierreading: Words that I want to emphasize or that Im defining areplaced in italics. Terms that are used in Visual Basic code are inmonotype font. Menu selections look like this: FileNew. This isshorthand for Fromthe File menu, select New.I use numbered lists toguide you through a sequential process such as build-inga WindowsForms application. The bold part of the step is atechnicaldescription of the action you are to perform, and thenormal (not bold) textthat follows provides further explanation ordescribes how I implemented thestep in my examples. 19.Introduction 3Bulleted lists are used to create memorable lists.For me, one of the toughestthings about programming is rememberingkey points, like features or bestpractices. I use the bulletedlists to help with those kinds of things.Code examples are brokenout from the rest of the paragraph, as follows:IfDateNumber.Text.Length0 ThenDateInterval = CInt(DateNumber.Text)EndIfNextWeek.Text =DateChooser.Value.Add(TimeSpan.FromDays(7)).ToString()The codeblocks are usually written in such a way that you can copythemright into your program. They will be in monotype font, andsometimes willhave linefeeds (the space and underscore character atthe end of the line) ininappropriate places because the printedpage is only so wide. Rememberthat when youre writing out the codeand youre looking at it on-screen, youwont need to use so manylinefeeds. If you have a question about where abreak should be,check out the sample code, which you can find on thisbookscompanion Web site, www.vbfordummies.net.What You Dont Have toReadIf youre not working with graphics right now, you can skip thechapter ongraphics. If you dont use a database, you can skip thedatabase chapter.See where I am going? If you dont use Webservices, you dont have to readabout them.Effectively, this is amodular book. Aside from Part I, which everyone needsto read, thereare no requirements to read anything in any particular order.Readwhat you need, and ignore the rest until someone comes intoyouroffice and needs something done on that topic. Then you canpull the bookout again and read that chapter.If you have a copy ofVisual Basic 2005 For Dummies, you will find many simi-laritiestothis book There were not too many changes between VB 2005 andVB2008, fortunately. I will strive to document the differencesbetween thisbook and the 2005 book and post them onwww.vbfordummies.net. 20. 4 Visual Basic 2008 For DummiesFoolishAssumptionsI assume that by buying this book and reading it, youare interested in findingout how to program in Visual Basic. Beyondthat, I also assume that you havethe following: A PC running someflavor of Windows (Windows Vista or XP, most likely) A copy ofVisual Studio 2008 Professional installed on your PC Access to theInternet, for downloading code samples and further readingHow ThisBook Is OrganizedThis book is meant to be read as a series ofarticles, but it can easily be usedas a reference or read straightthrough. I recommend reading it at your com-puter,with VisualStudio running.Each part is designed to teach you something thatyou need to know. The onlypart that I strongly suggest you read,however, is Part I, Getting to Know .NETUsing Visual Basic. Afterthat, you can read whatever you need to get the jobdone, or readthe whole book all the way through it is up to you.Part I: Gettingto Know .NETUsing Visual BasicAfter a quick jump start, I discussthe tools and concepts in this part. Chapter 1is a Hello Worldintroduction to the language, which experienced VB program-merswillfind useful and new programmers will find vital. Chapter 2 is atour ofthe development tool you will be using, Visual Studio2008.Chapter 3 is arguably the most important chapter in the book.It is aboutdesigning good software with Visual Basic. You may wantto read that onetwice. I wanted to print it twice, but thepublisher wouldnt let me. 21. Part II: Building Applicationswith VB2008This part gets you started programming. You find one chapterhere for eachof the four most-used project types (Windows and WebForms, DLL files, andXML Web services) and then a chapterdiscussing how to debug all of them.Part III: Making Your ProgramsWorkThis part is actually about Visual Basic the language. You see,the projectsdiscussed in Part II are actually available to lots oflanguages. You can writea Windows Forms project in Java (Microsoftcalls it J#) if you want to. Theactual VB language doesnt kick inuntil you write a program that needs morethan the visualdesign.Part IV: Digging into the FrameworkFinally, in Part IV, youlook at the last part of the puzzle what the .NETFramework can dofor you. Tons of tools that are built right into the frame-workareavailable to all languages but have a special twist when usedwithVisual Basic.I begin with the important stuff, specificallysecurity. Then I cover data, files,networks, and drawing.Throughout all these chapters, I provide code exam-plesthat canhelp you through the tougher problems that you may encounterin yourVB career.Part V: The Part of TensSome things fit nowhere. Thatswhat the Part of Tens is for. In this part, I col-lectedthe mostuseful tips that didnt fit elsewhere and made them intotop-tenlists. For more of these kinds of lists, check out thisbooks companionWeb site at www.vbfordummies.net.Introduction 5 22.6 Visual Basic 2008 For DummiesIcons Used in This BookOne of thethings I like best about the For Dummies series of books is theeaseof reading. Important facts are easily distinguishable fromtips or technicaldetails by this cool series of icons in themargins. I hope you find them asuseful as I do.This is the icon Iuse most often. It highlights a best practice, a commonusage, orjust something that I think you will find good to know about afea-tureor tool.I use this icon to point out something that youwant to, well, remember. Thefamous gotchas that all programmers areso familiar with get this icon. Someusages arent always obvious. Ihope to help you help yourself by pointingthem out.This icon pointsout something you do not want to do unless youre willing tosufferthe consequences. Read the paragraphs next to the Warning iconsothat youll know how to avoid the pitfall, trap, or mistake.Theseicons are pointers to places where the My object, new to VisualBasic2008, can be useful.Sometimes, I give you more informationthat you really need. When I do that,I try to use the TechnicalStuff icon. You will find things you never wanted toknow about theinner workings of the .NET Framework, design ideas, andother geekystuff alongside this icon.I use this icon to highlight a newfeature in Visual Basic 2008.Where to Go from HereIf yourecompletely new to Visual Basic and Visual Studio, start out byflip-pingthe page and reading Chapter 1. If youre interested inlooking up a par-ticulartopic, skim through the Table of Contentsor the Index and turn to theindicated page.When youre feeling morefamiliar with the language, tool, and project type,branch out bychecking out the list of tips in the Part of Tens to take yournextprogramming step. 23. Introduction 7You can, of course, read thebook all the way through. Another great way tofigure out how VisualBasic works is to follow a project path all the waythrough. Forexample, start with a Windows Forms project with System.Drawingelements, and go through the examples in the chapters thatdiscussthose topics (Chapters 4 and 18, in this case).Be sure touse the code samples for this book, provided atwww.vbfordummies.net. They will give you a broad starting point fora lot of other,larger programs that you might want to write.Youalso might be in the position where you have to quickly learn howto usethis language for your job, and there might be speciallibraries and standardsthat you have to work with there. Irecommend that you take the book home,where you can workundistracted, and give yourself a good foundation in thelanguage.Then you can take the book back to work and use it as areferencefor your future programming efforts.Things change in thesoftware world, and Microsoft software is especiallyprone tochange. Things have probably changed since I wrote this book. Ifthesoftware changes, I cant update the books that have already beenprinted.However, I can (and do) list any errata and updates on thisbooks companionWeb site, www.vbfordummies.net. Check it out often.24. 8 Visual Basic 2008 For Dummies 25. Part IGetting to Know.NETUsingVisual Basic 26. In this part . . .Everyone must startsomewhere, and I start at thebeginning in this part. You write yourfirst Visual Basicprogram, and, in doing so, you discover some ofthe ideasbehind the .NET Framework (the backbone of this versionofthe language). You then get to do the only required read-ingin thisentire book. First, you go over the use of the tool,Visual Studio.Second, you design the example applicationthat you write in thenext part. 27. Chapter 1Wading into Visual BasicIn This ChapterSeeing where Visual Basic fits in with .NETWriting your firstVisual Basic 2008 program Exploiting the newfound power of VisualBasicTo get started with Visual Basic 2008, I recommend that youjump right inand write software! And to help you with such anassertive approach, thischapter gives you just what you need totest the waters of the Visual Basicpool and get comfortable withits place in the larger Visual Studio environment.Then you canreally get your feet wet as you build Hello World your firstVB 2008Windows Forms application right here in the first few pages!Youfind out how to launch Visual Studio 2008 (the development toolfor your VBapplications), how to start a new project, and how tobuild a form visuallyand make it work with code.Also in thischapter, I give you a glimpse into the deeper power of VisualBasic.Specifically, I introduce how VB 2008 integrates with theMicrosoft .NETFramework and offer insight into what that means toyou as a programmer.Visual Basics Role in the FrameworkMicrosoftcreated the .NET Framework to make development for thevariousWindows operating systems easier. But because of thedifferences betweenVisual Basic 6.0 and Visual Basic 7.0 (the first.NET version), most VB devel-opersfound development much harder.For example, VB 7.0 made all variablesinto objects, which removedthe programmers ability to define a variable typeon the fly.Butdeveloping applications in .NET doesnt have to be harder than itwas inVB 6.0. The .NET Framework and Visual Basic 2008 can bepowerful tools, andthe trick is discovering how they work togetherthrough the Visual StudioIntegrated Development Environment (IDE).28. 12 Part I: Getting to Know .NET Using Visual BasicPart of thedifficulty that many programmers face when moving to the.NETFramework is the terminology, which can get confusing. Id liketo putthe problem with terminology to bed right now, so check outthis list of thepotentially confusing terms used in .NETdevelopment: Visual Basic 2008: The programming language describedthroughoutthis whole book. No longer can you run or load VisualBasic as a sepa-rateentity. It is simply one programming languagethat speaks to theMicrosoft .NET Framework, which is the next termin the list. .NET Framework: The layer that sits between thelanguage (in this case,Visual Basic) and the operating system,which can be Windows 98,Windows Me, Windows 2000, Windows XP,Windows Server 2003, or anyof the subversions of those (such as theTablet PC edition). The .NETFramework layer serves to providefunctionality based on the operationof the Windows system on whichit resides, as well as to provide librariesfor other functionality(such as math computations and database access).Figure 1-1 is avisual representation of the relationship of all the layers intheframework. Visual Studio 2008: The tool that you use to create anykind of applica-tionusing any compatible programming language.Visual Studio replacesthe Visual Basic 6.0 program that wasformerly part of the Visual Studiosuite (all individual suitecomponents were labeled Version 6.0). Whenyou go to write a newprogram in the .NET environment, you run VisualStudio 2008 andselect the kind of program you want to write in thepro-gramminglanguage you want to use. For example, you may choosetocreate a Windows Forms program using the Visual Basic language,justlike the old days. Or you might want to write an applicationfor a smartdevice using C#. You can also mix languages, forexample, writing theforms in VB and the classes in C#. In thisbook, I will be using VB foreverything because it is a book aboutVB!.NET Framework 3.5LINQASP.NET 3.5 CLR Add-inFramework.NETFramework 2.0 + SP1AdditionalEnhancements.NET Framework 3.0 +SP1WindowsCardSpaceWindowsWorkflowFoundationWindowsCommunicationFoundationWindowsPresentationFoundationFigure1-1:The .NETFrameworkhierarchy. 29. Chapter 1: Wading into VisualBasic 13 Windows Forms: The new term for an old-fashioned VisualBasic appli-cation.This term refers to an application that iswritten using the .NETFramework and has a Windows user interface.Web Forms: The term for an application with a Web page interfacewrit-tenusing the .NET Framework. Creating a Web Forms applicationis verysimilar to writing a Windows Forms application. Webservices: The class libraries that are written using a standarddefinedby the same people who defined standards for the World WideWeb. Webservices are used for interaction between divergentsystems.The .NET Framework is what you may already know as theWin32 layer in theold Windows DNA system. Like the new .NETFramework, the Win32 layergave you the ability to get to thefunctions of the operating system whendeveloping for a Windowsplatform. Also, the .NET Framework includes a lotof adjunctfunctionality, such as math and data libraries, that makesprogram-minga more cohesive experience.Basically, everything thatWindows does is exposed by the .NET Framework.Specifically, the.NET Framework gives a programmatic name to nearly everyobject andevent that Windows can control. A programmer can use that nametorefer to anything existing in the operating system. Do you need totell theprinter to make two copies of your document? Try referringto My.Computer.Printers.DefaultPrinter.PrinterSettings.Copies = 2.Do youneed to paint some item on the screen blue? Try referring toSystem.Drawing.Brushes.Blue.In this .NET world, the programminglanguage becomes just a way to interactwith the framework and,therefore, with the Windows operating system. Allprograms need aset of established rules to handle the flow (decisions, loops,andso on) within programs. Visual Basic provides one such set ofrules, andthe framework provides the objects and events to interactwith.Saying Hello to VB 2008!In the following sections, I get youstarted with the classic Hello World pro-gram.Although this isntthe single most exciting application you can build, ithelps to makesure that your development environment is set up the bestwaypossible. 30. 14 Part I: Getting to Know .NET Using Visual BasicHowVB 2008 differs from VB 6Visual Basic 6 was a stand-aloneprogram,and Visual Basic 2008 is one language in alargerdevelopment system. To go back to VBsroots, Basic was a programminglanguage used20 years ago as part of MS-DOS. In 1985, BasicbecameVisual Basic and was made into a partof the Windowsapplication-building tool. Youfind a lot more to the Visual Basic 6programthan just the language its form-building soft-ware,forexample, is called Ruby.Visual Basic has gone through a fewrevisionssince VB 6. VB 2002 (a.k.a. VB 7), VB 2003 (VB7.1), and VB2005 (VB 8) are all just revisions ofthe language as it uses the.NET Framework. VB2002 brought on board a whole new way tothinkabout building applications in Windows, and VB2005 broughtback a lot of the features that VB 6programmers depended on likeease of use.In Visual Basic 2008, you have a new way tobuild userexperiences and, with it, a new wayto interact with the Windowsoperating system.The real reason to understand the extent ofthislarger development system and the com-plexityof the .NETFramework that surroundsVB 2008 is so that reading related booksanddocumentation is easier.Installing Visual StudioTo follow thisexample, you need to start by running Visual Studio 2008, whichisthe development environment used throughout this book to buildapplica-tionsin Visual Basic. Before you can run Visual Studio, youneed to install it!Visual Studio comes in a number of editions:Team System: Designed for full programming staffs in largecorporations,this edition includes large-scale application systemdesign tools such astest-driven development and Team FoundationServer. Professional Edition: Designed for the developers workingwith users ina stand-alone setting. The Professional Edition ismore common for thesolo developer or for mid-sized applicationdevelopment. This is the edi-tionI use in this book. StandardEdition: Designed for building smaller, stand-aloneapplica-tions,this version is perfectly functional for 80 percentof applicationsbuilt. But if you plan to build large systems thatneed to be enterprisequality and may have many users, go for theProfessional Edition. Express Edition: Designed for students andhobbyists. This version lacksa lot of the project types that theother versions have. If you are runningExpress, some of theexamples in this book wont work for you. On thisbooks Web site(www.vbfordummies.net), I have posted a few Expressarticles andsome projects that I have altered to work in Express edition. 31.If you dont have access to the MSDN Library (Microsofts handytechnicalarchive), I highly recommend getting it. You can load up amachine with yourchoice of sample code, documentation, and otherreference material onVisual Studio editions, operating systems, andserver software. You can findout about the library at , and you can buysubscriptions fromseveral resellers, including your favorite softwaredealer.Installing Visual Studio can be rough, so I recommend goingwith the defaultsfor your first time. The installation processtakes quite a while, too. Even ifyou are using the DVD, expect tospend two hours installing the program.If you are working from theCDs, expect to spend four hours.After installing Visual Studio, youcan run it by choosing StartAll ProgramsMicrosoft Visual Studio2008Microsoft Visual Studio 2008. The environmentloads, and you canget started on a program by choosing FileNewProject.Next, you needto make choices about your project type and language, asdescribedin the next section.Starting a Windows Forms projectAfter youchoose FileNewProject in Visual Studio, the New Project dialogboxappears, as shown in Figure 1-2. In the Project Types pane, youfind afolder structure that lists the languages loaded with yourinstallation and theproject types available for those languages. Isuggest beginning with a plainold Windows Forms Application whichis the Visual Basic 2008 answer tothe traditional (and perhapsfamiliar) VB 6.0 application.Figure 1-2:The NewProjectdialogbox.Chapter 1: Wading into Visual Basic 15 32. 16 Part I: Gettingto Know .NET Using Visual BasicTo get started building your HelloWorld application, follow these steps:1. Select the project typefrom the Templates pane in the New Projectdialog box.For thisexample, select Windows Forms Application. Also, make surethatVisual Basic is the language selected in the Project Types pane.Ifyou loaded other languages during installation, you may haveotherchoices.2. Type the name you want to give your project toreplace the defaultname in the Name text box.In this example, Itype Hello World in the text box.3. Click the OK button.VisualBasic loads the default form (called Form1) and presents it toyouin the Design View. The default form comes complete with aworkspace,the title bar, and familiar Windows elements like theResize buttons andthe Close button. You do most of the work tocustomize your form usingthis visual view.4. Click the word Toolboxon the left side of the screen and open theCommon Controls tree.TheToolbox appears, with Windows Forms controls loaded, as showninFigure 1-3.5. Double-click the Button control.Visual Studio loadsa button onto the default form in Design View.6. On the defaultForm1, click the Button control and drag it to reposi-tionit on theform.Figure 1-4 shows the result of dragging the button to themiddle of theForm1 window.This step list gives you the beginningsof the Windows Forms application,which you see as Form1 in theDesign View. But to see where Visual Basiccomes in, you have tofind the code behind the form. Visual Studio offers you(surprise!)the Code View when youre ready to use Visual Basic to addfunc-tionalityto your form. 33. Figure 1-3:ChoosingtheButtoncontrol fromthe Toolbox.Figure 1-4:Movingthe buttonaroundtheform.Chapter 1: Wading into Visual Basic 17 34. 18 Part I: Gettingto Know .NET Using Visual BasicAdding functionality tothe form withVB codeTo add a little functionality to the Windows form you buildin the precedingsection, follow these steps:1. Double-click theButton control to enter Code View.In the Code View window, you seebasic button-click code that looks likethe following:Public ClassForm1Private Sub Button1_Click(ByVal sender As _System.Object,ByVal e As System.EventArgs) _Handles Button1.ClickEnd SubEndClassThis code is a template that wraps the code that will be runwhen youclick the button. Visual Studio does the hard part for you,making surethat the formatting of the Sub is correct!2. In the CodeView window, type a line of code to change the text thatappears onthe Button control to Hello World.Specifically, type the followingcode on the line preceding the End Subline:Button1.Text = HelloWorldYour buttons code now looks like the following:Public ClassForm1Private Sub Button1_Click(ByVal sender As _System.Object,ByVal e As System.EventArgs)_Handles Button1.ClickButton1.Text =Hello WorldEnd SubEnd Class 35. Running and operating your WindowsformSo this experience is pretty cool, right? Programming withVisual Basic is soeasy that, here in Chapter 1, you can alreadywrite a Windows Forms applica-tion.But what can you do with it?Check out the following: Run your Windows Forms application withinthe Visual Studio envi-ronment.Press F5, and Visual Studio opensyour active project as aWindows program. It appears on your taskbarand everything. Clickthe button on your form, and the button textchanges to Hello World(or whatever text you specified in the code).Pretty neat, huh? YourWindows form should look something like theimage in Figure 1-5. Run your application outside of the VisualStudio environment. If youare still in Debug mode, you will need tostop your program first byusing the Stop button on the toolbar orby closing the form window.Then you can save and move on.The verysimple way to run an application outside of Visual Studio isasfollows:1. Choose FileSave All.Visual Studio will save yourproject using the defaults you suppliedin the Add New Projectdialog box.2. Choose BuildBuild Program Name.In this example,choose BuildBuild Solution, and Visual Studiocompiles yourapplication into a usable Windows program (withthe file extension.exe) and stores it in the default folder.3. Navigate to thedefault folder containing your new Windowsapplication.For myapplication, the path is C:Documents and SettingssempfMyDocumentsVisual Studio 2008ProjectsVBFDChapter1HelloWorldbinDebug.Figure 1-5:Your HelloWorldapplication.Chapter 1:Wading into Visual Basic 19 36. 20 Part I: Getting to Know .NETUsing Visual BasicIf your local configuration for the projecthappens to be set to Release mode(not recommended for this book),you might find it in C:Documents andSettingssempfMy DocumentsVisualStudio 2008ProjectsVBFDChapter1Hello WorldbinRelease.4.Double-click the filename for the compiled program to run it.Youmay see a lot of files in the default folder, but in theexample,Hello World.exe is the file youre looking for.There is amore complex method for running your VB programs outside theVisualStudio environment. You use a Setup Project, which is a very cooltoolbut beyond the scope of this book. Research the term SetupProject in theMDSN Library when youre ready to find out more aboutthis device, whichhelps you distribute your application to otherusers.Finding More Power in Visual StudioEarlier in this chapter, Ishowed you the Windows Forms application develop-mentenvironmentand a little of the new Visual Basic 2008 code. If you arefamiliarwith VB 6.0, the form and the code look pretty familiar at thispoint.In fact, the major Windows development tools for anyprogramming languagework pretty much this way.But when you lookbeyond the Windows form and the code structure, a fewmore detailsbecome evident. For instance, Visual Studio takes your VBcodebeyond the Windows form. The following sections give you anoverview ofthe development power that you find in VisualStudio.Visual Studio doesnt just do Windows!The first evidentchange that sets Visual Studio apart as a development toolis this:You can use Visual Studio to write programs that run on theWorldWide Web as well as on Windows computers. When you click theFile menuto add a new project, notice the second option in themenu. As shown inFigure 1-6, the second project option is a new Website.Choose this option to create a Web application, whichincorporates a wholehost of technologies the .NET Framework,ASP.NET, Visual Basic, andHTML that each have essential roles forenabling an application to runonline. 37. Visual Basic goesmobileMobile computing made its appearance in Visual Basic 2005 andreally shinesnow in Visual Studio 2008. If you follow developmentfor mobile devices, youmay have noticed the plethora of releasesfrom the Mobile team over the pastfew years. They are all bakedright into Visual Studio 2008. Pocket PC 2003,Mobile 5.0, andMobile 6.0 all make their appearance in Visual Studio 2008,and canbe programmed in VB 2008 just like every other type of project.Idont give examples of these specific project types in this bookbecause youcan create a mobile device application in the samemanner that you create aWindows Forms application (like the HelloWorld program discussed earlierin the chapter). You should knowthat getting familiar with the Visual Basiclanguage as presented inthis book puts you on the right track for creatingapplications fora Pocket PC. Mobile computing applications require somespecialprogramming practices, so make sure to grab somedevice-specificinformation when you work on those projecttypes.Writing routines to use with other software is easier withVisual Basic 2008.You can write add-ins for Microsoft Office apps,including Excel and Wordtemplates with VB code running behind them.These routines dont use theVBScript that you may have seen before;a completely new part of Office 2007allows you to write templateswith special, built-in functionality. For example,Ive built a Wordtemplate that automates a reporting process by asking theuser for areport number, checking that number against a database of allthereports filed, and filling out part of the document-in-processwith the relevantinformation from the database. You can alsocustomize the ribbon bar andcreate and deploy add-ins easily.Figure1-6:The Filemenu inVisualStudio.Chapter 1: Wading into Visual Basic21 38. 22 Part I: Getting to Know .NET Using Visual BasicVB as yourone-stop development shopGenerally, Visual Studio and the .NETFramework are designed to be the one-stopshop for any kind ofdevelopment on Windows machines. But in this ver-sion,Visual Basic2008 can also do it all. The language can now touch all theparts ofthe .NET Framework that any of the other languages can get to,with-outresorting to the cryptic function calls necessary in priorversions of VB.The new features covered in this book include thefollowing: The Windows Presentation Foundation: Microsoft hasupdated the for-mulato design new user experiences again with evenmore power. The Windows Communication Foundation: Makinginterconnectedapplications even more powerful, the WCF is anadvanced step that Illtouch on later in the book. LanguageIntegrated Query: LINQ brings data constructs right into yourcodewith new query mechanisms for collections of objects. System.XML:If you are working with Extensible Markup Language, VB2008 bringsnew meaning to the word simple. 39. Chapter 2Using Visual Studio2008In This Chapter Going over Visual Studio tools Discovering howthe code ties it all together Customizing with options Usingthird-party toolsBefore you can effectively work with Visual Basic,you must know its toolsinside and out. For the purpose of thischapter and this book, I will focuson just one Visual Studio 2008.Visual Studio gives you access to the drag-and-drop controls thatwere introduced in earlier versions of Visual Basic.Although I dontcover the specifics of code in this chapter, I do cover allthecode-generating tools that Visual Studio 2008 provides forVisual Basic. Forexample, I discuss the new, improved IntelliSense,which can help youremember the 288,000 methods, properties, andevents in the .NET Frame-work,but I dont cover the frameworkitself.Understanding Visual Studio ToolsPart of the joy ofprogramming in Visual Basic 2008 is using the tools thatareprovided by Visual Studio. Rapid Application Development (RAD)is a buzz-wordnow, but when Visual Basic was first developed, itdescribed (amongother things) the ability to code faster by reusingbits of code built into thedevelopment tools.This ability has neverbeen more apparent than it is with Visual Basic 2008.Even thoughVisual Basic is a language, and it depends on Visual Studio foritsenvironment, many tools make RAD real. In the following sections, Icoverthese tools. These tools are language independent, projectindependent, andindispensable. 40. 24 Part I: Getting to Know .NETUsing Visual BasicKeep in mind that Visual Studio isnt necessary tomake Visual Basic programs.You can, in fact, make completeapplications in the old-school style by usinga command-linecompiler.Additionally, much of the documentation provided by theMicrosoft DeveloperNetwork (MSDN) Library assumes an understandingof the tools. The docu-mentationrefers to the tools by name andoften doesnt clearly describethem. You must know where you areworking before you can work, so thefollowing sections take you on atour of the Visual Studio tools.When you installed Visual Studio,you were probably asked to install theMSDN Library. You will findit an indispensable tool (its what you get whenyou go to the Helpmenu, in fact). Additionally, you can find the library onlineat the Design ViewWhen youlaunch Visual Studio (usually by selecting its icon on yourStartmenu) and begin any visual project, you see the Design View.The DesignView is where the Graphical User Interface (GUI) worktakes place. Generallyspeaking, anytime you are working withpictures of forms, not code, you areworking with the Design View.When I use the term designer window, I amreferring to the actualplace you do the work. The term Design View refersto the state theapplication is in.In the Design View, you can accomplish thefollowing: Manufacture windows, Web, and smart device forms bydragging controlsdirectly to the form in aWhat-You-See-Is-What-You-Get (WYSIWYG)typeenvironment Work withdatabases and XML files visually Create software components byvisually managing the partsIn general, Design View is the core partof Visual Studio. Many of the othertools in Visual Studio depend onthe Design View, in fact, and are disabledwhen you use anotherview, such as Code View, to work on your project.Using the DesignView tabsThe designer tabs have the word [Design] in the tab name,as shown inFigure 2-1, to indicate that you are using the DesignView. Tabs are used inthe Design and Code Views. The gray tabrepresents files that are open butnot active. An asterisk (*) nextto the filename means that youve madechanges, but not yet saved thefile. 41. The white tab is active and contains the editable form.When you have morethan one document open, you can edit only theactive form. You can drag thetabs to the left and right to changetheir order. Right-clicking a tab gives youa menu from which youcan choose several screen management options, asshown in Figure2-2.Figure 2-1:A form inDesignView.Figure 2-2:Managingtabgroups.Chapter 2: Using Visual Studio 2008 25 42. 26 Part I:Getting to Know .NET Using Visual BasicUnderstanding tab groupsTabgroups make it easier to copy information out of one form andintoanother. For example, you can have one set of pages on the tophalf of thescreen and another on the bottom half, and copy from oneand paste into theother without changing screens. You can also saveand close from this menu,or get information, such as the currentpath or the containing folder.Accessing controls with the ToolboxToadd form components, such as buttons and text, to the form in theDesignerwindow, you simply drag them from the Toolbox. The Toolbox,usually seenon the left side of the Visual Studio environment andto the left of the Designerwindow, is where the RAD components ofvarious project types are held foruse until you need them. TheToolbox is shown in Figure 2-3.Figure 2-3:The Toolbox. 43. Chapter2: Using Visual Studio 2008 27The Toolbox is project-sensitive,meaning that controls for Web pages andsmart devices dont show upwhen you are writing a Windows Forms project.Because those controlscant be used in those project types, the Toolboxdoesnt even let yousee them.You can access the controls in the following ways: Click acontrol and drag it to a form, dropping it exactly where you wantit. Double-click the control, and it appears in the upper-leftcorner of theactive form.If you lose the Toolbox, or if it isntshowing on your screen, you can open itby choosing ViewToolbox orby pressing Ctrl+Alt+X. Right-clicking theToolbox gives you layoutoptions, including ordering and movement. One ofthe options isReset Toolbox, which puts it back the way Microsoft had it a greatfeature.The gray dividers, labeled Data or Windows Forms amongother things,divide the tools in the Toolbox by category. To open aclosed category, clickthe divider.Visual Studio is extendablebecause of the Toolbox. You can use third-partycomponents with yourprograms. For example, a clock control that enablesthe user to setthe time would show up in the Toolbox. You can also use theToolboxto store often-used pieces of text, such as comment blocks.You canactually drag a little block of code onto the Toolbox for reuse,suchas a common comment block or a sample. I use this all the timewhen I ampresenting. I just make a new section by right-clickingthe Toolbox and select-ingAdd Tab. Then I can just select code inthe Code View (which I cover in afew pages) and drag it right underthe new section header.Changing details withthe PropertieswindowAfter you drop the controls on the form designer, you willneed to edit theirproperties. Size, name, activity, color . . .these are the kinds of things youfind in the Properties window. TheProperties window, shown in Figure 2-4,is usually on the right sideof the screen. It contains all the editable valuesassociated with acontrol.If the Properties window isnt on the right side of thescreen, you can find itby choosing ViewProperties Window, or youcan press F4. 44. 28 Part I: Getting to Know .NET Using VisualBasicAt the top of the Properties window, you see the form elementwhose proper-tiesare being viewed. You can select a differentcontrol by clicking it in theDesigner window or by selecting a newcontrol from the drop-down list. InFigure 2-4, the form itself isselected.Beneath the selected control, you find a few buttons thatresort the list orfilter by category. Of special interest is thelightning-bolt button, whichallows you to define what the controldoes under certain circumstances a pattern called events. I coverevents in depth throughout Part II.The table that takes up themajority of the Properties window contains theproperties of thecontrol. This is a simple hash table format the propertiesare onthe left, and the possible values are on the right. To change avalue,you can usually type in the cell and press Enter. Someproperties have anellipsis button (...) that opens a form tosimplify adding complex details, andI cover those as I discuss themin other chapters.The grouping buttons at the top of the Propertieswindow are a useful fea-ture.The Category button is great when youare just starting out, becauseyou can find the properties based onwhat you need. The A-Z list is betterlater on, when you knowexactly what property you are looking for.Figure2-4:ThePropertieswindow. 45. The bottom of the Properties windowhas a brief description of the propertythat is being edited. Thisinformation is right out of the documentation and isa very handyfeature.Organizing your project withthe Solution ExplorerSolutionsand projects hold forms and components like files in folders.Infact, solutions and projects are represented by folders in theVisual StudioProjects directory of your My Documents folder. TheSolution Explorer isVisual Studios tool that allows you to managethe files that make up yourproject.If you envision your projectslike folders, you can imagine that you wouldgroup like folderstogether in a folder one level up, right? Thats what solu-tionsdo.They are both physically and logically exactly that folders fullofprojects.In Figure 2-5, you see the important files in yourproject, and a whole bunchof buttons above to help manage them.Toopen a file, double-click the files icon or name. To rename, copy,or deletea file, right-click the file and choose the desired actionfrom the context-sensitivemenu that appears. In the SolutionExplorer, you can also make newfolders and move files into them, orright-click the project to make a new formor support file.Thebuttons above the files themselves are the most significant part oftheSolution Explorer. They are as follows, from left to right:Properties: Opens the Properties window. Show All Files: Showshidden files. This is more significant in VB 2008than before. Evenmore files are hidden from normal view.Figure 2-5:TheSolutionExplorer.Chapter 2: Using Visual Studio 2008 29 46. 30 PartI: Getting to Know .NET Using Visual Basic Refresh: Checks thesolution folder for new files that may have beenadded by anothertool. This button is very handy when youre usingthird-party tools.View Code: Opens the selected file in Code View. View Designer:Opens the selected file in Design View. View Class Diagram: Opensthe selected file in Diagram View.Visual Studio stores a lot offiles that keep metadata about the project in theMy Project folderin Solution Explorer. Metadata is information about data in thiscase, extra information about your project. If you click the ShowAllFiles button in Solution Explorer and expand My Project, youwill see no lessthan seven files with information about yourproject. You wont need to editthese files often, but if you justcant find something, you might want to checkthem out.Accessingoutside resourceswith the Server ExplorerGoing outside of yourproject to access needed resources is one of the mostcommonfeatures that isnt supported by most development environments.Thatall changed with Visual Studio 2002 and has gotten better eversincewith the addition of the Server Explorer, shown in Figure 2-6.You can openServer Explorer by pressing Ctrl+Alt+S or by selectingit on the View menu.Now getting to the servers that provide yournecessary services is easierthan ever.The Server Explorer is one ofthe more dynamic tools in the Visual Studioenvironment. In Figure2-6, I am using my virtual development machine, XP.What you see inthe Server Explorer depends on your local configuration.Figure2-6:The ServerExplorer. 47. The Servers node in this explorer showsup in some editions of Visual Studio.At press time, theProfessional edition was one of them. Also, the Team Systemeditioncertainly has it, and you can get that edition from the MicrosoftWebsite in a trial version.Server Explorer gives you access toremote (or local) resources from a man-agementand a codeperspective. The tree view inside the Server Explorercan show manyservers, and beneath each server are the functional bits thatyouhave access to.Most developers are looking for a one-stop shop fordevelopment; most often,that includes needing the ability to managedevelopment server(s) and lookat databases. The Server Explorerhandles both of these, but the new DataSources window is evenbetter, and I cover it in the following section.The servicesavailable to you in your Server Explorer depend on yourenvi-ronment,but here is a brief description of some of theservices that arecommon: Crystal Reports Services: Crystal is athird-party reporting tool that isincluded with Visual Studio. Theservices include Crystal Enterprise,Report Application Server, andWeb Services. Event Logs: This represents the normal old WindowsNTstyle eventlogs that you can access from the Control Panel. Logsare available bothprogrammatically in .NET and for management fromthe Server Explorer. Management Classes: Management Classesrepresent Windows Manage-mentInstrumentation (WMI) classes such asNetwork Adapters, Printers,and Services, all of which you can touchprogrammatically on remotemachines. Management Events: They allowyou to register for WMI events, likenetwork changes and hardwarewarnings. Message Queues: Message Queues are a way to help managethe numberof requests to a very large application. The individualqueues are madeavailable here. Performance Counters: This is accessto PerfMon from the Windowsoperating system. Each counter isavailable both for viewing andprogramming. Services: The servicesfrom the Control Panel are available here. Youcan stop and startthe Web services, for example. Data Connections: This is a specialcategory that isnt directly relatedto the servers shown. The DataConnections relate to connections youhave set up over time on yourinstance of Visual Studio, and are remem-beredfor yourconvenience.Chapter 2: Using Visual Studio 2008 31 48. 32 Part I:Getting to Know .NET Using Visual BasicIn Design View, you canactually drag an Event Log or Performance Counterinto the form towrite code to adjust its properties. Aside from thesepro-grammaticcapabilities, the Server Explorer does provide thatone-stopmanagement shop.The Data Connections node allows you toconnect your application to a datasource. Right-click the DataConnections node and choose Add Connection toadd a new connection.After selecting a Data Provider (I picked SQL Server),the AddConnection dialog box appears, as shown in Figure 2-7.Visual Studioinstalls SQL Server Express as part of the package ofprogramsprovided. If you have access to no other databases, you canalways use thatone. It will appear as Machine/SqlExpress in the AddConnection dialog box.In Figure 2-7, I selected my local machine(XP), the SQL Express instance, andthe Northwind database. Youprobably dont have the Northwind databaseinstalled by default. Youcan get it from www.microsoft.com/downloadsorwww.vbfordummies.net.This selection connects your project with adatabase, which then allows youto use the Data Sources window,manage the data objects within the data-base,and edit datadirectly. When you have finished adding the values totheconnection, click the Test Connection button to make sure thatyour projectcan get the database you selected.Figure 2-7:TheAddConnectiondialog box. 49. Dynamically editing data withthe DataSources windowWhen you start a new project, the Data Sources windowsays Your projectcurrently has no data sources associated with it.(If you cant see the DataSources window, choose DataShow DataSources with a project open, orpress Shift+Alt+D.) To maintain datain the .NET world, as with any otherenvironment, you must connectyour application to a data source. The DataSources window is theprimary way to do that.To connect to a data source (like a databaseor XML file), follow these steps:1. Click the Add a New Data Sourcebutton.Doing so starts the Data Source Configuration Wizard.2.Click the Next button.The wizard shows the data source options. Youcan select the Databaseoption to use an SQL Server or Oracledatabase, the Service option toconnect to an XML Web service, orthe Object option to connect to adata access layer.3. Select theconnection to Northwind that you made in the Accessingoutsideresources with the Server Explorer section, and then clickthe Nextbutton (shown in Figure 2-8).Figure 2-8:TheDataSourceConfigurationWizard.Chapter 2: Using Visual Studio 200833 50. 34 Part I: Getting to Know .NET Using Visual Basic4. Acceptthe default connection name (probably NorthwindConnection)and clickthe Next button.You are given a choice of what objects to includein your dataset. I coverdatasets in Chapter 15.5. For now, selectthe first view in the Views checklist: Alphabetical ListofProducts.6. Click the Finish button.As shown in Figure 2-9, each ofthe columns in the view you selected appearsas the editable objecttypes that can represent them. You can now drag themto the DesignView to create a data-bound control.Just for fun, drag theQuantityPerUnit field onto the blank form that was cre-atedfor youwhen you started the project. Visual Studio will create a bunchofdata piping for you and then add the field and a label to the form.Using theData Sources window like this provides you with fantasticfunctionality forquickly developing data applications.In Figure2-10, I have a picture of my screen as I dragged the field intotheform. You can see in the Design View bottom, where thebackground is gray,that five components have been added to Form1.Components are functionalitems from the Toolbox, not things thatare visible on the screen. The DataSources window makes all thosecomponents and adds the control to thepage, just based on the fieldyou moved. That is the point of these RAD tools.Frankly, theDiagram View is a very sophisticated tool, which I dont coverinthis book. It allows enterprise architects to buildcomponent-based softwareby taking whole blocks of code and movingthem in a graphic environment.Figure 2-9:The DataSourceswindow. 51.Every now and again, when you have written something in VisualBasic, goahead and load up the Diagram View. You can enter DiagramView by right-clickinga file in the Solution Explorer and selectingView in Designer from thecontext-sensitive menu. It will create anew file called Classdiagram1.cd inyour Solution Explorer and showyou the piping behind the software youhave built. It can be aneducational experience try it!Moving a Tool WindowYou can customizethe Visual Studio environment to make it easier for youto work in.All the 2ff7e9595c
Comments