VisualBasic2005Jumpstart
ByWei-MengLee
...............................................
Publisher:O'Reilly
PubDate:September2005
ISBN:0-596-10071-X
Pages:214
TableofContents|Index|Errata
Okay,allyouVB6developers--time'sup.AsofMarch2005,Microsoftnolonger
supportsthisversionofVisualBasic.Andyoucan'tblamethem.Threeyearsago,
theyintroducedthe.NETFramework--anelegant,powerfulplatform--alongwiththe
newcomponent-basedVB.NETlanguage.Butroughlyfivemillionofyoudecidedto
stickwithVB6,mostlytomaintainlegacyWindowsandCOMprojects.
Now,withtheupcomingreleaseofVB2005,Microsofthasseveralattractivereasons
toupgradethatyou'llfindhardtoresist,includingthereturnofsomeVB6features.
Andwehavetheperfectbooktohelpyoumaketheconversion:VisualBasic2005
Jumpstart.Now,youcantest-drivethebetaversionofVB2005withthreehands-on
projectsthatenableyoutolearnthesyntaxofthisnewlanguagequickly.
VB2005notonlyletsyouconvertthebulkofyourexistingVB6code,butoffers
severalfamiliarfeatures,suchascompile-and-rundebugging,newMyClassesthat
simplifyuseof.NETlibrariesandframeworks,lotsofIDEsupportforWindows,web
andmobileGUIdevelopment,anddataaccesscontrolsthatcloselyresemblewhat
youusenow.Therealplusisthatyou'llbeusingthesefeatureswiththe.NET
platform,whichismoresecure,lesscomplexthanCOM,andoffersOneClick
deployment.
VisualBasic2005Jumpstartletsyougetthefeelofthisplatformforbuilding
smart/richWindowsFormsclients,ASP.NETwebapplications,andwebservices.
AuthorWei-MengLee,aMicrosoft.NETMVP,veteranO'Reillyauthorandfrequent
contributortotheO'ReillyNetwork,hasputtogetherthreeusefultest-driveprojects,
completewithcodesamples,thatletyoudevelop:
ApersonallibraryWindowsapplication
AWeb-basedshoppingcartapplication
AstockenquiryWebService
Ourjumpstartguideisthequick,painlesswaytomigratefromVB6toVB2005,and
theperfecttrainingmanualformovingyourorganizationtothemorerobust,dynamic
andsecureworldof.NET.
VisualBasic2005Jumpstart
ByWei-MengLee
...............................................
Publisher:O'Reilly
PubDate:September2005
ISBN:0-596-10071-X
Pages:214
TableofContents|Index|Errata
Copyright
AbouttheAuthor
Foreword
Preface
WhoThisBookIsFor
WhatYouNeedtoUseThisBook
ConventionsUsedinThisBook
UsingCodeExamples
SafariEnabled
I'dLiketoHearfromYou
CommentsandQuestions
Acknowledgments
Chapter1.IntroducingVisualBasic2005
Section1.1.CreatetheApplicationandItsMainWindow
Section1.2.AddaMenuandToolbar
Section1.3.ConnecttoaDatabaseandBrowseRecords
Section1.4.CreateanExitDialogBox
Section1.5.HandleExitandCloseEvents
Section1.6.RunandDebugtheApplication
Section1.7.InspectanObjectatRuntime
Section1.8.AddanAboutBox
Section1.9.ConfiguretheApplication
Section1.10.Summary
Chapter2.ProgrammingwithVisualBasic
Section2.1.DataTypes
Section2.2.Variables
Section2.3.Constants
Section2.4.Strings
Section2.5.Arrays
Section2.6.TypeConversion
Section2.7.Operators
Section2.8.Statements
Section2.9.FunctionsandSubroutines
Section2.10.ErrorHandling
Section2.11.MyNamespace
Section2.12.Summary
Chapter3.PuttingObject-OrientedProgrammingtoWork
Section3.1.WorkingwithClassesandObjects
Section3.2.ReusingandCustomizingClasses
Section3.3.DesigningYourOwnClasses
Section3.4.ControllingHowClassesAreImplemented
Section3.5.Summary
Chapter4.DevelopingaWindowsApplication
Section4.1.CreatingtheWindowsApplicationandBuildingtheMainWindow
Section4.2.ViewingBookInformationOffline
Section4.3.DeployingtheApplication
Section4.4.AutomaticUpdating
Section4.5.Summary
Chapter5.BuildingWebApplications
Section5.1.BuildingtheStorefront
Section5.2.CreatingaShoppingCart
Section5.3.MembersArea
Section5.4.TestingtheApplication
Section5.5.Summary
Chapter6.MovingfromVB6toVB2005
Section6.1.Migrate,Replace,Rewrite,orReuse?
Section6.2.UsingCOMObjectsinVB2005
Section6.3.UpgradingVB6Applications
Section6.4.Summary
Colophon
Index
Copyright
Copyright©2005O'ReillyMedia,Inc.Allrightsreserved.
PrintedintheUnitedStatesofAmerica.
PublishedbyO'ReillyMedia,Inc.,1005GravensteinHighwayNorth,
Sebastopol,CA95472.
O'Reillybooksmaybepurchasedforeducational,business,orsalespromotional
use.Onlineeditionsarealsoavailableformosttitles(safari.oreilly.com).For
moreinformation,contactourcorporate/institutionalsalesdepartment:(800)
998-9938or
Table
Editor:
JohnOsborn
ProductionEditor:
AdamWitwer
CoverDesigner:
EllieVolckhausen
InteriorDesigner:
DavidFutato
PrintingHistory:
September2005:
FirstEdition.
NutshellHandbook,theNutshellHandbooklogo,andtheO'Reillylogoare
registeredtrademarksofO'ReillyMedia,Inc.VisualBasic2005Jumpstart,the
imageofmoorfrogs,andrelatedtradedressaretrademarksofO'ReillyMedia,
Inc.
Microsoft,MSDN,the.NETlogo,VisualBasic,VisualC++,VisualStudio,and
WindowsareregisteredtrademarksofMicrosoftCorporation.
Manyofthedesignationsusedbymanufacturersandsellerstodistinguishtheir
productsareclaimedastrademarks.Wherethosedesignationsappearinthis
book,andO'ReillyMedia,Inc.wasawareofatrademarkclaim,thedesignations
havebeenprintedincapsorinitialcaps.
Whileeveryprecautionhasbeentakeninthepreparationofthisbook,the
publisherandauthorassumenoresponsibilityforerrorsoromissions,orfor
damagesresultingfromtheuseoftheinformationcontainedherein.
ThisbookusesRepKover™,adurableandflexiblelay-flatbinding.
ISBN:0-596-10071-X
[M]
AbouttheAuthor
Wei-MengLee(MicrosoftMVP)isatechnologistandfounderofDeveloper
LearningSolutions(),atechnology
companyspecializinginhands-ontraininginthelatestMicrosofttechnologies.
Wei-Mengspeaksregularlyatinternationalconferencesandhasauthored
numerousbookson.NET,XML,andwirelesstechnologies,includingASP.NET
2.0:ADeveloper'sNotebookandthe.NETCompactFrameworkPocketGuide
(bothfromO'Reilly).HewritesextensivelyfortheO'ReillyNetworkontopics
rangingfrom.NETtoMacOSX.Wei-MengiscurrentlyaMicrosoftRegional
DirectorforSingapore.VisitWei-Meng'sblogat
.
Foreword
VisualBasicrevolutionizedprogrammingwhenitwasfirstreleasedin1991by
makingiteasierthaneverfordeveloperstobuildWindowsprograms.This
successcontinuedwithVisualBasic6.0,whichbecameoneoftheworld'smost
popularprogramminglanguages.ThetransitionfromVisualBasic6.0toVisual
Basic.NEToffereddevelopersanewrangeofdevelopmentpossibilities.Using
thesamesetofdevelopmentskills,developerscouldnowtargetWindows,Web,
Mobile,andOfficeapplicationsbetterthaneverbefore.VisualBasic2005isthe
mostpowerfulandaccessibleversionofVisualBasic.Theadditionoffeatures
liketheMynamespaceandEditandContinuehelpdeveloperstoaddress
businessproblemswiththeproductivitythatisthehallmarkofVisualBasic
development.
ThisbookisagreatwaytotakeyourVisualBasic6.0developmentskills
forwardtobecomeanexpertinVisualBasic2005programming.I'mhappyto
havepartneredwithWei-MengandO'Reillytocreatethisbookwhichisapart
ofanongoingefforttoenableVisualBasic6.0developerstoleveragetheir
existingskills.ExperiencedVBprogrammerswillseehowtheirexistingVisual
BasicskillscanbeappliedtoquicklybecomeproductiveinVisualBasic2005.
Ihopethatyoufindthisbookusefulandlookforwardtohearingfromyouwith
anycomments.Pleasefeelfreetocontactmedirectlyat
JayRoxe
ProductManager,VisualBasic
MicrosoftCorporation
Preface
WhoThisBookIsFor
WhatYouNeedtoUseThisBook
ConventionsUsedinThisBook
UsingCodeExamples
SafariEnabled
I'dLiketoHearfromYou
CommentsandQuestions
Acknowledgments
WhoThisBookIsFor
VisualBasic2005JumpstartiswrittenforVB6programmerswhohaveyetto
movetoVisualBasic2005,thelatestreleaseofMicrosoftVisualBasic,oneof
theworld'smostpopularprogramminglanguages.WithVB2005,Microsofthas
givenVB6developersahostofreasonstoupgradenow,includingthereturnof
VB6featuresomittedfromearlierversionsofVB.NET.
Myaimistoprovideyouwithastartingpointajumpstartthatdemonstrateshow
easyitistobecomeproductivewiththenewlanguagewhenit'spairedwiththe
VisualStudio2005developmentenvironment.
Togetthemostoutofthisbook,you'llneedacopyofVisualStudio2005that
supportsVisualBasic(see"WhatYouNeedtoUseThisBook").Iencourage
youtoworkyourwaythroughthesampleapplications,especiallythosein
Chapters1,Chapters4,andChapters5,astheyarepurposefullysmalland
designedtoshowoffthebestofthenewfeaturesinVB2005.You'llbesurprised
athoweasilyandquicklyyoucanbuildarelativelysophisticatedWindowsor
webapplication.Thecompletesourcecodeforthebook(alongwithanyerrata)
isavailableontheO'Reillywebpageforthisbook,
/>
HowThisBookIsOrganized
VisualBasic2005Jumpstartconsistsofsixchapters,eachofwhichfocusesona
particularaspectoftheVB2005languageoratypeofprojectthatVB6
programmersarelikelytoencounterinmakingthemovetothenewtool.
Chapter1,IntroducingVisualBasic2005
You'lluseVB2005andVisualStudio2005tobuildasimpleWindows
applicationthatanyVB6programmerwillrecognize.Thoughthe
applicationissimple,buildingitillustratesanumberofpowerfulfeatures
presentintheVB2005languageandtheVisualStudio2005development
tool.AmongthesearenewWindowscontrolswithSmartTasks,new
Windowsapplicationtemplates,restoredsupportforedit-and-continue,
improvedIntelliSenseandCodeEditorfacilities,theDataSource
ConfigurationWizard,andApplicationSettings.
Chapter2,ProgrammingwithVisualBasic
youwillbetakenonawhirlwindtouroftheVB2005languageandits
syntax,andyou'llseehowitcompareswiththatofVB6.IfyouareaVB6
programmer,you'llbehappytolearnthatmuchofwhatyoualreadyknow
isstillsupported(orenhanced)inVB2005.You'llalsobeintroducedtothe
Mynamespace,whichvastlyexpandsthetroveoffunctionsavailableto
VisualBasicprogrammersandprovideseasieraccesstotherich
functionalityofthe.NETFrameworkClassLibrary.
Chapter3,PuttingObject-OrientedProgrammingtoWork
Youwillbeintroducedtothesupportforobject-orientedprogramming
(OOP)availableinVB2005andwilllearnwhyitmatters.Aprincipal
reasonforusingOOPfeaturesinVB2005isthesupporttheyprovidefor
reusing,customizing,andcontrollingtheuseothersmakeofyourcode,and
you'lllearnaboutavarietyoftechniquesforaccomplishingthesetasks.
You'llalsolearnabouttheVB2005ClassDesigner,howtoextendan
existingclassbyinheritingfromit,genericclasses,Partialclasses,and
advancedOOPconceptssuchasabstractclassesandmethods,interfaces,
attributes,andaccessmodifiers.
Chapter4,DevelopingaWindowsApplication
YouwillbuildaWindowsapplicationthatdemonstratestheeasewith
whichVisualStudio2005andVB2005canbeusedtocreateprofessional
Windowsapplications.Youwillalsolearnhowtoconsumewebservices
andhowdatacanbepersistedinaSQLdatabase,andyouwillseehow
ClickOncemakesdeploymentandupdatingofsmartclientseasyand
effortless.
Chapter5,BuildingWebApplications
Youwillbuildasimplee-commercewebapplicationusingnewcontrolsin
ASP.NET2.0thatletyoubuildpowerfulapplicationswithoutwritingmuch
VB2005codeatall.YouwillseehowtouseaMasterPagetomaintaina
consistentlookandfeelforthepagesofyoursite.Youwillalsoseehow
informationaboutuserscouldbepersistedusingthenewProfileservice.
Lastbutnotleast,youwilllearnhoweasyitistoimplementsecurityin
yourwebapplicationsusingnewASP.NET2.0securitycontrolswiththe
Membershipclassthatpowersthem.
Chapter6,MovingfromVB6toVB2005
Youwilllearnaboutthevariousfactorsthatyouneedtoconsiderwhen
decidingwhethertoupgradeanexisitngapplication.UpgradingfromVB6
toVB2005requirescarefulreviewoftheapplicationaswellasanalysisof
thevariousbenefitsthatamigrationwillbringyou.Youwillalsolearnhow
youcancontinuetouseyourlegacyCOMcomponentsinVB2005and
howthenewRegFreeCOMfeatureinVB2005shieldsyoufromthe
notoriousDLLhellproblem.Finally,thechapterendswithademonstration
oftheVisualBasic6.0CodeAdvisorandtheUpgradeWizard,whichaim
toeasetheupgradeofyourexistingVB6applicationstoVB2005,should
youdecidetogothatroute.
WhatYouNeedtoUseThisBook
Totryoutthemanyhands-onprojectsandcodesamplesinthisbook,you'llneed
toinstallanyeditionofVisualStudio2005onacomputerrunningWindows.
YoucanalsouseacombinationofthenewVisualStudioExpressEditions.To
workyourwaythroughalloftheexamples,you'llneedtoinstallVisualBasic
2005ExpressEdition,VisualWebDeveloper2005ExpressEdition,andSQL
Server2005ExpressEdition,allofwhichareavailableontheMSDNwebsite.
ConventionsUsedinThisBook
Thefollowingtypographicalconventionsareusedinthisbook:
Plaintext
Indicatesmenutitles,menuoptions,menubuttons,andkeyboard
accelerators(suchasAltandCtrl).
Italic
Indicatesnewterms,URLs,emailaddresses,filenames,fileextensions,
pathnames,directories,andUnixutilities.
Constantwidth
Indicatescommands,options,switches,variables,attributes,keys,
functions,types,controls,classes,namespaces,methods,modules,
properties,parameters,values,objects,events,eventhandlers,XMLtags,
HTMLtags,macros,thecontentsoffiles,ortheoutputfromcommands.
Constantwidthbold
Showscommandsorothertextthatshouldbetypedliterallybytheuser.
Boldisalsousedincodesamplestohighlightlinesofcodethatare
discussedinthetext.
Constantwidthitalic
Showstextthatshouldbereplacedwithuser-suppliedvalues.
Thisiconsignifiesatip,suggestion,orgeneralnote.
Thisiconindicatesawarningorcaution.
UsingCodeExamples
Thisbookisheretohelpyougetyourjobdone.Ingeneral,youmayusethe
codeinthisbookinyourprogramsanddocumentation.Youdonotneedto
contactusforpermissionunlessyou'rereproducingasignificantportionofthe
code.Forexample,writingaprogramthatusesseveralchunksofcodefromthis
bookdoesnotrequirepermission.SellingordistributingaCD-ROMof
examplesfromO'Reillybooksdoesrequirepermission.Answeringaquestionby
citingthisbookandquotingexamplecodedoesnotrequirepermission.
Incorporatingasignificantamountofexamplecodefromthisbookintoyour
product'sdocumentationdoesrequirepermission.
Weappreciate,butdonotrequire,attribution.Anattributionusuallyincludesthe
title,author,publisher,andISBN.Forexample:"VisualBasic2005Jumpstart,
byWei-MengLee.Copyright2005O'ReillyMedia,Inc.,0-596-10071-X."
Ifyoufeelyouruseofcodeexamplesfallsoutsidefairuseorthepermission
givenabove,feelfreetocontactusat
SafariEnabled
WhenyouseeaSafari®Enabledicononthecoverofyourfavorite
technologybook,thatmeansthebookisavailableonlinethroughtheO'Reilly
NetworkSafariBookshelf.
Safarioffersasolutionthat'sbetterthane-books.It'savirtuallibrarythatlets
youeasilysearchthousandsoftoptechbooks,cutandpastecodesamples,
downloadchapters,andfindquickanswerswhenyouneedthemostaccurate,
currentinformation.Tryitforfreeat.
I'dLiketoHearfromYou
Pleasesendcomments,suggestions,anderratato
Youcanalsovisitmywebsiteat:
foralistofarticlesthatIhavewrittenon.NET.CheckouttheCodeLibrary
sectiontodownloadsamplecodefortopicson.NET,VB2005,ASP.NET2.0,
andthe.NETCompactFramework.
CommentsandQuestions
Pleaseaddresscommentsandquestionsconcerningthisbooktothepublisher:
O'ReillyMedia,Inc.
1005GravensteinHighwayNorth
Sebastopol,CA95472
(800)998-9938(intheUnitedStatesorCanada)
(707)829-0515(internationalorlocal)
(707)829-0104(fax)
Wehaveawebpageforthisbook,wherewelisterrata,examples,andany
additionalinformation.Youcanaccessthispageat:
/>Tocommentorasktechnicalquestionsaboutthisbook,sendemailto:
Formoreinformationaboutourbooks,conferences,ResourceCenters,andthe
O'ReillyNetwork,seeourwebsiteat:
Acknowledgments
Iamverygratefultomyeditor,JohnOsborn,forgivingmethisopportunityto
writeabookonVB2005.Hispatienceandattentiontodetailhavedefinitely
madethisbookabetterread.Johnhaspainstakinglyreadandrereadeverysingle
wordIhavewrittenandhasalwayschallengedmetorethinkwhatIhave
written,andforthisIammuchhonoredtoworkwithJohn.Abigthankyou,
John!
SpecialthanksarealsoduetoJayRoxe,ProductManagerofVisualBasicat
Microsoft,forhissupportandreviewofthisbook.Jayhasplayedan
instrumentalroleinshapingtheoutlineofthisbookandprovidedmanyuseful
suggestionsforimprovingitscontent.Thanksforthehardwork,Jay!
Ialsowishtoexpressmygratitudetothereviewersfortheircommentsand
numeroussuggestions.TheyincludeRobertGreen,JeffBarr,PaulYuknewicz,
andJosephBinder.
Asalways,ithasbeenapleasureworkingwiththeO'Reillyteam.Abigthank
youtotheunsungheroesbehindthescenesthatmadethisbookpossible.
Thanks!
Chapter1.IntroducingVisualBasic2005
WhenMicrosoftreleaseditsnewversionofVisualBasicin2002,many
developerswillinglyupgradedtotakeadvantageofthenewwebfunctionality,
security,andperformanceprovidedbythe.NETplatformonwhichitwasbuilt.
Butindoingso,manyalsofelttheywereleavingbehindthefeaturesthathad
madeVisualBasic6.0suchapopulartoolfortherapiddevelopmentof
Windowsapplicationsinthefirstplace.
ThereleaseofVisualBasic2005(VB2005)isinmanywaysareturntoVisual
Basic'srootsastheRapidApplicationDevelopment(RAD)toolofchoice.Many
ofthemostpopularfeaturesofearlierversionsareback,suchasEditand
Continue,alongwithdozensofnewcontrols,betterIntelliSense,animproved
debugger,andahostofothertoolsthatspeedupprogramming,debugging,
testing,anddeployment.
Besidesthemanytoolsaddedtoitsinteractivedevelopmentenvironment(IDE),
VisualBasic2005providesmoresupportthaneverfordevelopingthenext
generationofnetwork-enabledWindowsclientsandwebapplications,whilea
newsetoffunctionalityuniquetoVB2005theMynamespacegivesyouthe
meansbywhichtoperformmanycommontaskswithouthavingtoworkyour
waythroughthecomplextypesofthe.NETclasslibraries.
ThebestwaytolearnaboutVisualStudio2005isbyusingthetooltobuildan
application.Inthefollowingsections,you'llassembleastraightforward
Windowsclientthatenablesuserstoconnecttoadatabaseandbrowseorupdate
theinformationtheyfindthere.You'llworkwiththeauthorstableofthepub's
databasethatshipswithSQLServer2005.You'llalsoseehowyoucanextend
theapplicationusingsomeofthefeaturesnewtoVB2005,suchasproject
templatesandapplicationconfigurationtools.Figure1-1showshowthemain
windowofthethecompletedapplicationwilllookwhenyou'vefinishedyour
work.
AlthoughthisbookusesMicrosoftVisualStudio2005asthetoolto
buildthesampleapplications,youcanalsouseMicrosoftVisualBasic
2005ExpressEdition.
Figure1-1.ThecompletedpubsdatabaseWindowsclient
1.1.CreatetheApplicationandItsMainWindow
Let'sstartbyusingVisualStudio2005tocreateaWindowsapplication,onethat
youcanprogramwithVB2005.
1. First,youneedtofireupVisualStudio2005andopenanewprojectby
selectingFile NewProject…ontheVisualStudio2005menu.Visual
StudiodisplaystheNewProjectdialogshowninFigure1-2.
2. IntheProjecttypeswindowoftheNewProjectdialog,selectVisualBasic
andthenselecttheWindowsApplicationtemplateintheVisualStudio
installedtemplatesdialogwindow.KeepthedefaultprojectName,
WindowsApplication1,providedbyVisualStudio.ClickOK.
VisualStudio2005willpresentyouwithitsfamiliarWindowsdevelopment
environment,showninFigure1-3,includingadesignersurfaceforForm1,
whichwillbecomethestartupwindowofyourapplication.
1.2.AddaMenuandToolbar
Let'snowaddamenuandtoolbartotheform.InVB2005,youcancreate
professionallookingWindowsapplications,completewithmenusandtoolbars
thatlooklikethoseusedwithMicrosoftOfficeapplications.
Figure1-2.CreatinganewWindowsapplication
Figure1-3.ThedevelopmentenvironmentofVisualStudio2005
1. IntheMenus&ToolbarstabinToolbox,showninFigure1-4,locateand
thendraganddroptheToolStripContainercontrolontotheform.
TheToolStripContainercontrolallowsothercontrols(suchasthe
ToolStripcontrol)toanchorinthefourpositionsavailable(left,right,
top,andbottom).
Figure1-4.ThevariouscontrolsundertheMenus&Toolbars
tabinToolbox
IntheToolStripContainerTasksmenu,clickonthe"DockFillin
Form"link(seeFigure1-5)todocktheToolStripContainercontrol
ontotheform.ThiswillcausetheToolStripContainercontroltofill
uptheentireformandautomaticallyresizeitselfwhentheformisresized.