Professional Documents
Culture Documents
VisualBasicNotes
VisualBasic.NETClassNotes
Introduction
StepstoCreatingaProgram
SystemDevelopmentLifecycle
VisualBasicIDE
Controls/Objects
ObjectNamingConventions
ObjectProperties
ObjectMethods
ObjectEvents
AddingCodetoaVBProgram
Outputtingdata
InternalDocumentation
DataTypes
Variables
AssigningValuestoVariables
ArithmeticOperators
Constants
Inputtingdata
SimpleIPOcharts
SelectionIF
CompoundSelection
IPOSelection
CountedRepetitionFor
IPORepetition
UncountedRepetitionDo
FileInputandOutput
CountingandAccumulating
TerminatingaForm
Debugging
MathFunctions
StringObjectMethods
StringObjectNumericFunctions
FormatFunctions
RandomNumbers
Subprograms
UserDefinedFunctions
VariableScope
FormLoad
MessageBox
InputBox
ShowingMultipleForms
ModalForms
Arrays
DynamicArrays
MultidimensionalArrays
StopWatchObject
Searching
Sorting
Menus
TimerObjects
MovingImages(Animation)
ReadingfromanAccessDatabase
ListViewControl
ListBoxControl
WhatisComputerProgramming?
Aprogramisasetofinstructionsthatguidethecomputerincarryingoutaspecifictask.Towriteaprogramyouneedtohaveaprogramming
language(software)suchas:VisualBasic,Turing,Basic,Java,Fortran,Cobol,C++,etc.TheseareEnglishlikelanguagesthathumanscan
read,understandandwrite,howeverthecomputercannotunderstandtheselanguages!Inorderforthecomputertocarryouttheinstructions,
theprogrammustbetranslatedtoalanguagethemachineunderstands,calledmachinelanguageandthenexecuted.Theprogramswewritein
VisualBasicarefirsttranslatedbytheVBsoftware.Whenthestatementsintheoriginalorsourceprogramaretranslatedtomachinelanguage,
calledtheobjectprogram,theprogramissaidtobecompiledandreadyforexecution
WhyWritePrograms
Allthesoftwareweuseonthecomputerareprogramswrittentocarryoutvariousapplications.EvenDOSandWindowsisaprogram(orsetof
programs)writtenasaninterfacebetweentheuserandthehardware.DOSandWindowsareoperatingsystems.Withoutoneofthemwe
wouldneedtoknowagreatdealmoretocommunicatewith,andmanagethehardwarecomponentsofthecomputersystem.Windowsisa
softwarepackagethatallowsustoworkinDOSwithoutneedingtounderstandallthebuiltincommands.Itmakesthecomputerfriendliertouse
becausethemenusandiconsreplacetheneedtorememberalltheDOScommands.
Thereissoftwarereferredtoasapplicationsoftwaresuchaswordprocessors(MSWorks/Word),spreadsheets(Works,Lotus,Excel),desktop
publishing(Pagemaker,VenturaPublisher),databaseprograms(Access,dBASE,Paradox,)graphicsprograms(CorelDRAW,AutoCAD)and
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
1/64
11/6/2016
VisualBasicNotes
communicationssoftware(PCtalk,HyperAccess).Theseprogramsarebuilttotoparticulartypesofjobsandallowustoprocessinformation
easily.
Ifinformationneedstobeprocessedinarepetitivemannerthenprogrammingacomputertocarryoutthetaskwillmakethejobquickerand
easier.
StepsToCreatingaProgram:
Softwarereferstoacollectionofinstructions,calledaprogram(VBcallsthemasolution)thatdirectsthehardware(monitor,keyboard,mouse,
CPUetc.)
Thefirststepinwritinginstructionstocarryoutataskistodeterminewhattheoutputshouldbe.Thesecondstepistoidentifythedata,orinput,
necessarytoobtaintheoutput.Thelaststepistodeterminehowtoprocesstheinputtoobtaintheoutput.Therefore,theproblemsolvingprocess
usedwillalwaysconsistofthreesteps:
1.input
2.processing
3.output
Whensolvingacomputerproblem,eachassignmentasksyoutofirstcreateanIPOchart.IPOstandsforinput,processingandoutput.IPO
chartsaredonebeforeyoustarttocode.IPOchartsstatetheprocessinginastructuredenglish,sometimescalledpseudocode.Forexample:
CreateanIPOchartforaprogramthatwillallowapersontoinputanamounttobedepositedinabankaccount,theinterestrateandthenumber
ofyearsthemoneywillbeleftintheaccount.Printtheamountofmoneyintheaccountattheendofthetime.
Input
Processing
Output
amountdeposited
interestrate
numberofyears
finalamount=amountdeposited
repeatforthenumberofyears
finalamount=finalamount+finalamount*interestrate
finalamount
NoticethattheIPOchart'explains'howtochangetheinputtotheoutput.Alltheinputsareusedintheprocessingandtheoutputsareclearly
calculatedintheprocessing.TheprocessingisstructuredandindentedsimilartoVBprogramsbutthelanguageismorelike'normal'English
thanaprogramminglanguage.ManyVBdetailsarenotincluded,suchasdim,endif,next,toString,becausetheyare'understood'tobeneeded
whenyoustarttocode.
SystemDevelopmentLifecycle
Whenworkinginteamsofprogrammers,oronlargeprogrammingprojects,itisimportanttostayorganized.Manyefficientprogrammersplan
theirprogramsusingthesystemdevelopmentlifecycleorSDLC.Thestepbystepprocessisshownbelow:
Step
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
Explanation
Howto..
2/64
11/6/2016
VisualBasicNotes
Analysis
Defineandunderstandtheproblem
Besureyouunderstandwhattheprogramshoulddo,thatis,whattheinputandoutputshouldbe.
Findalogicalsequenceofprecisestepsthatsolvetheproblem.CreatetheIPOchart,inthisclass.
Planthesolutiontotheproblem
AsequenceofstepssuchasthisiscalledanAlgorithm.Threepopularmethodsusedtodeveloplogicalplans
areflowcharts,pseudocodeandtopdowncharts.Thesetoolsormethodswillassisttheprogrammerin
breakingdownalargeproblemintosmallertasks.
ChoosetheInterface
Determinehowtheinputwillbeobtainedandhowtheoutputwillbedisplayedlayouttheform(s)
Development
Code
Createtheformandtranslatethealgorithmintoaprogramminglanguage.Theprogramiswrittenduringthis
stage.Writecommentsinsidetheprogramthatexplaintootherprogrammerswhatthecodeisdoing.
Testing
TestandDebug
Locateandremoveanyerrorsintheprogram.
Implementation
Installtheworkingprogramontheuser'scomputer
andtraintheuser
Writedocumentationthatisintendedtoallowanotherpersontounderstandtheprogramandtraintheuser
howtousetheprogram.
Design
Thismethodoforganizingaprogrammingprojectissometimescalledthewaterfallmethod,becausethestepsproceedfromonetothenext,
likewaterfallingdownfromsteptostep.
Thereareotherprojectmethodologiesthatexistsuchas:
rapidapplicationdevelopment(RAD)
jointapplicationdevelop(JAD)
spiralmodel
synchronizeandstabilize
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
3/64
11/6/2016
VisualBasicNotes
extremeprogramming(XP)
Allthesemethodologiesareusedtocoordinateteamsofprogrammersworkingonlargeprojects.Eachmethodologyhasitsstrengthsand
weaknesses.
VisualBasicProgrammingEnvironment(IDEIntegratedDevelopmentEnvironment)
Controls/Objects
InVB,aprogramisstartedbydrawingtheuserinterface(thepartoftheprogramauserwillsee)onaform(therectangularareawiththegrid
marksinthecenteroftheIDE).Allthecontrolsyoucanplaceonaformareinthetoolbox,ontheleftsideoftheIDE.Controlsyouplaceona
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
4/64
11/6/2016
VisualBasicNotes
formandtheformitselfarecalledobjects.
Examplesofobjects:
formawindowsscreen
button
labelusercannotchangeduringruntime
textBoxusercanchangeduringruntime
horizontalscrollbar
pictureBox
TheToolboxcontainsthefollowingstandardcontrols:
PictureBox
Label
TextBox
Button
GroupBox
CheckBox
RadioButton
ComboBox
ListBox
HorizontalScrollBar
VerticalScrollBar
Timer
Whenplacingseveralobjectsonaform,usethecommandsontheFormatmenutoplace,size,andaligntheobjects.First,dragthemouse
aroundtheobjectstoselectthem.UsingthecommandsontheFormatmenu,youcanthenalignorsizetheobjectsasnecessary.Object
propertiescangenerallybesetateitherdesigntimeorruntime
HereisaformwithLabel,TextBoxandButtonobjects.
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
5/64
11/6/2016
VisualBasicNotes
LabelControl
Alabelisagraphicalcontrolusedtodisplaytext.Theusercannoteditthetextinalabel.ThemostcommonuseforaLabelcontrolistoidentify
controlsthatdonothaveaCaptionproperty,suchastheTextBoxcontrol.YoucanalsousetheLabelcontroltodisplaytextsuchasstatus
messagesandotherprograminformation.
TextBoxControl
YouuseaTextBoxcontroltoobtaininformationfromtheuserortodisplayinformationprovidedbytheapplication.Unlikeinformationdisplayedin
alabel,theusercanchangeinformationdisplayedinatextbox.
TextBoxobjectshavea'ReadOnly'property,thatwhensetto'true'doesnotallowtheusertotypeintothetextbox.
ButtonControl:
AButtonperformsataskwhentheuserclicksthebutton.YouuseaButtoncontroltobegin,interrupt,orendaprocess.Whenclicked,a
commandbuttonappearstobepushedinandsoissometimescalledapushbutton.ThemostcommoneventforaButtoncontrolistheClick
event.
ObjectNamingConventions
Allobjectsyouplaceonaformmustbegivenaname,inthiscourse.Anobject'snameisusedtorefertotheobjectinyourprogramcode.You
canassignanynametoanobject,butitisagoodideatoadoptanamingconventionanduseitconsistentlythroughoutyourprograms.
ThefollowingtableliststhestandardnamingconventionsusedinVisualBasic.Adoptingtheseconventionsmakesiteasierforothersfamiliar
withthestandardnamingconventionstounderstandyourcode.
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
6/64
11/6/2016
VisualBasicNotes
SuggestedPrefixesforControls
ControlType
Prefix
Example
Checkbox
chk
chkReadOnly
Combobox,dropdownlistbox
cbo
cboEnglish
Button
btn
btnExit
Form
frm
frmEntry
Horizontalscrollbar
hsb
hsbVolume
Label
lbl
lblHelpMessage
Listbox
lst
lstPolicyCodes
Menu
mnu
mnuFileOpen
Radiobutton
rad
radGender
Picturebox
pic
picVGA
Textbox
txt
txtLastName
Timer
tmr
tmrAlarm
Verticalscrollbar
vsb
vsbRate
Properties
Propertiesdefinetheappearanceandbehaviorofobjects.Text,Font,andNamearecommonexamplesofproperties.Propertiesarethe
attributesyousetorretrieve.Eachobjecthasalonglistofproperties.Thesepropertiesareveryimportanttomakingthescreenlookrightandto
makingtheprogramactright.
SettingPropertiesatDesignTime:
Designtimeisthetimewhenyouarelayingoutyourformandwritingyourprogramcode.Mostpropertiesofanyobjectmaybesetatdesign
time.Whenanobjectontheformisselected,thepropertiesfortheobjectaredisplayedontherightsideoftheIDE.Tochangeorsetaproperty,
simplytypeyourdesiredchangeintheareanexttothepropertyname.
ExamplesofLabelproperties:
textthetextthatappearsonthescreen
namethenameoftheobject
NB:WewillneverleavethenamesLabel1,Label2,etcbecausethesearenotmeaningfulnamesandwillbeconfusing.
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
7/64
11/6/2016
VisualBasicNotes
Wewillusethesuggestedprefix(seeabove)andmeaningfulnamessothatothersfamiliarwiththestandardnamingconventionswillmoreeasily
understandyourcode.Eg.changethenameofLabel1tolblTitle
fontcontrolsthefont,size,style(bolditalics)
forecolorcontrolsthecolourofletters.Thepropertieswindowshowsacodednumber(morelateronthehexnumber)
backcolorcontrolsthebackgroundcolorofthelabel(abox)
visiblecontrolswhetherthelabelisvisibleornot(TrueorFalse)
ExamplesofFormproperties:
backcolorcontrolsthebackgroundcolorofthewholescreen
textthetextthatappearsintheform'stitlebar
windowstatecontrolshowbigthewindowiswhentheprogramisrun
0Normal1Minimized2Maximized(best)
namethenameoftheform
eg.changeForm1tofrmTitlescreen
FormBorderStylecontrolstheappearanceoftheform=sborder
alsodetermineswhethertheusercanresizetheform
yousettheBorderStylepropertyatdesigntime
youcannotchangetheBorderStylepropertyatruntime
Sizetosetthesizeofaform
ChangingObjectPropertiesduringRunTime
Whentheuserisrunningtheprogram,thisiscalledruntime.Anypropertyofanyobjectcanbechangedduringruntime.Thegeneralformof
commandstochangeobjectpropertiesis:
objectname.property=value
Examples:
lblQuestion.visible=False(makeslblQuestioninvisible)
lblAnswer.ForeColor=&H000000FF&(changestheforegroundcolorofthelabeltored.&Hhexadecimalnumber(base160123456
789ABCDEF).Tofigurethisnumberout,manuallychangethepropertyandcarefullyrecordthenumber.Thehexadecimalcode
numbersarebuiltbasedonsomuchRedGreenandBlue)
Methods
Methodsareactionsthatanobjectispreprogrammedtoperform,suchasmove,hide,showitself,etc.
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
8/64
11/6/2016
VisualBasicNotes
TheHidemethod,isanexampleofamethodthatdoesnothavearguments.ThefollowingcodemakestheformfrmGamedisappearfrom
view:
e.g.frmGame.Hide
Incontrast,theFindStringmethod,whichfindsastringinaListBoxrequiresthedesiredstringtobefound.Thefollowingcodereturnsthe
locationintheListBoxoftheword'school':
e.g.location=lstBuildings.FindString("school")
Events
Eventsareactionstheusercanperfom,whichobjectscanbeprogrammedtorespondto,suchasclick,doubleclick,keypressetc.Aneventis
anactionrecognizedbyanobject.Clickingamouseorpressingakeyareexamplesofevents.
Someeventsinclude:
ActivateDragOverLoad
ChangeGotFocusLostFocus
ClickKeyDownMouseDown
DblClickKeyPressMouseMove
DragDropKeyUpMouseUp
Eachobjecthasitsownsetofeventsthatitrecognizes.Theeventslisteddonotapplytoallobjects.Forexample,aformcanrecognizeeithera
ClickorDblClickeventwhileabuttononlyrecognizesaClickevent.
AddingCodetoaVBProgram
EveryVBobjectmayhavecode(programs)attachedtoit.Whentheuserclicksontheobject,VBwillexecutethisprogram.Doubleclickonan
objectontheformatdesigntimetobringupitscodewindowwhichlookslike:
PrivateSubobjectname_Click()
EndSub
YourcommandsgoinbetweenPrivateSubandEndSub.Commandsarethelinesofcodeyoutypeinordertogettheprogramtoperformas
youdesire.
NevereraseorchangePrivateSubandEndSub.
Alwaysrenameyourobjectsbeforecodingthemorthecodewillnotbeexecutedforthecorrectobjects
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
9/64
11/6/2016
VisualBasicNotes
Somesamplelinesofcodeinclude:
closeterminatetheexecutionoftheprogram
frmQ2.showshowfrmQ2onthescreen(movetonewquestioninQuizprogram)
txtName.Text="Hello,World!"changethetextitselftoHello,World!
AutoListMembersFeature:
Whenthenameofacontrolorobjectisentered,theAutoListMembersfeaturepresentsadropdownlistofavailablemembers(suchas
propertiesandmethods).
Whenyoutypeinthefirstfewlettersofthepropertyname,thenameisselectedinthelist.PressingtheTABkeyentersthepropertyinthecode
window.Inadditiontoacceleratingyourtyping,thisoptionishelpfulwhenyouaren'tsurewhichpropertiesareavailableforagivencontrol.
TheAutoQuickInfoFeature:
TheAutoQuickInfofeaturedisplaysthesyntaxforstatementsandfunctions.WhenyouenterthenameofavalidVisualBasicstatementor
function,thesyntaxisshownimmediatelybelowthecurrentlinewiththefirstargumentinbold,asshowninthefollowingillustration.Afteryou
enterthefirstargumentvalue,thesecondargumentappearsinbold.
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
10/64
11/6/2016
VisualBasicNotes
Intheexampleabove,noticethe'1of12'toindicatethereare12differentpossiblesetsofparametersthatareacceptable.
OutputtingData
Informationcanbedisplayedtotheuserinatextbox.InyourcodeyouassignyouroutputtotheTEXTpropertyofthetextboxobject.
Ifyoudonotwanttheusertochangethecontentsoftheoutput,thentheReadOnlypropertyofthetextboxcanbesettotrue.
Ifyouyouroutputwillbemorethanonelinelong,thensettheMULTILINEpropertyofthetextboxobjecttotrue.
Ifyouroutputwillbemanylineslongandyourtextboxobjectistooshorttodisplayallthelinesofoutput,youcanaddascrollbartothe
textboxobject,settheSCROLLBARpropertytovertical.
Tojointogethermanystringsintooneoutputline,usethestringconcatenationoperator(&or+).
Toassignnonstringstothetextboxtextproperty,usetheconverttostringbuiltinfunctionToString.
Tostartanewline,usethevbNewLineconstant.(ortheSystem.Environment.NewLineconstant)
Toleftalignastringandallowforpaddingontherightsideofthestring,withanexactnumberofoutputplaces,usethepadRight(n)function
with'n'toindicatetheroomtheoutputshouldtake,suchas"Tigers".padRight(20)
Toformatanumberwithanexactnumberofoutputplacesandalignright,usethepadLeft(n)commandontheconvertedtostringvalue,
suchas50.ToString.padLeft(20)
Examples:
txtOutput.text="hellothere"
txtOutput.text="hello"+"there"
txtOutput.text="hello"+name
txtOutput.text="hello"+name+vbNewLine+"goodbyenow"
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
11/64
11/6/2016
VisualBasicNotes
txtOutput.text="hello"+name+vbNewLine
txtOutput.text=txtOutput.text+"goodbyenow"
txtOutput.text="myageis"+16.ToString
txtOutput.text=name.padRight(15)
InternalDocumentation:
Internaldocumentation,alsocalledcomments,areEnglishstatementsaddedtoyourprogramcodethatexplainsyourprogramtootherpeople,
whichthecomputerdoesnotprocess.Addingcommentstocodemakesiteasierforsomeoneelsetodeterminewhatthecodedoes.Italsohelps
youtounderstandthecodeatsomelaterdate.
InVisualBasictherearetwomethodsforaddingcommentstocode.VisualBasicignoresanythingfollowingasinglequote(')orREM,so
commentscanbeplacedontheirownlineorattheendofalineofcode.
Youmustaddthefollowingcommentstoyourprograminthe'General'section:
1.questionnumber
2.name
3.date
4.purposeoftheproject.
Example:
'assignment:4
'programmer:FrankFurter
'date:Feb.21,2000
'purpose:Aprogramthatcalculatesprofitforacompanybyreadingfromafilethe
'revenueandexpensesofagiven'file.
Atthetopofeachsub/endsub,youmustincludecommentstoexplainthecode.Donotplaceacommentaboveeachlineofcode.
Tocommentasectionofyourprogram,whenyouaretestingaprogramanddon'twantsomeoftheprogramtorun,selectthelinesoftextor
codetobecommentedandclickCommentBlockiconontheTextEdittoolbar.
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
12/64
11/6/2016
VisualBasicNotes
ToaccesstheTextEdittoolbar,clickonView,thenToolbarsandthenTextEdit.
DataTypes
Thecomputerstoresalldata(anumber,aname)asapatternof0'sand1's.Eachsingleletterisadifferentpatternof160'sand1's.Thesame
patternmaymeantheletter'a'orthenumber97.Thecomputerknowshowtointerpretthepatterns,becausetheprogrammergiveseachpattern
adatatype.Adatatypeisaninstructionthattellsthecomputerhowtointerpretapatternof0'sand1's.
VisualBasichasthefollowingdatatypes:
Variabletype
Purpose
AlternateName
Size
Boolean
Byte
Char
Decimal
1character
2bytes
1byte
2bytes
16bytes
Double
numberwithdecimalportion
8bytes
Integer
Long
Short
Single
numberwithoutdecimalportion
numberwithoutdecimalportion
numberwithoutdecimalportion
numberwithdecimalportion
Int32
Int64
Int16
4bytes
8bytes
2bytes
4bytes
String
Dependson
implementingplatform
Valuerange
TrueorFalse.
0through255(unsigned).
0through65535(unsigned).
0through+/79,228,162,514,264,337,593,543,950,335withnodecimal
point
0through+/7.9228162514264337593543950335with28placestothe
rightofthedecimalsmallestnonzeronumberis
+/0.0000000000000000000000000001(+/1E28).
1.79769313486231570E+308through
4.94065645841246544E324fornegativevalues
4.94065645841246544E324through1.79769313486231570E+308for
positivevalues.
2,147,483,648through2,147,483,647.
9,223,372,036,854,775,808through9,223,372,036,854,775,807.
32,768through32,767.
3.4028235E+38through1.401298E45fornegativevalues1.401298E
45through3.4028235E+38forpositivevalues.
0toapproximately2billionUnicodecharacters.
Variables:
Avariableincomputerprogrammingislocationinthecomputer'smemorythatwillstoreasinglevalue,towhichyougiveanameanddatatype.
Youcanthinkofavariableasastorageboxwithanameforholdingcertaintypesofthings:
Thisisthevariablewhosenameisageandthenumbervalue16isstoredinthebox.
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
13/64
11/6/2016
VisualBasicNotes
Whatisstoredinthismemorylocationcanchangeitcanvary.
Youmustnameyourvariablessothatyourprogramcanrememberwhereyoustoredtheinformationandyoumustgiveadatatypesothe
computerknowshowtointerpretwhatisstored.Inamachine'slanguagethesememorylocationsarenumberedwhichcanbeveryconfusingfor
theprogrammer.InahighlevellanguagelikeVisualBasic,goodprogrammersgivemeaningfulnamestotheirvariables,suchas'age'tostorean
age,'name'tostoreaname,'address'tostoreanaddress.Indoingthis,programsbecomeeasiertofollow.Variableslikexandbcanbeused
butitbecomesmoredifficulttoknowwhatisstoredinthemandusingmeaninglessnamesispoorprogrammingstyleandshouldbeavoided
whereverpossible.
NamingConventionsforVariables
VisualBasicinsiststhatthenameofavariablemustbeginwithaletterfollowedbyletters,numbersortheunderscore.Youcannotputany
specialcharacterssuchasspaces,hyphens,periodsetc.inthevariablename.Youmustalsoavoidusingreservedwordsorcommandnames
likeprint,tab,var,etcThesewordsarepartoftheVisualBasiclanguageandusingthemwouldconfusetheprocessor.
DeclaringVariables
Itisgoodprogrammingpracticetodeclareallvariablesbeforetheycanbeusedinaprogram.Wedeclareavariabletoinstructtheprocessorto
setasidealocationinmemoryforouruse,toassignanametothememorylocationandtoinformtheprocessorwhattypeofdatawewishto
storethere.AprogrammerinVBusesthekeyworddimtodeclareavariable.Thereareseveraldifferenttypesofdatainteger,Double,string
andboolean.Stringdataconsistsofanyalphanumericcharacters,suchasnames,addresses,phonenumbers.Numberscanbestoredasstring
dataifyoudonotwishthecarryoutmathematicaloperationsonthem.
Herearesomedeclarationstatementsandwhattheydo:
dimageasinteger
Thisstatementwillsetupamemorylocationcalledagetostoreaninteger(apositiveornegativenumberwithoutdecimals).Inmost
computersanintegeronlyrequires2bytesofmemory.
dimanswerasDouble
Thisstatementwillsetupamemorylocationcalledanswer,tostorerealvalues(positiveornegativenumbersthatcontainadecimal
portion).Thecommonnumberofbytesusedisfour.
dimflagasboolean
Thistypeofvariablecanonlyhavetwovaluestrueorfalse.Abooleanvariablecouldberepresentedbyonebit.
dimnameasstring
Thisstatementwillsetupamemorylocationcalledname,tostorestringdatadataconsistingofalphanumericcharacters.Eachlocation
willhaveenoughspacesetasideforupto256charactersofstring.(eachcharacterisonebyteofinformation)
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
14/64
11/6/2016
VisualBasicNotes
Youcanrequirethatallvariablesbedeclaredbeforetheyareused.YoudothatbyplacingtheOptionExplicitONstatementintheGeneral
Declarationssectionofthemodule.ThisensuresthatmisspelledvariablenamesdonotgetautomaticallydeclaredbyVBwhichcancause
programerrorsthataredifficulttofind.
AssigningValues
Valuescanbeassignedtoavariableusingthe=sign.Thevariablenamealwaysappearsontheleftofthe=sign.Whateverisontherightis
evaluatedandthenstoredinthevariable.Therightsidemaybealiteral(suchas"Devoy"),anumericvalue(suchas18),anobjectproperty
(suchastxtName.text)oranexpression(suchas3+1),oranothervariable.
ArithmeticOperators
Parenthesesshouldbeusedwhennecessarytoclarifythemeaningofanexpression.Whennoparenthesesareused,normalBEDMASrules
apply.VBhasdesignatedcertainsymbolstorepresentcertainmathematicaloperators.Seetablebelowfordetails:
Operator
Addition
Symbol
Code
Output
3+4
Subtraction
74
Multiplication
4*7
28
Division
25/5
IntegerDivision
7\2
3roundstothelowest
integer.
Math.pow(4,2)
(foursquared)16
(80+90+100)/3
90
4E01
0.4
5.6E02
560
Exponent
Math.pow()
Parentheses
()
ScientificNotation
Constants
Aconstantisameaningfulnamethattakestheplaceofanumberorstringthatdoesnotchange.Althoughaconstantsomewhatresemblesa
variable,youcan'tmodifyaconstantorassignanewvaluetoitasyoucantoavariable.VBhasmanypredefinedconstants,theseallstartwith
vb___.UserdefinedconstantsaredeclaredusingtheConststatement,inamannersimilartodeclaringvariables.Forexample:
constPIasDouble=3.141592
constTAX_RATEasDouble=0.08
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
15/64
11/6/2016
VisualBasicNotes
Constantsareusedtomakeyourprogrammorereadable,sinceanamesuchasTAX_RATEprovidesmoremeaningthananumbersuchas
0.08.Theyarealsousedwhenavalueappearsmanytimesthroughoutyourprogramachangetothevalueoftheconstantmustonlybemade
inthedeclare,notthemanyplacesinyourprogramwheretheconstantisuse.
Tomakeothersawarethatanameisaconstant,itisgoodprogrammingpracticetomakethenameallcapitals,withindividualwordsseparated
byanunderscore.
InputtingData
Onaform,inputformtheuserisfrequentlyacceptedinatextboxobject.TheTEXTpropertyofthetextboxobjectcontainstheuserinput.After
theuserhastypedtheirinputintoatextbox,theyoftenarerequiredtousethemousetoclickabutton.Yourcodecanthenassignthecontentsof
thetextboxobjecttoanappropriatevariable.
Examples:
dimnameasstring
name=txtName.text
dimageasinteger
age=Convert.ToInt32(txtAge.text)
dimcostasDouble
cost=Convert.ToDouble(txtCost.text)
IPOChart
Input
listalldatatheuserwillinputtomakethe
programwork
usemeaningfulnames
studentName
studentage
numberofyears
Processing
showhowtheinputdatawillbeconvertedintotheoutputdata
usetheexactsamenamesyouhaveintheinputandoutputcolumns
statetheconversionsasequations,asyouwouldinMathclass,withtheoutputontheleftsideofthe
equalsign
futureage=studentage+numberofyears
Output
listalldatatheprogramwilloutput
usemeaningfulnames
futureage
Selection
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
16/64
11/6/2016
VisualBasicNotes
Inyourcomputerprogram,youcaninstructthecomputertomakeadecisionandthenbasedonthedecision,selecttorunapartofyourprogram
ornotrunapartofyourprogram.TheVisualBasiccommandformakingthisselectionisthe'if'command.
Generalformatis:
if<condition>then
codetorunonlywhentheconditionisTRUE
endif
Or:
if<condition>then
codetorunonlywhentheconditionisTRUE
else
codetorunonlywhentheconditionisFALSE
endif
Youreplacethe<condition>withsometestthatcanbetrueorfalse,suchasgrade=11
Note:the'elseclause'isnotrequiredwhennoactionistobeperformedwhentheconditionisfalse.
3wayorMoreDecisions
if<condition1>then
codetorunonlywhencondition1isTRUE
elseif<condition2>then
codetorunonlywhencondition1isFALSEandcondition2isTRUE
elseif<condition3>then
codetorunonlywhencondition1isFALSEandcondition2isFALSEandcondition3isTRUE
else
codetorunonlywhenallconditionsareFALSE
endif
RelationalOperators
=equalto
<lessthan
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
17/64
11/6/2016
VisualBasicNotes
>greaterthan
<=lessthanorequalto
>=greaterthanorequalto
<>notequalto
Note:twostringsmaybecompared,orastringmaybecomparedtoaliteral.Inthiscase,thevaluesarecomparedletterbyletter,asyouwould
listwordsinadictionary.However,capitalletterscomebeforelowercaseletters(eg."A"islessthan"a").Tocomparestringswithouttheconcern
forupperandlowercase,youmaywanttoconvertthestringstoallcapitalsorlowerletterspriortodoingthecompare(seeUCaseandLCase
below).
Examples:
ifuserschoice=6then
(somecodegoeshere)
endif
ifage>13then
(somecodegoeshere)
(anotherlineofcodegoeshere)
endif
ifage>=13then
(somecodegoeshere)
else
(someothercodegoeshere)
endif
iftown="Winchester"then
(somecodegoeshere)
elseiftown="Cambridge"
(someothercodegoeshere)
elseiftown="Kitchener"
(someothercodegoeshere)
else
(someothercodegoeshere)
endif
Notethattheelseclausemaybeomitted,whennotneeded.
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
18/64
11/6/2016
VisualBasicNotes
CodingConventions
Thecodewithineachsubsectionoftheselection(IF)structueisindentedoneTAB,forclarity.Remembertoalwaysindentyourprogramsfor
easierreadibility.
CompoundSelectionStatements
Attimeswehaveamorecomplexconditionthanjustonesimpletesttodeterminewhetheraportionoftheprogramshouldbeexecutedornot.In
thiscasewemustconnecttogethermultipletestsusingtheBooleanoperators.
Logical(Boolean)Operators
ABooleanexpressioncanbeformedusingthelogicaloperatorsAND,ORandNOT.Alogicalexpressionjoinstwoexpressionsandcreatesan
expressionthatevaluatestoeithertrueorfalse.WhenANDisusedbothexpressionsmustevaluatetotruefortheentireconditiontobeconsider
true.IfORisused,eitheroneoftheexpressionsorbothexpressionsmustevaluatetotruefortheentireconditiontobeconsideredtrue.
Ifcondition1ANDcondition2Then
Statements
Endif
Ifcondition1ORcondition2Then
Statements
Endif
IfNOTcondition1Then
Statements
Endif
OperatorHierarchy
Theuseofparentheseswithlogicaloperatorsimprovesreadability:however,theycanbeomittedsometimes.
VisualBasichasaoperatorhierarchyfordecidinghowtoevaluateexpressionswithoutparentheseswhichis:
1.allarithmeticoperationsarecarriedout
2.thenallexpressionsinvolving>,<and=areevaluatedtotrueorfalse
3.thenlogicaloperatorsarenextapplied,intheorder:
1.BRACKETS
2.NOT
3.AND
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
19/64
11/6/2016
VisualBasicNotes
4.OR
Examples:
ifage<18ORgrade=12ANDweight>100+10then
(somecodegoeshere)
endif
if(heightA<heightB10ORweight<110)ANDgrade>9then
(somecodegoeshere)
endif
IPOChartsSelection
WhencreatingIPOchartsthatmakeuseofselection,clearlyshowthedecisionthecomputerwillmake.Indentanyinstructionsthatwillbe
executedbasedonthedecision.Itisnotnecessarytowritethe'endif'command.
Input
Processing
Output
age
grade
weight
ifage<18orgrade=12andweight>100+10then
sportsteameligible
sportteameligible=true
else
sportsteameligible=false
ForNextLoops:
Aloopisusedtorepeatasequenceofstatementsanumberoftimes.Whenweknowhowmanytimesaloopshouldbeexecuted,aspecialtype
ofloop,calledaForNextloopcanbeused.TheForNextloopdesignatesanumericvalue,calledthecontrolvariable,thtisinitializedand
thenautomaticallychangesaftereachexecutionoftheloop.
TheFor..Nextlooptakesonthefollowingform:
ForI=mton
Statement(s)
NextI
I=controlvariable
M=initialvalue
N=terminatingvalue
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
20/64
11/6/2016
VisualBasicNotes
Example1:AProgramthatdisplaysthefirstfivenumbersandtheirsquares.
DimxAsInteger
Forx=1To5
txtOutput.text=x.ToString+Math.pow(x,2).ToString.padLeft(8)
Nextx
Intheaboveexample,thecontrolvariablewasincreasedby1aftereachpassthroughtheloop.AvariationoftheForstatementallowsany
numbertobeusedastheincrement.Thestatement
For1=mtonstepx
Instructsthenextstatementtoadd'x'tothecontrolvariableinsteadof1.Thenumberxiscalledthestepvalueoftheloop.
Example2:aprogramthatthatuses0asanintialnumberandrequestsanendingnumberandastepvalueasinputfromtheuserandthen
displaysthenumberswithinthatrange.
dimxAsInteger
dimendsAsInteger
dimincrementsAsInteger
ends=Convert.ToInt32(txtEnds.Text)
increments=Convert.ToInt32(txtSteps.Text)
Forx=0ToendsStepincrements
txtOutput.text=txtOutput.text+x.ToString+vbNewLine
Nextx
NestedLoops
ThestatementsinsideaForNextlooporaDoLoopcanconsistofanotherForNextloop.Suchaconfigurationisknownasanestedloopand
isusefulinrepeatingasingledataprocessingroutineseveraltimes.
Example3:Aprogramthatprintsamultiplicationgrid3X3
dimjAsInteger
dimkAsInteger
txtOutput.text=""
Forj=1To3
Fork=1To3
txtOutput.text=txtOutput.text+j.ToString+"X"+k.ToString+"="+(j*k).ToString+Space(8)
Nextk
txtOutput.text=txtOutput.text+vbNewLine
Nextj
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
21/64
11/6/2016
VisualBasicNotes
IPOChartsForLoops
WhencreatingIPOchartsthatmakeuseofa'for'loop,clearlyshowhowmanytimestheloopwillrepeat.Indentanyinstructionsthatwillbe
repeated.Itisnotnecessarytowritethe'next'command.
Input
Processing
Output
amountdeposited
interestrate
numberofyears
finalamount=amountdeposited
forthenumberofyears
finalamount=finalamount+finalamount*interestrate
finalamount
DoLoops
ADOLOOPrepeatsasequenceofstatementseitherWhileorUntilacertainconditionistrue.ADOstatementprecedesthesequenceof
statementsandaLoopstatementfollowsthesequenceofstatements.Thecondition,alongwitheitherthewordWhileorUntil,followstheword
Do.
TheformatfortheDOLOOPisasfollows:
DoWhilecondition
Statements
Loop
Example4:Writeaprogramthatdisplaysthenumbers1to10usingaDoWhile
DimnumAsInteger
num=1
txtOutput.text=""
DoWhilenum<=10
txtOutput.text=txtOutput.text+num.ToString+vbNewLine
num=num+1
Loop
Example5:Writeaprogramthatdisplaysthenumbersto10usingaDoUntil
DimnumAsInteger
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
22/64
11/6/2016
VisualBasicNotes
num=1
txtOutput.text=""
DoUntilnum>10
txtOutput.text=txtOutput.text+num.ToString+vbNewLine
num=num+1
Loop
Example6:Writeaprogramthatprintsamessageoncethecorrectpasswordisentered.
DimpasswordAsString
txtOutput.text=""
DoWhilepassword<>"HOOAH"
password=InputBox("Pleaseenteryourpassword")
password=UCase(password)
Loop
txtOutput.text="Congratulations,you'veenteredmyserverspace."
FileInputandOutput
Todate,ourdatahasbeenputintomemoryusingassignmentstatementscreatedbytheprogrammer
(e.g.name="FrankFurter",num=5)
orwehaveassignedthecontentsofanobjecttoavariable
(e.g.name=txtName.text,num=Convert.toInt32(txtNumber))
Thesemethodsaresufficientforsmallscaleapplicationsbutwithlargevolumesofdataandmostrealworldapplicationsweneedabetter,more
versatileandaccessiblewayofstoringdata.Theharddiskorfloppydiskoffersthesolution.Datafilesstoredondiskcanbeaccessedbyseveral
programsfordifferentpurposes.
Whyuseadisk?
Nonprogrammerscanuseaprogramandmodifythedataondiskwithoutknowinghowtoprogram,suchasastudenttypinganessayinMS
Word.Dataonadiskmaybeaccessedandmodifiedmanytimes,suchaschangestoanessay.Dataonadiskmaybeusedbymanydifferent
programs,suchasanessaycreatedinMSWordusedforinputtoaMSPublisherdocument.
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
23/64
11/6/2016
VisualBasicNotes
TypesofDiskFileAccess
Yourprogramscanaccessfilesin2ways
1.sequentially
2.randomly
Asequentialfileaccessesinformationonerecordatatime,inthesameordertherecordswerewritten,thisislikeacassettetape,whereyou
mustpassbythefirst3songstogetthethefourthsong.
Arandomaccessfilecanbeaccessedinanyorderyouwant.ThisislikesongsonaCDwhereyoucanjumptoanysongyouwant,inanyorder.
ProcessingaDataFile
Thefollowing3tasksmustbecarriedoutwhenaccessingadatafile:
1)Openthedatafile
2)Processtherecords,asrequiredbytheprogram(eitherreadorwrite)
3)Closethefile
Example#1:Writeaprogramthatusesafileforinputanddisplayswhatisread.Theformshouldconsistofacommandbuttonandatextbox.Use
Windows'Notepadtocreatethefiledata.txtcontainingthefollowingline.
Data.txt
4,HighStreet
Example:Programmerassignsvalues
PrivateSubcmdDisplay_Click()
dimschoolNumberasinteger
dimstreetasstring
txtOutput.text=""
schoolNumber=4
street="HighStreet"
txtOutput.text="Mr.Devoy'shouseislocatedon"+schoolnumber.ToString+street
EndSub
Example:Userstoresvaluesonhard/floppydiskanddataisreadfromthefile
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
24/64
11/6/2016
VisualBasicNotes
PrivateSubcmdDisplay_Click()
dimschoolNumberasinteger
dimStreetasstring
txtOutput.text=""
FileOpen(1,"data.txt",OpenMode.Input)
input(1,schoolNumber)
input(1,Street)
txtOutput.text="Mr.Devoy'shouseislocatedon"+schoolnumber.ToString+street
FileClose(1)
EndSub
FileOpenNotes:
TheopenstatementtakestheformFileOpen(filenumber,"Filename",mode)
ThefilenameisthenameoffileyoucreatedinNotepad.
Yourfilemustbestoredinthesamefolderasyourexecutableprogramfile(thatisthe'bin'folder)
ThemodeiseitherOpenMode.Input,OpenMode.OutputorOpenMode.Append.
Themodehasthefollowingaffect:
inputlooksforanexistingfileandplacesyouatthebeginningofthefileforreading
outputcreatesanemptyfileifitdoesn'talreadyexist,oreraseseverythinginanexistingfileandplacesyouatthebeginningready
towritedata
appendlooksforanexistingfileandplacesyouattheend,readytowritedata.
Thefilenumberisanintegerthatlinksthefiletoanumberfrom1to255usedthroughouttheprogram,andisanynumberyouchoose.
FileInputNotes
TheinputstatementtakestheformINPUT(filenumber,variablename)
VBusesthekeyword'input'toreaddatafromafile
thefilenumbermustbethesameasusedontheopencommand
thevariablenamemustbeavariablepreviouslydeclaredandthedatainthefilewillbeplacedintothisvariable
Eachinputcommandmovesfurtherthroughthefile.
FileOutputNotes
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
25/64
11/6/2016
VisualBasicNotes
TheoutputstatementtakestheformWriteLine(filenumber,variablename,variablename,...)
VBusesthekeyword'WriteLine'tooutputdatatoafile
thefilenumbermustbethesameasusedontheopencommand
thevariablenamemustbeavariablepreviouslydeclaredandthedatainthevariablewillbeplacedintothefile
morethanonevariablemaybeononeWriteLinestatement
EachWriteLinecommandmovesfurtherthroughthefile.
MakingDataFiles
WhencreatingadatafileusingNotepad,theformatisimportantifthedataistobereadinproperly:
Insertcommasbetweeneachdataentry
Nocommaisrequiredafterthelastdataentryonaline.Thiscommaisenteredautomatically.
Encloseastringwithquotationmarksifitcontainscommasorspacesaspartofthestring.
Sinceweareworkingwithsequentialfiles,thefilemustbereadthesamewayinwhichitwascreated.Forexample,ifthefilecontainsfour
variables...astring,anintegerandthentwomorestrings.Toloadthedatabackin,wemustprovidefourvariablesofthesamedatatypein
thesameorder.
Saveyourfileinthe'bin'folderofyourVBassignment,sotheFileOpencommandcanfindit(otherwise,fullqualifythepathtothefile)
Oneofthemainapplicationsofprogrammingistheprocessingoflistsofdata.ADoloopisusedtodisplayallorselecteditemsfromlists,search
listsforspecificitems,andperformcalculationsonthenumericalentriesofalist.
Example:Userstoresvaluesonhard/floppydiskandalldataisreadfromthefileanddisplayed.
Createafilenameddata.txtwith5namesoffriend(remembertoencloseeachnameinquotes)
PrivateSubcmdDisplay_Click()
dimcountasinteger
dimnameasstring
txtOutput.text=""
FileOpen(1,"data.txt",OpenMode.Input)
forcount=1to5
input(1,name)
txtOutput.text=txtOutput.text+name+vbNewLine
nextcount
FileClose(1)
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
26/64
11/6/2016
VisualBasicNotes
EndSub
EOFFunction
Oftentheamountofdatainafilemayvary,unliketheexampleabovethathad5names.Insteadofacountedloop(for)thedatainafiletobe
processedareoftenretrievedbyaDoloop.VisualBasichasausefulfunctioncalled,EOF,thattellsusifwehavereachedtheendofthefilefrom
whichwearereading.Ifafilehasareferencenumber"1"thenthefunctiontakesonthefollowingform:
EOF(1)
Example7:Aprogramthatdisplaysthecontentsofatelephonedirectory.Thenamesandphonenumbersarecontainedinafile.Theloopwill
repeataslongastheendoffileisnotreached.
dimnamesAsString
dimphoneAsString
FileOpen(1,"ex4.txt",OpenMode.Input)
DoWhileNotEOF(1)
Input(1,names)
Input(1,phone)
txtOutput.text=txtOutput.text+names+Space(5)+phone+vbNewLine
Loop
FileClose(1)
Example8:Aprogramthatwillsearchthetelephonedirectoryinthepreviousquestionforanamespecifiedbytheuser.Ifthenamedoesnot
appearinthedirectory,amessageofnotificationwillappear.
dimnamesAsString
dimphoneAsString
names=""
FileOpen(1,"ex4.txt",OpenMode.Input)
DoUntilEOF(1)Ornames=txtName.Text
Input(1,names)
Input(1,phone)
Loop
Ifnames=txtName.TextThen
txtOutput.text=names+Space(5)+phone
Else
txtOutput.text="Namenotfound"
EndIf
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
27/64
11/6/2016
VisualBasicNotes
FileClose(1)
CountersandAccumulators
Acounterisavariablethatisusedtocalculatethenumberofelementsinlists.
Anaccumulatorisavariablethatisusedtosumnumericalvaluesinlists.
Example9:Aprogramthatcountsandfindsthevalueofcoinslistedinafile.
dimnumCoinsAsInteger
dimsumAsDouble
dimvalueAsDouble
sum=0
numCoins=0
FileOpen(1,"ex6.txt",OpenMode.Input)
DoWhileNotEOF(1)
Input(1,value)
numCoins=numCoins+1
sum=sum+value
Loop
txtOutput.text="Thevalueofthe"+numCoins.ToString+"coinsis"+sum.ToString
Inthisexample,numCoinsisthecounterbecausewitheachiterationoftheloop,weaddonetoitsvalue,thusintheend,wehave
countedhowmanycoinstherewereinthefile.
Inthisexample,sumistheaccumulatorbecausewitheachiterationoftheloop,weaddthevalueofthecoin,thusintheend,wehave
addeduphowmuchallthecoinsareworth.
Notethepatternofthecountandaccumulationstatements:thecountandaccumulatorvariableappearsonboththerightandleftside
oftheequalssign!
Also,itisimportanttostartthecountandaccumulatorvariablesoutatsomevaluebeforewestarttheloop(inthiscase0),thisis
calledinitializingthevariables.
TerminatingaForm
Toterminateaformwhichexitstheprogramwhenthereisonlyoneformusethecommand:
me.close()
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
28/64
11/6/2016
VisualBasicNotes
'me'referstotheformitselfandcloseisamethodoftheformthatwillasktheformtoterminate.
Debugging
ComputerProgrammingErrors
Preparingacomputerprogramtosolveaproblemrequiresyoutobesystematicandprecise.Whatismore,aprogramthatislessthancorrectis
nouseatall.Youmustredefineituntilitisperfect.Whenyoufirstprepareaprogramitmightproducecrazyanswers.Youmustcorrectthe
programerrorsorbugsuntilitgivescorrectresultsonthetestdatathatyoufeedit.Youmustgiveitawideenoughrangeoftestdatatoensureit
alwaysgivescorrectresults.
Therearethreetypesoferrors:
1.syntaxerrors
2.runtimeerrors
3.logicerrors
Asyntaxerrorisonethatviolatesthegrammaticalrulesorsyntaxrulesoftheprogramminglanguage.Asyntaxerrorwillresultinanerror
messageyouaretypingyourprogram,andsoiseasytofindandfix.
Aruntimeerrorisanerrorthatoccurswhentheprogrammingisrunningandsomeinstructionisimpossibleforthecomputertoperform,suchas
divisionbyzero.TheprogramisstoppedandyouaregivenamessageboxthatasksifyouwanttoENDorDEBUG.IfyouselectDEBUG,then
VBhighlightsthelineofcodewiththeerror.
Ontheotherhand,withalogicerrortheprogramcorrectlyrunsbutperformsthewrongtask.Theseerrorscanonlybefoundbyexaminingthe
resultsandrunningtheprogramwithavarietyoftestdata.Thecorrectingofprogramerrorsiscalleddebugging.
Settingabreakpoint
Settingabreakpointallowsyoutostoptheprogramsexecutionatthelineofcodewherethebreakpointisadded.Tosetabreakpoint,clickthe
MarginIndicatorbarnexttothelineofcode.Wheninbreakmode,youcanmovethemouseoveranyvariablenameandtheToolTipboxwill
appeargivingthevalueofthevariable.Onceinbreakmode,youcanclickonthestepinto,stepoutorstepoverbuttonsonthedebugtoolbarto
executetheprogram.Tostepintoaproceduremeanstorunitonelineattime.Tostepoveraproceduremeanstorunitasaunit.Tostepoutofa
proceduremeanstorununtilitcompletesthecurrentprocedureandreturnstothecallingprocedure.Therearefunctionkeyequivalentstothe
'stepinto''stepover'andstepoutof'buttons.
Addingthedebugtoolbar
Rightclickanywhereonthecodeandclickondebug.AsecondmethodistoclickonView,ToolbarsandDebug.
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
29/64
11/6/2016
VisualBasicNotes
ImmediateWindow(wheninBreakmode)
Wheneveryouareinbreakmode,youcanprintthevalueofanyvariableintheimmediatewindow.SimplytypeprintvariableNameandpress
enterintheimmediatewindow.Iftheimmediatewindowisnotvisible,simplyclickViewandImmediateWindow.Forexample,toprintthevalueof
thevariableintLoanPaymentsimplytypeprintintLoanPaymentor?intLoanPayment.Whenyoupressenter,thevalueofthevariablewillbe
displayed.Theprogrammustberunningandinbreakmodefortheimmediatewindowtofunction.
FormatFunctions
Inthefollowingtablenrepresentsanumberornumericvariable.dateStringrepresentsadateinaformsuchasmonth/day/year.
Function
Purpose
Format(n,"Standard")
convertsnumberstostringrepresentationshavingtwodecimalplacesand
commaseverythreedigitstotheleftofthedecimalpoint
Format(n,"Currency")
convertsnumberstostringrepresentationswithaleadingdollarsign,two
decimalplaces,commaseverythreedigitstotheleftofthedecimalpoint,
andenclosesnegativenumbersinparentheses
Format(n,"#,0")
Examples
Format(1/6,"Standard")
OutputValue
0.17
Format(12345,"Standard")
12,345.00
Format(2000,"Currency")
$2000.00
Format(0.2,"Currency")
($0.20)
convertsnumberstostringrepresentationsandroundsnumberstowhole
numbersandplacescommaseverythreedigitstotheleftofthedecimal
point
Format(10002.8,"#,0")
10,003
Format(n,"###,###,##0.00)
convertsnumberstostringrepresentationsandroundsnumberstotwo
decimalplacesandplacescommaseverythreedigitstotheleftofthe
decimalpoint,takingaminimumspaceof14places(#willbeblankifno
digit,0showsadigitalways)
Format(32.7,"###,##0.00)
Format(n,"Percent")
convertsnumberstostringrepresentationsofthenumbersinpercentwith
twodecimalplacesandatrailingpercentsign
Format(0.281,"Percent")
Format(n,"Scientific")
convertsnumberstostringrepresentationsofnumbersinscientificnotation Format(0.018,"Scientific")
withdecimalplaces
Format(1018,"Scientific")
Format(dateString,
"LongDate")
returnsaformattedversionofthedate
32.70(where
representblanks)
28.10%
1.80E02
"1.02E+03"
Format("3/17/00","LongDate")
"Friday,March17,
2000"
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
30/64
11/6/2016
VisualBasicNotes
MathFunctions
Function
Purpose
Sqrt(n)
calculatesthesquarerootofthenumbern
pow(x,y)
calculatesxraisedtothepowerofy
Int(n)
returnsthenumber,withthefractionalportiontruncated
nModm
returnsthewholenumberremainderwhennisdividedbym
Round(n,d)
returnsnroundedtoddecimalplaces
Examples
Output
Value
Math.Sqrt(16)
Math.Sqtr(2)
1.414214
Math.pow(2,3)
Int(16.01)
16
Int(16.967)
16
Int(16.11)
16
15Mod4
8Mod3
Math.Round(7.666,
1)
7.7
RandomNumbers
PseudorandomnumberscanbegeneratedbythecomputerwiththeuseoftheRandomclass.Todeclarearandomnumbergenerator:
dimrandgenasRandom
Tocreateanobjectoftherandomgenerator:
randgen=NewRandom
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
31/64
11/6/2016
VisualBasicNotes
Togeneratearandomintegerbetween1and6(including1butexcluding6)
dimnumberasInteger
number=randgen.Next(1,6)
Togeneratearandomdecimalvaluebetween0.0and1.0(including0.0butexcluding1.0)
dimnumberasdouble
number=randgen.NextDouble()
StringFunctions
Inthefollowingtablenandmrepresentnumbersornumericvariables,strrepresentsastringorstringvariable.
Function
Purpose
Examples
dimfirstasstring
simlastasstring
dimfullNameasstring
String.concat(str1,str2)
concatentationjoinstogethertwostrings
first="sam"
last="jones"
fullName=String.concat(first,last)
dimfirstasstring
simlastasstring
dimfullNameasstring
+(or&)
concatentationgluetogether2stringstocreatealongerstring
str.substring(m,n)
returnsastringconsistingofncharactersofstrstartingwiththem'th
character
Iftheparameternisomitted,str.substring(m)isallthecharactersfromthe
m'thcharacteron.
Note:thefirstcharacterisinposition0
str.Remove(m,n)
removesncharacters,startingatpositionm
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
OutputValue
samjones
samjones
first="sam"
last="jones"
fullName=first+last
dimnameasstring
dimanswerasstring
name="Mr.Devoy"
answer=name.substring(2,5)
".Dev"
"voy"
answer=name.substring(6)
dimnameasstring
dimanswerasstring
name="Mr.Devoy"
answer=name.remove(0,5)
evoy
32/64
11/6/2016
str.Insert(n,str2)
VisualBasicNotes
insertsstr2inthemiddleofstr,startingatpositionn
dimnameasstring
dimanswerasstring
Mr.MikeDevoy
name="Mr.Devoy"
answer=name.insert(3,"Mike")
dimnameasstring
dimanswerasstring
str.ToUpper()
changesalllowercaseletterstouppercase
name="Mr.Devoy"
"MR.DEVOY"
answer=name.ToUpper()
dimnameasstring
dimanswerasstring
str.ToLower()
changesalluppercaseletterstolowercase
name="Mr.Devoy"
"mr.devoy"
answer=name.ToLower()
dimnameasstring
dimanswerasstring
str.Trim()
removesallthespacesfromthebeginningandendofstr
name="Mr.Devoy"
"Mr.Devoy"
answer=name.Trim()
dimnumasinteger
dimanswerasstring
num.ToString()
convertsnumberstostrings
num=8
"8"
answer=num.ToString()
dimnameasstring
dimanswerasstring
str.Replace(find,replace)
returnsanewstringwithalloccurencesoffindchangedtoreplace
name="Mr.Devoy"
"Mr.Divoy"
answer=name.replace("e","i")
str.equals(str2)
returnstrueifstr2containsthesamecharactersasstr,falseotherwise
dimnameasstring
name="Doyle"
true
ifname.equals("Doyle")
dimname1asstring
dimename2asstring
String.compare(str1,str2)
returns0ifthecharactersinthetwostringsarethesame,anegativevalue
ifthecharactersinstr1arealphabeticallybeforestr2,otherwiseapostive
number
name1="Doyle"
name2="Mustang"
wouldbetruesinceDoyleis
alphabeticallybefore
Mustang
ifString.compare(name1,name2)<0
String.compare(str1,str2,case
insensitive)
ifcaseinsensitiveistrue,thencomparesasabovebutignoresupperand
lowercasedifferences.
ifcaseinsensitiveisfalse,comparesasabove
dimname1asstring
dimename2asstring
name1="Doyle"
name2="doyle"
wouldbefalse,thecompare
returnsa0sincebothstrings
arethesamewithcase
ignored
ifString.compare(name1,name2,true)<0
dimnameasstring
str.padLeft(n)
addsspacestotheleftofthestringstrtocreateatotalwidthofncharacters
name="Mike"
usedforrightaligning
"Mike"(whererepresent
ablank)
name.padLeft(10)
dimnameasstring
addsspacestotherightofthestringstrtocreateatotalwidthofn
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
"Mike"(where
33/64
11/6/2016
VisualBasicNotes
str.padRight(n)
charactersusedforleftaligning
representsablank)
name="Mike"
name.padRight(10)
StringRelatedNumericFunctions
Inthefollowingtablenrepresentsanumberornumericvariable,str,str1,str2representstringsorstringvariables.
Function
Purpose
Examples
OutputValue
dimnameasstring
dimanswerasinteger
str.Length()
thenumberofcharactersinthestringstr
name="Mr.Devoy"
answer=name.Length()
Thevalueofthefunctionisthepositionofstr2instr.
str.index(str2)
Note:thefirstletterispostion0
dimwordasstring
dimanswerasinteger
word="function"
answer=word.index("o")
returnstheANSInumbercorrespondingtothefirstcharacterofstr
Asc("a")
97
returnsthesinglecharactercorrespondingtotheANSIvalueofint
(reverseofAsc)
Chr(97)
convertsavalueinastringvariabletoanIntegervariabletype
Convert.ToInt32("97")
97
convertsavalueinastringvariabletoasinglevariabletype
Convert.ToSingle("97.5")
97.5
convertsavalueinastringvariabletoadoublevariabletype
Convert.ToDouble("197.5")
197.5
astringconsistingofnspaces
"Go"&Space(3)&"Now"
"GoNow"
Asc(str)
Chr(int)
Convert.ToInt32(str)
Convert.ToSingle(str)
Convert.ToDouble(str)
Space(n)
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
34/64
11/6/2016
VisualBasicNotes
FormLoad
Ifyouhavecodethatyouwantexecutedautomaticallywhenaformcomesup,putthecommandsin:
FormLoadonlyexecuteswhentheformisfirstloaded.
Warning:mostoftenyoushouldplaceyourcodeinsidethebuttonclickcommand,youshouldnotnormallyneedtousetheseevents.
MessageBoxes
PopupmessageboxesarecreatedbytheMessageBox.showcommandinyourprogramming.
Examplesofmessageboxes:
Messagebox.show("Thepostalcodeisnotenteredcorrectly.")
MessageBox.Show("Youmustenteraname.","NameEntryError",buttonsConstant,iconConstant)
wherebuttonsConstantcanbeoneofmanychoicessuchas
MessageBoxButtons.OK
MessageBoxButtons.YesNoCancel
MessageBoxButtons.YesNo
MessageBoxButtons.OKCancel
MessageBoxButtons.RetryCancel
MessageBoxButtons.AbortRetryIgnore
whereiconsConstantcanbeoneofmanychoicessuchas
MessageBoxIcon.Exclamation
MessageBoxIcon.Asterisk
MessageBoxIcon.Error
MessageBoxIcon.Hand
MessageBoxIcon.Information
MessageBoxIcon.None
MessageBoxIcon.Question
MessageBoxIcon.Stop
MessageBoxIcon.Warning
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
35/64
11/6/2016
VisualBasicNotes
UsingtheReturnedValueofmessageboxes
userschoice=MessageBox.show("Areyousureyouwanttoquit?","Quit",MessageBoxButtons.YesNo)
Ifuserschoice=DialogResult.YesThen
me.close()
EndIf
TheMsgBoxreturnsanumericvaluedependingonwhattheuserdoesandthisnumberisstoredinthevariableuserschoice.Again,thenumeric
valueexistsinbuiltinconstants.
constant
User'sAction
DialogResult.OK
OkButton
DialogResult.Cancel
CancelButton
DialogResult.Abort
AbortButton
DialogResult.Retry
RetryButton
DialogResult.Ignore
IgnoreButton
DialogResult.Yes
YesButton
DialogResult.No
NoButton
InputBox
Usually,atextboxisusedtoobtaininputdescribedbyalabel.Sometimeswewantjustonepieceofinputandwouldrathernothaveatextbox
andlabelstayonthescreenforever.Theproblemcanbesolvedwithaninputbox,whichisaninputformautomaticallycreatedbyVBforyou.To
displayaninputBoxusethefollowingstatement.
dimresponseasstring
response=InputBox(prompt,title)
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
36/64
11/6/2016
VisualBasicNotes
Example:
dimlastnameAsString
lastname=InputBox("Pleaseenteryourlastname","RegistrationEntry")
iflastname=Nothingthen
MessageBox.Show("Youpressedthecancelbuttonordidn'tenteranything.")
else
MessageBox.Show("Soyou'retheonethatmadethismess!")
endif
Iftheuserpressesthecancelbutton,thenthevaluereturnedbytheInputBoxistheVBconstantNothing.
ModularCodeSubprograms
Largestructuresarebuiltfromsmallermodules(e.g.Ikeafurniture,Stereo,andcomputersystems)Allthesearemodularbecauseyoubuilda
completesystemfromasetofindividuallypurchasedcomponents.Wecanbuildcompletecomputerprogramsfrommodules.VBhastwotypes
ofmoduleswecanusetobuilduplargerprograms,theyarecalled
1.subprograms(sometimescalledprocedures)
2.functions
WhyuseModularCodewithinourprograms?
Codebecomesmoreorganizedandreadable
Codewillbecomesmaller,faster,andmoreefficientusinglesscodetodothesamething.
Allowsteamsofprogrammerstoseparateaprojectintosmaller,independentpartsthatindividualscanworkon.
Subprograms/procedures
Callstatements:
Asubprogram,asthenamesuggests,isaprogramwrittenseparatelyfromthemainprogram.Itislikeaminiprogram.Eachsubprogramshould
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
37/64
11/6/2016
VisualBasicNotes
doone,welldefinedjob.Toperformitsjob,asubprogrammayhavetobesentinsomedata,thesearecalledarguments.
RunningaSubprogram
Subprogramsarerun(executed)withtheVBCALLstatement.
CallAddNumber(num1,num2)
Noticethatthefirstletterofthesubprogramname,'AddNumber'isuppercasetodistinguishitfromavariable.
Arguments:
InsidetheparenthesesofaCallStatementareargumentswhichinthiscasearevariables.(num1,num2).Theycouldalsobeconstants
AddNumber(2,3,)orexpressionsAddNumber(num1+2,num2+3).
DefiningaSubprogram
Theblockofcodethatistobethesubprogrammuststartwiththesubprogramheaderandendwithan'EndSub'statement.
Thesubprogramheaderhastheform:
PrivateSub<subprogramname>(<parameterdeclares>)
SubprogramName
Thesubprogramnamecanbeanynameyouchoose.Itmuststartwithaletterandcontainonlyletters,digitsand_(noblanksareallowed).In
ourclass,thenameshouldtaketheformofatleasttwowordsthatdescribewhatthesubprogramdoes,thefirstwordshouldbeaverbandthe
secondshouldbeanoun.
ParameterDeclares
Parametersarevariablesthataredatathatwillbereceivedbythesubprogramfromthemainprogram,soitcandoitsjob.Theyappearinthe
headingofasubprogram,suchas:
PrivatesubAddNumber(byValnum1asDouble,byValnum2asDouble)
theVBkeywordbyValindicatesthatanychangesbythesubprogramtothevalueofaparameter,willnotbesentbacktothecalling
programyoushouldalwaysuseByValunlessyouhaveagoodreasonnotto!
theVBkeywordByRefindicatesthatanychangesbythesubprogramtothevalueofaparameter,AREsentbacktothecalling
programByRefwillnormallyonlybeusedbysubprogramsthatgatherinputfromthetextboxesonaform
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
38/64
11/6/2016
VisualBasicNotes
theparametertypemustbeincluded(e.g.Double,string,integer)
thenamesoftheargumentsandparameterscanbethesameordifferent.Whatmattersisthattheorder,numberandtypesof
argumentsandparametersmatch.
CreatingaSubprogram
1.Moveyourcursortheendofyourcode,justbeforethe'EndClass'statement
2.Typeintheheaderofthesubprogramwhichhasthefollowingformat:
PrivateSub<subprogramname>(<parameterdeclares>)
3.Aseparatorlineandtwolinesofcodehavebeenaddedatthebottomofthecodewindow,alongwithan'EndSub'statement.
4.TypethestatementsofthesubprogrambetweenthePrivateSubandEndSubstatements.
PropertiesofProcedures:
theyareseparatefromthemainprogram
theycanuselocalvariables
theycanobtainparametersfrom,andreturnthemto,themainprogram
VariableScope:
LocalVariables
Themainprogramandeachsubprogramhasitsownsetofvariablesevenifthevariableshavethesamenames!Thismeansthatavariable
usedinthemainprogramcannotbeaccessedbyanyoftheSubs,andthatvariablesusedintheSubscannotbeaccessedbythemainprogram
oranyotherSubs.ThesevariablesaresaidtobeLocal.Thismakessensewhenyouconsiderthatmuchofprogrammingtodayusestheteam
approach.Therewouldbechaosifthevariablesinonesubcouldaffectthevaluesofvariablesinanothersub.
FormLevelVariables:
VisualBasicprovidesawaytomakeavariablevisibletoeveryprocedureinaform'scodewithoutbeingpassedasaparameter.Suchavariable
iscalledaformlevelvariableorglobalvariable.Formlevelvariablesappearatthetopofthecodewindowandareseparatedfromtherestofthe
codebyahorizontalseparatorline.
SubProgramExamples
'Example1:
'Aprogramthataddstwonumberswithouttheuseofsubprograms.
OptionExpliciton
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
39/64
11/6/2016
VisualBasicNotes
PrivateSubcmdAdd_Click()
dimnum1AsDouble
dimnum2AsDouble
dimanswerAsDouble
num1=2
num2=3
answer=num1+num2
'Displaythesumoftwonumbers
txtOutput.text="Thisprogramdisplaysasentence"+vbnewline
txtOutput.text=txtOutput.text+"identifyingtwonumbersandtheirsum."+vbnewline
txtOutput.text=txtOutput.text+"Thesumof"+num1+"and"+num2+"is"+answer
EndSub
'Example2:Aprogramthataddstwonumbersandcallsasubprogramto
'displaytheheader
OptionExpliciton
PrivateSubcmdAdd_Click()
dimnumlAsDouble
dimnum2AsDouble
dimanswerAsDouble
numl=2
num2=3
answer=num1+num2
CallExplainPurpose
txtOutput.text=txtOutput.text+"Thesumof"+numl+"and"+num2+"is"+answer
EndSub
PrivateSubExplainPurpose()
'Explainthetaskperformedbytheprogram
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
40/64
11/6/2016
VisualBasicNotes
txtOutput.text=txtOutput.text+"Thisprogramdisplaysasentence"+vbnewline
txtOutput.text=txtOutput.text+"identifyingtwonumbersandtheirsum."
EndSub
'Example3:
'Aprogramthatcalculatesthesumoftwonumbersandcalls2subprograms
'1stsubdisplaysheader
'2ndsubadds/displaysthesumof2numbersbypassingthevaluesfromthe
'mainprogramtothesubprogram'AddDisplay
OptionExpliciton
PrivateSubcmdAdd_Click()
dimnumlAsDouble
dimnum2AsDouble
num1=2
num2=3
CallExplainPurpose
CallAddDisplay(num1,num2)
EndSub
PrivateSubExplainPurpose()
'Explainthetaskperformedbytheprogram
txtOutput.text=txtOutput.text+"Thisprogramdisplaysasentence"+vbnewline
txtOutput.text=txtOutput.text+"identifyingtwonumbersandtheirsum."+vbnewline
EndSub
PrivateSubAddDisplay(byValnum1AsDouble,byValnum2AsDouble)
'Displaynumbersandtheirsubs
dimanswerasDouble
answer=num1+num2
txtOutput.text=txtOutput.text+"Thesumof"+num1+"and"+num2+"is"+answer
EndSub
'Example#4
'Aprogramthatcalculatesthesumoftwonumbersthreetimesbyincluding
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
41/64
11/6/2016
VisualBasicNotes
'thenumbersasarguments.Subprogramscanbecalledaninfinitenumberof
'timessavingtheprogrammervaluabletime.
OptionExpliciton
PrivateSubcmdAdd_Click()
'DisplaythesumoftwonumberswiththeAddsubprogramcalledseveral
'times.
CallExplainPurpose
CallAddDisplay(2,3)
CallAddDisplay(4,6)
CallAddDisplay(7,8)
EndSub
PrivateSubExplainPurpose()
'Explainthetaskperformedbytheprogram
txtOutput.text=txtOutput.text+"Thisprogramdisplaysasentence"+vbnewline
txtOutput.text=txtOutput.text+"identifyingtwonumbersandtheirsum."+vbnewline
EndSub
PrivateSubAddDisplay(num1AsDouble,num2AsDouble)
'Displaynumbersandtheirsubs
txtOutput.text=txtOutput.text+"Thesumof+;num1+"and"+num2+"is"+num1+num2
EndSub
'Example#5
'Calculatesthesumoftwonumberscalling3subprograms
'1stsubexplainspurpose
'2ndsubgetstwonumbersinputtedbytheuser
'3rdsubaddsanddisplaysthesumoftwonumbers.
OptionExpliciton
PrivateSubcmdAdd_Click()
'Calculatesthesumoftwonumberscalling3subprograms
dimnum1AsDouble
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
42/64
11/6/2016
VisualBasicNotes
dimnum2AsDouble
CallExplainPurpose
CallGetData(num1,num2)
CallAddDisplay(num1,num2)
EndSub
PrivateSubExplainPurpose()
'Explainthetaskperformedbytheprogram
txtOutput.text=txtOutput.text+"Thisprogramdisplaysasentence"+vbnewline
txtOutput.text=txtOutput.text+"identifyingtwonumbersandtheirsum."+vbnewline
EndSub
PrivateSubAddDisplay(byValnum1AsDouble,byValnum2AsDouble)
'Displaynumbersandtheirsubs
DimanswerAsDouble
answer=num1+num2
txtOutput.text=txtOutput.text+"Thesumof"+num1+"and"+num2+"is"+answer
EndSub
PrivateSubGetData(byRefnum1AsDouble,byRefnum2AsDouble)
'Receivestwonumbersfromtheuser.
num1=Convert.ToDouble(txtNum1.Text)
num2=Convert.ToDouble(txtNum2.Text)
EndSub
UserDefinedFunctions
UserdefinedfunctionsarethesecondtypeofmodulethatVBsupports.Afunctionissimilartoasubprogrambecauseitisablockofcodethat
performsonejob.Functionsdifferfromsubprograms,becauseafunctionalwaysreturnsexactlyonevalue.Youhaveseenmanyfunctionsin
mathclass,toexecuteafunctionyoumustsendinanumberornumbersandthefunctionreturnstheanswer,anexampleisthecalculationofthe
areaofacircle.
PropertiesofUserDefinedFunctions:
theyareseparatefromthemainprogram
theycanuselocalvariables
theycanobtainparametersfromthemainprogram
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
43/64
11/6/2016
VisualBasicNotes
theyreturnexactlyonevalue(answer),always
ExecutingaUserDefinedFunction:
Sincefunctionsreturnexactlyonevalue,wemusthaveavariableinwhichtostoretheanswerreturned.Becauseofthis,functionsareexecuted
usinganassignmentstatement.Forexample,ifourfunctionisCalculateArea,thentorunthisfunctionwewouldwrite:
dimareaasDouble
area=CalculateArea(3)'3istheradiusofthecircle
DefiningaUserDefinedFunction
Creatingauserdefinedfunctionissimilartocreatingasubprogram,exceptthelaststatementmustbetheanswertobereturned.Theblockof
codethatistobethefunctionmuststartwiththefunctionheaderandendwithan'EndFunction'statement.
Thefunctionheaderhastheform:
PrivateFunction<functionname>(<parameterdeclares>)As<returnvariabletype>
FunctionName
Thefunctionnamecanbeanynameyouchoose.Itmuststartwithaletterandcontainonlyletters,digitsand_(noblanksareallowed).Inour
class,thenameshouldtaketheformofatleasttwowordsthatdescribewhatthefunctiondoes,thefirstwordshouldbeaverbandthesecond
shouldbeanoun.
ParameterDeclares
Parametersarevariablesthataredatathatwillbereceivedbythefunctionfromthemainprogram,soitcandoitsjob.Theyappearinthe
headingofafunction,suchas:
PrivateFunctionCalculateArea(byValradiusasDouble)AsDouble
theVBkeywordbyValindicatesthatanychangesbythefunctiontothevalueofaparameter,willnotbesentbacktothecalling
programyoushouldalwaysuseByValunlessyouhaveagoodreasonnotto!
theVBkeywordByRefindicatesthatanychangesbythefunctiontothevalueofaparameter,AREsentbacktothecallingprogram
ByRefwillnormallyonlybeusedbysubprogramsthatgatherinputfromthetextboxesonaformandneverbyfunctions,inourclass
theparametertypemustbeincluded(e.g.Double,string,integer)
thenamesoftheargumentsandparameterscanbethesameordifferent.Whatmattersisthattheorder,numberandtypesof
argumentsandparametersmatch.
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
44/64
11/6/2016
VisualBasicNotes
ReturnVariableType
Sincethefunctionmustreturnexactlyonevalue(answer),theheaderisfinishedwiththetypeofvariablethatwillbesentback.Itcanbeanyof
theVBvariabletypes(integer,Double,string,etc.)
CreatingaFunction
1.Moveyourcursortheendofyourcode,justbeforethe'EndClass'statement
2.Typeintheheaderofthefunctionwhichhasthefollowingformat:
PrivateFunction<functionname>(<parameterdeclares>)As<returntype>
3.Aseparatorlineandtwolinesofcodehavebeenaddedatthebottomofthecodewindow,alongwithan'EndFunction'statement.
4.TypethestatementsofthefunctionbetweenthePrivateFunctionandEndFunctionstatements.
FunctionExample
'Example1:
'Aprogramthatcalculatestheareaofacircle.
OptionExpliciton
OptionStrictOn
PrivateSubcmdCircle_Click()
dimradiusAsDouble
dimareaAsDouble
radius=2
area=CalculateArea(radius)
'Displaythearea
txtOutput.text="Theareaofthecircleis"+area.toString+vbnewline
EndSub
PrivateFunctionCalculateArea(byValradasDouble)AsDouble
dimareaasDouble
area=Math.PI*Math.pow(rad,2)
returnarea
EndFunction
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
45/64
11/6/2016
VisualBasicNotes
ShowingMultipleForms
AVBprogrammayconsistofmanyforms.Theformthatisfirstdisplayedwhentheprogramisstartedisspecifiedintheprojectpropertiesmenu
option.
Withinthedialogboxthatappearsfortheprojectproperties,the'startupObject'shouldindicatewhichformtoloadwhentheprogramisfirst
started.
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
46/64
11/6/2016
VisualBasicNotes
OtherformsthatmaybeinthesolutioncanbeshowninthecodeyouwritebyusingtheVBmethod'Show',thissetstheVisiblepropertyofa
formtotrue.The'Hide'methodcanbeusedtomakeaformdisappear,thissetstheVisiblepropertyofaformtofalse.Toshowaformcalled
form2anddrawabluesquarewecouldaddthecodebelowtoabuttononthefirstforminourprogram.
'declareaformobjectcalledabout,asatypeofform2
DimaboutAsNewform2()
about.Show()
'Drawabluesquareontheform.
'NOTE:Thisisnotapersistentobject,itwillnolongerbe
'visibleafterthenextcalltoOnPaint.Tomakeitpersistent,
'overridetheOnPaintmethodanddrawthesquarethere
DimgAsGraphics=about.CreateGraphics()
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
47/64
11/6/2016
VisualBasicNotes
g.FillRectangle(Brushes.Blue,10,10,50,50)
ModalForms
Attimesyoumaywantyourprogramtouseasecondformtoallowuserinput,butthestandardinputboxdoesnotmeetyourneeds.Inthiscase,
youneedtodesignasecondform,whichyoucanshowwhenneeded.Aformthatappearsandkeepsthefocus,untiltheuserdismissesit,is
called'modal'.TheVBmethod'ShowDialog'isusedtodisplaytheform.TheShowDialogmethodtakesaparameterwhichistheparentofthe
dialogform.Aftertheuserdismissesthedialogform,thecontentsoftheformcanberead,afterwhichyoushoulddisposeoftheformtorelease
unneededmemory.
'declareaformobjectcalledtestDialogasatypeofformwehavealreadydesigned(form2)
DimtestDialogAsNewForm2()
'ShowtestDialogasamodaldialoganddetermineifuserclickedOKbuttontoleave
IftestDialog.ShowDialog(Me)=System.Windows.Forms.DialogResult.OKThen
'ReadthecontentsoftestDialog'sTextBox.
txtResult.Text=testDialog.TextBox1.Text
Else
txtResult.Text="Cancelled"
EndIf
testDialog.Dispose()
Arrays
Avariableisanametowhichthecomputercanassignasinglevalue.Anarrayvariableisanorderedcollectionofvariablesofthesametypeto
whichthecomputercanefficientlyassignalistofvalues.
Avariablemarkwouldlooklikethis:
mark
64
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
48/64
11/6/2016
VisualBasicNotes
Anarrayof10markswouldlooklikethis:
index
mark
64
77
87
75
65
54
95
47
66
87
Allthestorageboxesarecalledmarkandtotellonefromanother,eachhasitsownnumber,calledtheindex.So,anarrayissimilartoamotel,
theentiremotelhasonenameandtodistinguishbetweenrooms,eachhasanumberonthedoor.Ineachelementofthearray(roomofthe
motel),wecanstoreonenumber.Intheexampleabove,64isstoredinthefirstelementofthemarkarray.
CreatinganArray
InVisualBasicwefirstmustdeclare(create)anarray(buildthemotel)beforewetrytostoreinformationinit.ThecommandfordoingthisisDIM.
DIMmark(20)asDouble
Createsanarraycalledmarkwithelements0to20thatstores21Doubles
DIMage(15)asinteger
Createsanarraycalledagewithelements0to15thatstores16integers
DIMname(10)asstring
Createsanarraycallednamewithelements0to10thatstores11strings
AssigningValuestotheelementsinanArray
Mark(1)=76Storesthenumber76inthefistelementofthearraymark
Mark(3)=87Storesthenumber87inthethirdelementofthearraymark
Displayingvaluesinanarray
txtOutput.Text=mark(1).toString
Toassign0ineveryelementinmark
mark(0)=0
mark(1)=0
mark(2)=0...
mark(20)=0
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
49/64
11/6/2016
VisualBasicNotes
OR
forx=0to20
age(x)=0
nextx
Toreadfromafile20marksandstoreinanarray
FileOpen(1,"marks.text",OpenMode.Input)
Forx=0to19
input(1,mark(x))
Nextx
FileClose(1)
Toreadfromafilewithanunknownnumberofrecord
FileOpen(1,"marks.text",OpenMode.Input)
count=0
Dowhilenoteof(1)
count=count+1
input(1,mark(count))
Loop
FileClose(1)
Todisplayall20marksinReverseOrder
forx=19to0step1
txtOutput.Text=txtOutput.Text+mark(x).ToString
nextx
Todisplaythevaluesstoredinoddelements,backwards,ononeline:
Forx=19to0step2
txtOutput.Text=txtOutput.Text+mark(x).ToString
Nextx
ToCalculatethetotalofallagesandtheaverage
total=0'initializevariables
Forx=0to19
total=total+mark(x)
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
50/64
11/6/2016
VisualBasicNotes
Nextx
average=total/20
txtOutput.Text=total.ToString+average.ToString
Toprintthehighestmark
highest=0
Forx=0to19
Ifmark(x)>highestthen
highest=mark(x)
endif
Nextx
txtOutput.toString=highest.ToString
Example1:Readingdataintoparallelarrayswhenthenumberofentriesinknown.
Thetablebelowgivesnamesandtestscoresfromamathematicscontest.Writeaprogramtodisplaythenamesofthestudentsscoringabove
theaveragefortheseeightstudents.
RichardDolen
133
GeraldineFerraro
114
JamesB.Fraser
92
JohnH.Malby
91
PaulH.Monsky
130
MaxA.Plager
114
RovertA.Shade
91
BarbaraM.White
124
'Thefollowingprogramcreatesastringarraytoholdthenamesofthecontestents
'andanumericarraytoholdthescores.Thenumberofcontestentsisknown.
PrivateSubcmdShow_Click()
dimtotalAsInteger
dimstudentAsInteger
dimaverageAsDouble
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
51/64
11/6/2016
VisualBasicNotes
'Createarraysfornamesandscores
dimnom(7)AsString
dimscore(7)AsInteger
'Assumethedatahasbeenplacedinthefile"SCORES.TXT"
'(Thefirstlineofthefileis"RichardDolen",135)
FileOpen(1,"student.txt",OpenMode.Input)
Forstudent=0To7
Input(1,nom(student))
Input(1,score(student))
Nextstudent
FileClose(1)
'Analyzeexamscores
total=0
Forstudent=0To7
total=total+score(student)
Nextstudent
average=total/8
'Displayallnameswithaboveaveragegrades
Forstudent=0To7
Ifscore(student)>averageThen
txtOutput.Text=txtOutput.Text+nom(student)+vbnewline
EndIf
Nextstudent
EndSub
Dynamicarrays
Canbeusedwhenyoudon'tknowexactlyhowlargetomakeanarraybecauseitcanberesizedatanytime.Afteradynamicarrayisinitially
declared,youcanaddnewelementsasneeded,ratherthanestablishingthesizeofthearrayatthetimethecodeiswritten.
Youdeclarethearrayasdynamicbygivingitanemptydimensionlistasfollows:
dimage()asinteger
Todimensionthearray,usetheRedimcommandasfollows:
Redimage(6)
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
52/64
11/6/2016
VisualBasicNotes
Or,usingavariable:
dimcountasinteger
count=6
redimage(count)
Note:redimdoesnotspecifythetypeofthearrayagainandthevalueinthebracketsistheindexoftheupperbound.
BoundsoftheArray
Sincetheupperboundcanbechangedbytheredimcommand,weneedawaytofindwhatithasbeensetat.VBprovidesthefunction:
arrayname.GetLength(0)returnsthenumberofelementsinthe1dimensionalarray,notethatthiswillalwaysbeonelargerthantheindexof
theupperboundbecausearraysareindexedstartingatthenumber0
Tocreateaforloopthatdisplaysallelementsofanarraynamed'age',withoutknowingtheupperboundwecanwrite:
forindex=0toage.GetLength(0)1
txtOutput.Text=txtOutput.Text+age(index).ToString+vbnewline
Nextindex
ArraysasParameterstofunctionsandsubs
Arrayscanbesenttofunctionsandsubsasparameters.Whensendinganarrayasaparameter,justsendthearrayname,notthearraysizeor
type.
Thisistrueforuserdefinedfunctionsandsubs.
Whencreatingauserdefinedsuborfunction,wespecifythearraynameandtype,butnotthebounds,inthefunctionheader,forexample:
PrivateSubDisplayNames(byrefnames()asstring)
Note:passinganarraybyrefmeansthatasecondcopyofthearrayisnotcreated,thussavingmemory.
RelatedArrays
Twoormorearraysaresaidtoberelated,iftheycontaininformationthatgoestogether,suchasonearraywithstudentnamesandasecond
arraywithscores.Inthiscase,theindexofthearraysconnecttheinformationinthearrays,forexample,index3isstudentnamesmithand
index3isthescoreforsmith.
'Thefollowingprogramcreatesastringarraytoholdthenamesofthecontestantsandanumericarraytoholdthescores.Thenumberof
contestantsisunknown.Usethedatafilefromthepreviousquestion.
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
53/64
11/6/2016
VisualBasicNotes
privateSubcmdShow_Click()
dimnumStudentsAsInteger
dimnTempAsString
dimsTempAsInteger
dimstudentAsInteger
dimTotalAsInteger
dimaverageAsDouble
dimnom()asstring
dimscore()asinteger
'Determineamountofdatatobeprocessed
numStudents=0
FileOpen(1,"scores.txt",OpenMode.Input)
DoWhileNotEOF(1)
Input#1,nTemp,sTemp
numStudents=numStudents+1
Loop
FileClose(1)
'Createarraysfornamesandscores
redimnom(numStudents1)AsString
redimscore(numStudents1)AsInteger
FileOpen(1,"scores.txt",OpenMode.Input)
Forstudent=0TonumStudents1
Input#1,nom(student),score(student)
Nextstudent
FileClose(1)
'Analyzeexamscores
Total=0
Forstudent=0TonumStudents1
Total=Total+score(student)
Nextstudent
average=Total/numStudents
'Displayallnameswithaboveaveragegrades
Forstudent=0TonumStudents1
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
54/64
11/6/2016
VisualBasicNotes
Ifscore(student)>averageThen
txtOutput.Text=txtOutput.Text+nom(student)+vbnewline
EndIf
Nextstudent
EndSub
StopWatchObject
VBhasaclassnamedStopWatchwhichcanbeusedtodetermineanelapsedtimebetweentwotimes.
TodeclareaStopWatchobject:
dimmyWatchasNewStopWatch
TheStopWatchmethodsandpropertiesare:
Method/Property
Purpose
Examples
OutputValue
Start
starts,orresumes,measuringelapsedtimeforaninterval
Stop
stopsmeasuringelapsedtimeforaninterval
myWatch.Stop()
ElapsedMilliseconds
returnstheelapsedtimeofinterval,measuredinmilliseconds
myWatch.ElapsedMilliseconds
numberofmillisecondsbetweenwhenthe
watchwasstartedandstopped
myWatch.Start()
Tocalculatehowmanymillisecondsablockofcodehasbeenrunningfor(theelapsedtime):
DimmyWatchasNewStopWatch
myWatch.Start()
....blockofcodetotimegoeshere...
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
55/64
11/6/2016
VisualBasicNotes
myWatch.Stop()
timeElapsed=myWatch.ElapsedMilliseconds
Searching
LinearSearch
Ifwehadanarrayof500namesandwantedtofindthelocationofaspecificnameinthearray,wecouldstartatthefirstelementofthearray,
checkit,thenmovetothenextelementofthearray,checkit,andsoonuntilwefoundthenamewewanted,oruntilwereachedtheendofthe
array.
Thealgorithmcanbestatedas:
currentindex=0
found=false
foundIndex=1
repeatwhilenotfoundandcurrent_index<array_upper_bound
ifcurrent_list_element=desired_elementthen
found=true
foundIndex=current_index
else
add1tocurrentindex
TocodeauserdefinedfunctioninVBthatreturnedtheindexofanameinanarrayofnames,wecouldwrite:
privatefunctionfindName(byrefnames()asstring,byvalseekNameasstring)asinteger
dimfoundasboolean
dimcurrentIndexasinteger
dimfoundIndexasinteger
found=false
foundIndex=0
currentIndex=0
dowhile(NOTfoundandcurrentIndex<names.GetLength(0))
ifseekName=names(currentIndex)then
found=true
foundIndex=currentIndex
else
currentIndex=currentIndex+1
endif
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
56/64
11/6/2016
VisualBasicNotes
loop
iffoundthen
returnfoundIndex
else
return1
endif
endsub
Thelinearsearchiseasytounderstandandcode.Itwillworkonanyarray.However,itisnotanefficientsearchingtechnique.
BinarySearch
Ifwehadanarrayof500namesinalphabeticalorderandwantedtolocateaspecificpersoninthelistweoneapproachistostartwiththefirst
nameandconsidereachnameuntilamatchwasfound.Thisprocessiscalledalinearsearch.Wewouldfindapersonsnamethatbeginswith
theletter"A"considerablyfasterthanwewouldanamebeginningwith"Z".Thismethodistimeconsumingforlargelists.
Ifalisthasalreadybeensortedamoreefficientbinarysearchcanbeperformed.
SampleList:
1.Alex
2.Dave
3.Dan
4.Dylan
5.Jason
6.Kyle
7.Matt
8.Saroja
LetsassumewearelookingforthenameKyle.Abinarysearchlooksforwhichhalfofthelistthenameliesinanddiscardstheotherhalf.The
retainedpartofthelistnowbecomestheentirelist.Thisprocessisrepeateduntiltheitemisfound.AflagcanindicateifKyleisfound.Thisis
muchthesamewayyouwouldlookupapersoninthetelephonebook.
Thealgorithmisasfollows:
1.Ateachstage,denotethesubscriptofthefirstitemintheretainedlistbyfirstandthesubscriptofthelastitembylast.Initially,thevalueof
firstisthelowerboundofthearray,thevalueoflastistheupperboundofthearray,andthevalueofthefoundflagisFalse.
2.Lookatthemiddleitemofthecurrentlist,theitemhavingthesubscriptmiddle=int(first+last)/2).
3.IfthemiddleitemisKyle,theflagissettoTrueandthesearchisover.
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
57/64
11/6/2016
VisualBasicNotes
4.IfthemiddleitemisgreaterthanKyle,thenKyleshouldbeinthefirsthalfofthelist.SothesubscriptofKylemustliebetweenfirstand
middle1.Thatis,thenewvalueoflastismiddle1
5.IfthemiddleitemislessthanKyle,thenKyleshouldbeinthesecondhalfofthelistofpossibleitems.SothesubscriptofKylemustlie
betweenmiddle+1andlast.Thatis,thenewvalueoffirstismiddle+1
6.Repeatsteps2through5untilKyleisfoundoruntilthehalvingprocessusesuptheentirelist.(Whentheentirelisthasbeenusedup,first
>=last.)Inthesecondcase,Kylewasnotintheoriginallist.
TocodeauserdefinedfunctioninVBthatreturnedtheindexofanameinanarrayofnames,wecouldwrite:
privatefunctionfindName(byrefnames()asstring,byvalseekNameasstring)asinteger
dimfoundasboolean
dimlowIndexasinteger
dimhighIndexasinteger
dimmiddleIndexasinteger
found=false
lowIndex=0
highIndex=names.GetLength(0)1
middleIndex=Convert.toInt32((highIndex+lowIndex)/2)
dowhile(NOTfoundandlowIndex<=highIndex)
ifseekName=names(middleIndex)then
found=true
elseifseekName>names(middleIndex)then
lowIndex=middleIndex+1
middleIndex=int((highIndex+lowIndex)/2)
else
highIndex=middleIndex1
middleIndex=int((highIndex+lowIndex)/2)
endif
loop
iffound=truethen
returnmiddleIndex
else
return1
endif
endsub
Thebinarysearchisnotaseasytocodeorunderstandasthelinearsearch,andthearraymustbesorted,however,itismuchmoreefficientthan
thelinearsearchingtechnique.
SortAlgorithms
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
58/64
11/6/2016
VisualBasicNotes
Therearemanydifferenttypesofsortingroutines.Herearesomeexamples.Belowisthepseudocodefortwodifferentsorts.
SelectionSort
Inaselectionsort,westartatoneendofthearraythe'selected'element.Wecompareeachelementinthearrayagainsttheselectedelement
andswapthemifnecessary.Whenonepassthroughtheentirearrayiscomplete,theselectedelementcontainsthelargest(orsmallest)value.
Wethenselectthenextelementtocompareallelementsagainst.
fori=thebeginningofthearraytotheend1
forj=thei+1elementtothelastelement
ifthejthelementissmallerthantheithelement
swapthejthelementwiththeithelement
Moreinformationishere.
BubbleSort
Inabubblesort,adjacentvaluesarecomparedandexchangediftheyarenotinorder.Witheachpassthroughtheentirearray,onemorevalue
'bubbles'upintoplace.
fori=beginningofthearraytotheend1
forj:beginningofthearraytoi1
ifthejthelementissmallerthanthej+1element
swapthejthelementwiththej+1element
Moreinformationisfoundhere,
Amoreefficientversionisfoundhere.
Aquiziffoundhere.
MultidimensionalArrays:
Twodimensionalarrayscanbethoughtofaslookinglikeatable,withrowsandcolumns.Therowsarethefirstdimensionandthecolumnsare
theseconddimension.
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
59/64
11/6/2016
VisualBasicNotes
columns
|
v
rows>
Thefollowingstatementdeclaresatwodimensional10by10array:
dimmatrixA(9,9)asDouble
Twodimensionalarrayscanalsobedynamicarraysanddeclaredwithoutanysizeandthenlaterdimensioned,forexample:
dimmatrixA(,)asString(Note:thecommaisrequiredtoindicate2dimensions)
dimmatrixA(5,7)
Todeterminethenumberofrowsandcolumnsofanexistingtwodimensionalarray,wecanusetheGetLengthcommand.Theparameterafter
thearraynameisthedimensionnumberweareinterestedingetting(startingat0).Forexample:
dimrowsasinteger
dimcolumnsasinteger
rows=matrixA.GetLength(0)1
columns=matrixA.GetLength(1)1
Whenaccessinganelementofatwodimensionalarray,wemustalwaysspecifybothdimensions.Forexample,theoutputthevalueofan
elementinrow5,column2toapicturebox,wewouldwrite:
txtOutput.Text=matrixA(5,2)
Twodimensionalarraysareoftenprocessedinnestedforloops.Forexample,tooutputallelementsofamatrix,wewouldwrite:
forrow=0tomatrixA.GetLength(0)1
forcolumn=0tomatrixA.GetLength(1)1
txtOutput.Text=txtOutput.Text+matrixA(row,column)
nextcolumn
nextrow
Menus
YoucanmakeyourVBprojectsveryprofessionalbyaddingmenustoyourprograms.YouselecttheMainMenucontrolfromthetoolboxandraw
itanywhereontheform.Youmustalsosettheformproperty'MenuName'toMainMenu,sothemenuisdisplayedwhentheprogramruns.
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
60/64
11/6/2016
VisualBasicNotes
ALT+lettershortcuts:
Typean&infrontoftheletterforwhichyouwouldliketheshortcut.Forexample,ifyouwantALT+finthefilemenusimplytype&Fileinthe
captionsectionofthemenueditor
Code:
Toaddcodetothemenuoptionsimplydoubleclickonthemenuitemintheprojectwindowandthecodewindowwiththesub/endsubforthat
menuitemwillbedisplayed.Addyoucode.
TimerObjects
Atimercanbeplacedonaform.Itdoesnotappearwhentheprogramisrun.Thetimergoesoffafterasetnumberofclicks(intervalproperty).
Whenthetimergoesoffitrunsthecodeinthetimer_timersub.Itcontinuestoruntheprograminthetimersubeverytimethetimeintervalis
reachedandinthatsenseisalsoarepetitionstructure.
MovingImages
Imageshave2propertiesthatcontrolwheretheimageappearsontheform.leftand.top.Thenumbersforthesepropertiesstartattheupper
leftcorneroftheform.Asthetopnumberincreasestheimagemovesdownthescreen.Astheleftnumberincreasestheimagesmovestothe
right
Tomovetheimagechangeitstopandleftproperties.
YoucanchangethepictureshownbyapictureBoxbycopyingthepicturefromanotherpictureBoxobject(usuallyinvisible).
picImage1.picture=picImage2.picture
changesimage1tothepicturethatisinpicImage2
Theswitchingisdonebyabooleanvariable,ifstatementandanot.
Exampleofswitchingimages:
inmodule
publicswitchasboolean
intimer
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
61/64
11/6/2016
VisualBasicNotes
ifswitchthen
picRealimage.picture=picInvisibleimage1.picture
else
picRealimage.picture=picInvisibleimage2.picture
endif
switch=notswitch
ReadingfromanAccessDatabase
DatamaybestoredinanAccessDatabase,ratherthanatextfile.Databasesallowyoutoaccessdatainadirectmanner,ratherthanneedingto
readthroughallthedatatofindwhatyouwant.Inaddiiton,withtheuseofanSQLSELECTstatement,adatabasefindsonlythedatayouare
interestedin.TheexamplebelowbuildsanSQLstatementthatselectsjusttheOrderIDandCustomerIDfieldsfromtheOrderstablewherethe
CustomerIDisequaltoavaluetakenfromatextboxontheformandtheamountoftheorderisgreaterthananamounttakenfromatextboxon
theform.TheAccessdatabasecalledCustomer.mdbholdsthedata.AReaderobjectreturnsthedatadesired.
DimmySelectQueryAsString=_
"SELECTOrderID,CustomerIDFROMOrdersWHERECustomerID='"&txtCust.Text&"'ANDAmount>'"&txtAmount.Text&"'"
DimmyConnStringAsString=_
"Provider=Microsoft.Jet.Oledb.4.0;DataSource=Customer.mdb"
DimmyConnectionAsNewOleDbConnection(myConnString)
DimmyCommandAsNewOleDbCommand(mySelectQuery,myConnection)
myConnection.Open()
DimmyReaderAsOleDbDataReader=myCommand.ExecuteReader()
dimstrOutputasstring
Try
WhilemyReader.Read()
strOutput="Customer:"&Reader.Item("CustomerID")&vbNewLine
strOutput&="Order:"&Reader.Item("OrderID")
MessageBox.Show(strOutput,"SearchResults")
EndWhile
CatchexAsException
MessageBox.Show("Anerroraccessingthedatabase.","ERROR!")
Finally
'alwayscallClosewhendonereading.
myReader.Close()
'alwayscallClosewhendonereading.
myConnection.Close()
EndTry
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
62/64
11/6/2016
VisualBasicNotes
ListBoxControl
AListBoxcontrol,displaysalistofitems.Ifthetotalnumberofitemsexceedsthenumberthatcanbedisplayed,ascrollbarisautomatically
addedtotheListBoxcontrol.
ToadditemsinaListBoxcontrol,usetheItems.Add,forexample:
lstNames.Items.Add("Michael")
ToremoveallitemsfromtheListBoxcontrol,usetheItems.Clearmethod,forexample:
lstNames.Items.Clear()
ListViewControl
AListViewcontrolcandisplayatableofrowsandcolumns.TosetthetheListViewcontroltodisplayinformationinrowsandcolumns,setthe
ViewpropertytoDetails.
ColumntitlesareaddedatdesigntimebyusingtheColumnsproperty,clicktheellipsesnexttoCollections.TheColumnHeaderCollections
EditorthenappearsandyoucanaddthecolumnheadingsintheTextpropertyforeachcolumn.
EachrowintheListViewcontrolisconsideredanListViewItem.Tostartanewrow,createanewListViewItem.Thecolumns,afterthefirst,are
consideredsubitems.ToadddatatothecolumnsusetheSubItems.Add()method.Whenyouhavecreatedallthedatafortherow,thenaddthe
rowtotheListViewwiththeItems.Add()method.Forexample:
DimrowAsListViewItem
row=NewListViewItem("Mike")
row.SubItems.Add("Casey")
row.SubItems.Add("12")
row.SubItems.Add("M")
lvwNames.Items.Add(row)
row=NewListViewItem("Pete")
row.SubItems.Add("Smith")
row.SubItems.Add("10")
row.SubItems.Add("M")
lvwNames.Items.Add(row)
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
63/64
11/6/2016
VisualBasicNotes
row=NewListViewItem("Sue")
row.SubItems.Add("Jones")
row.SubItems.Add("10")
row.SubItems.Add("F")
lvwNames.Items.Add(row)
http://doyle.wcdsb.ca/ICS3MI/Notes/notes.htm
64/64