Académique Documents
Professionnel Documents
Culture Documents
8Notes,page1
CIS230,VisualBasic
Ch.8Notes,page1
Objective#1:Setupanduseacontrolarray.
Anarrayisagroupofobjectswiththesamename.Inthischapter,youwillstudytwokindsofarrays,controlarraysandarraysofvariables.
AcontrolarrayissimplyagroupofVBcontrolsthathavethesamename.Remember,controlsareobjectsthatyoucanplaceonaformthat
suchascommandbuttons,textboxes,andlabels.Inacontrolarray,eachcontrolmustbeofthesameclass.Thatis,nomatterhowmany
controlsareinacontrolarray,theyallhavetobethesametypeofcontrol,optionbuttonsforexample.
Individualcontrolswithinacontrolarraycanbereferencedbyanindex(sometimescalledasubscript.)Actually,thewholenameofan
individualcontrolinacontrolarrayincludestheindexwhichisplacedinparentheses.Thenameofaspecificcontrolinacontrolarrayof
commandbuttonsmightbecmdLevel(5)where5istheindex.
AllofthecontrolsinacontrolarraysharethesameClickmethod(aswellasothermethodsspecifictothetypeofcontrol.)Thisallowsa
programmertoefficientlyplaceonecodesegmentinthebodyoftheClickeventprocedureandexpectittoexecutewhentheuserclicksonany
ofthecontrolsinthecontrolarray.Insomesituations,itisnotdesirabletohavesuchoverlapbutinothersitisextremelyuseful.
Eachofthecontrolsinacontrolarraycanhaveuniqueproperties,however.Therefore,youcouldmaketheBackColorofonecommandbutton
vbGreenandanother'svbBluebutstillexpectthesamecodetoexecutewheneitheroneisclicked.
Tocreateacontrolarrayofoptionbuttonsforexample,youfirstcreateanoptionbuttonbutchangeitsnametooptCar(0).Thatisyoutype0in
parenthesesaftertheactualnameoftheoptionbutton.ThiscausesallsubsequentoptionbuttonsthatarenamedoptCartoautomaticallytake
thenamesoptCar(1),optCar(2),optCar(3),etc.Notethatthefirstcontrolinacontrolarrayalwayshastheindex0.
Youcanalsocreateacontrolarraybycreatingthefirstcontrolasusual.Thencopyandpasteaduplicateofthatcontrolonthesameform.VB
willaskyouwhetheryouwouldliketocreateacontrolarrayandifyouclick"Yes",thenextcontrolofthattypewilltaketheappropriatename
withanindexof1.
Objective#2:CodeselectionlogicusingaSelectCasestatement.
GenerallymostnestedIfstatementscanberewrittenasaSelectCasestatement.OftenSelectCaseisusedbecauseitiseasiertoreadand
understand.
ThegeneralformoftheSelectCasestatementis:
SelectCaseexpression
Caseconstantlist
statement(s)
[Caseconstantlist]
[statement(s)]
[CaseElse]
[statement(s)]
EndSelect
http://www.minich.com/education/racc/visualbasic/cis230ch8/ch8notes1.htm 1/6
1/29/2017 VisualBasicCh.8Notes,page1
Usuallytheexpressioninthefirstlineisavariable.Dependingonthevalueofthatvariable,thecomputerwillperformthestatementsinoneof
thebranchesundereachCasestatements.Theconstantlistsarespecificvaluesorrangesofvaluesthatthevariablecouldtakeon.
Whileitisnotrequired,specifyingaCaseElseisawiseideasinceitcanbeusedeffectivelyforerrorcheckingandvalidation.
OnceVBmatchestheexpressionwithoneoftheconstantlistsandperformsthestatementsdirectlyafterthatconstantlist,itwilltransfer
controltothefirstlineofcodebelowtheEndSelectstatement.
TheSelectCasestructureisparticularlyeffectivewithintheClickprocedureofacontrolarrayofoptionbuttons.AnargumentnamedIndexis
automaticallysenttotheClickeventforanoptionbuttoncontrolarray.Thisargumentindicateswhichoptionbuttonwasactuallyclickedbythe
user(remembertheindexofthefirstcontrolinacontrolarrayiszeronotone.)Seepp.291&292foragoodillustrationofhowSelectCaseis
reallyusefulinthissituation.
Objective#3:Establishanarrayofvariablesandrefertoindividualelementsinthearraywithvariablesubscripts
Inanyprogramminglanguage,onecancreateanarrayofvariables.Oftenarraysofvariablesaresimplycalledarrays.Ifyoumeantoindicate
thatsomethingisacontrolarrayasopposedtoanarrayofvariables,youshouldclearlystatethatitisa"controlarray."
Anarrayofvariablesisagroupofvariableswiththesamedatatypeandnameexceptthatitisrequiredtoplacetheindexofspecificarray
variableattheendofitsname.Ifyouwerewritingateacher'sgradebookprogramforexampleyoumaywishtostorethesemester's5quizzes
forastudentinanarrayofvariableswithspecificvariablesnamedStudentQuizzes(0)throughStudentQuizzes(4).Theonlyreasonindexvalues
0through4areusedinsteadof1through5isbecauseVBsetsthefirstarrayvariabletoindex0bydefault.
Usingarraysofvariablesmakesiteasytomanipulate,search,sort,andperformothertaskswithrelatedvariables.Forexample,toinitializeall
5ofastudent'squizscorestozeroatthebeginningofasemester,youcouldusebruteforcelike:
StudentQuizA=0
Forj=0To4
StudentQuizB=0
or,youcouldusealoop StudentQuizzes(j)=0
StudentQuizC=0
andanarray: Nextj
StudentQuizD=0
StudentQuizE=0
Theactualvaluesthatarestoredinspecificarrayvariablesarecalledelements.Intheexample,abovezeroisanelementofall5subscript
positionsofthearrayStudentQuizzes.
Objective#4:UsetheForEach/Nexttotraversethearray.
Traversinganarraysimplymeansvisitingeachposition/elementofthearray.Youcouldtraverseanarrayinordertosearchfortheoccurrence
ofaspecificvalueoryoucouldtraverseanarrayinordertosubtotalitselements.
Tofindasubtotaloftheelementsofanarray,youcouldusealoopandanaccumulatorstatement:
Forj=1To5
intTotal=intTotal+StudentQuizzes(j)
Nextj
Todeclareanarray,youuseastatementlikeDimStudentQuizzes(5)AsIntegerwherethearrayStudentQuizzeswillbeabletoholdfive
elementsinwithsubscripts0through4.Ifyouprefertoworkwithsubscripts1through5youcanspecifythatrangewithadeclaration
http://www.minich.com/education/racc/visualbasic/cis230ch8/ch8notes1.htm 2/6
1/29/2017 VisualBasicCh.8Notes,page1
statementlikeDimStudentQuizzes(1To5)AsInteger.
Itispossibletocreateadynamicarraywherethetotalnumberofelementsinanarrayisnotspecified.Otherwise,youarecreatingastatic
arraywhichcannotchangeitssizeduringaprogram'sexecution.
TheForEach/Nextloopstructureallowsyoutoconvenientlytraverseanarray.Forexample,youcouldinitializeeachelementofthearray
intExampletoacertainvaluewiththefollowingcode:
Forj=1To10
intExample(j)=15
Nextj
or,youcoulduseaForEach/Nextloop,
DimvntTempAsVariant
ForEachvntTempInintExample
vntTemp=15
NextvntTemp
wherethevariantvariablevntTempissimplyusedwiththelooptotraversethearrayintExampleandassigneachelementthevalue15.TheFor
Each/NextloopmaynotseemparticularlymoreefficientthantheFor/Nextloopbutifyouneedtotraverseandinitializeamultidimensional
arrayitisabetterchoice.InsteadofnestedFor/Nextloops....
Forr=1to10
Forc=1to10
intExample(r,c)=15
Nextc
Nextr
theForEach/Nextloopismoreefficient...
ForEachvntTempInintExample
vntTemp=15
NextvntTemp
sincetheloopdoesassigneveryelementofthetwodimensionalarrayintExampletothevalueof15.
Objective#5:Createuserdefineddatatypesformultiplefieldsofrelateddata.
VBallowsyoutouseanumberofsimpledatatypessuchasInteger,String,Boolean,Long,etc.Sometimes,itisveryusefultousemore
complicatedvariabledatatypes.Youcancreateyourownuserdefineddatatypesinsuchsituations.
Userdefineddatatypesareusedtocombinerelateddataintounits.Forexample,itmaybeefficientforagradebookprogramtohaveauser
defineddatatypecalledStudentwhichhasindividualfieldsforastudent'sname,SocialSecurityNumber,YearofGraduation,Telephone
http://www.minich.com/education/racc/visualbasic/cis230ch8/ch8notes1.htm 3/6
1/29/2017 VisualBasicCh.8Notes,page1
Number,etc.
OneusesaTypestatementtocreateauserdefineddatatypeinthegeneraldeclarationssectionofamodule.Ifitisusedinaformmodulethe
keywordPrivatemustbeusedbeforethewordType.
AnexampleofaTypestatementis:
TypeStudent
strLastNameAsString
strFirstNameAsString
strSocSecNumbAsString
intYrGraduationAsInteger
strTelephoneNumberAsString
EndType
Thisuserdefineddatatypehas5fields.
Toaccessinformationwithinoneofthefieldsofauserdefineddatatype,youmustusedotnotation.Forexample,tohavethelastnameofa
studentplacedinalabelnamedlblExample,youwouldfirsthavetoassumethatavariableofdatatypeStudentwasdeclaredasinDim
udtTeachersPetAsStudent.YouwouldalsoassumethatthefieldstrLastNameofudtTeachersPetcontainssomeone'slastname.Tohave
thatelementplacedinthelabel,usethestatementlblExample.Caption=udtTeachersPet.strLastNameNotethatudtisthecommon
prefixforuserdefineddatatypes.
OftenonedeclaresanarrayofauserdefineddatatypesuchasawholearrayofvariablesoftypeStudent.Suchadeclarationwouldlooklike
DimClassList(30)AsudtTeachersPetandtoplacethefirstnameofthe5thpersoninthearrayClassListintoLabel1,usethe
codeLabel1.Caption=ClassList(4).strFirsName(Notethattheelementinthefifthpositionwouldhavethesubscriptof4.)
Objective#6:Accumulatetotalsusingarrays.
AccumulatorstatementssuchasintTotal=intTotal+intNextAmountareoftenusedtocomputetotals.Arrayscaneasilybeusedwith
accumulatorstatementssincearraysaregroupsofvariablesthatcanbeaddedandsubtotaled.
Itiseasytoobtainthetotalsumoftheelementswithinanarraywithcodelike,
intTotal=0
Forj=1To10
intTotal=intTotal+intMyArray(j)
Nextj
Simplyusetheloopvariablejtoreferenceeachelementinthearray,intMyArray
Anevenmorecomplicatedaccumulationofmanytotalscanbeachievedusinganarrayofvariables.SupposethatthearrayintNFLTeamWinsis
usedtoholdthenumberofwinsforeachNFLfootballteamandthatthearrayhas31elementsindexedfrom1to31.Furthermore,supposethat
theuserenterstheindexnumberreferringtoaspecificteaminthetextboxtxtTeamalongwiththatteam'snumberofwinsintoatextbox
namedtxtWins.ToaccumulatetheupdatednumberofwinsforthatteamthestatementintNFLTeamWins(Val(txtTeam.Text))=
Val(txtWins)canbeused.UsingtheteamnumberasanindextothearrayintNFLTeamWinsisatechniquecalleddirectreference.
http://www.minich.com/education/racc/visualbasic/cis230ch8/ch8notes1.htm 4/6
1/29/2017 VisualBasicCh.8Notes,page1
Objective#7:Distinguishbetweendirectaccessandindirectaccessofatable.
Whenaspecificelementofatablemustbemodified,yousimplyneedtorefertoitsrowandcolumnsubscripts.Forexample,toaddthevalue
5totheiteminthesecondrowandthirdcolumnofatable,thestatementintExample(1,2)=intExample(1,2)+5wouldwork.
NotethattheelementintExample(1,2)isfoundinthesecondrowbecausetherownumbersbeginwithzero.Thistechniqueusesdirectaccess
toatablesincetheactualsubscriptsarebeingused.
Ontheotherhandsupposethatyoudonotknowtheactualsubscriptsoftheelementinanarraythatyouwishtomodify.Inthiscaseyoumust
useatablelookup.SupposeauserdatatypeTeamandanarrayofTeam'snamedudtNFLTeamsexists.EachudtNFLTeamelementcontains
twofields,strNameandintWins.Ifaprogrammerwantstoupdatethenumberofnewwins(intNewWins)foraspecificteam,he/shemustfirst
determinetheindexofthatteaminthearrayudtNFLTeams.Byperformingatablelookup,youcanupdatetheintWinsfieldoftheappropriate
elementofthearray.YoucouldasktheusertoenterthenameoftheteamandcomparethisuserinputwiththestrNamefieldofeach
udtNFLTeamsarrayelement.Usealoopfrom0ton1wherenisthenumberofelementsinthearray.Iftheloopvariableisjthenthe
statementwouldlooklikethis:
IftxtUserInput=udtNFLTeams(j).strNameThenudtNFLTeams(j).intWins=_
udtNFLTeams(j)+intNewWins
Thismethodofaccessinganelementofanarraywithoutfirstknowingtheelement'ssubscriptorindexisconsideredindirectaccess.
Objective#8:Combinetheadvantagesoflistboxcontrolswitharrays.
TheListIndexpropertyofalistboxorcomboboxallowsaprogrammertodeterminewhichitemisselectedbytheuser.Eventhoughthe
valuesinthelistboxmaynotbenumeric,theListIndexpropertywillbeanumberbetween0andn,wherenisthenumberoftotallistbox
itemsminus1.WiththeListIndexpropertyyoucandirectlyreferenceanelementofanarrayinorderto,say,addittoarunningtotal.
Objective#9:CoordinatelistsandarraysusingtheItemDataproperty.
Oneproblemthatcouldoccurwhenyouareworkingwithlistboxesandarraysisthattheoriginalelementsofalistboxcouldbesorted(using
thelistbox'sSortedproperty).Whenthelistboxitemsaresorted,theListIndexofeachelementisprobablygoingtobedifferentfromits
originalListIndex.Usingthetechniquedescribedinobjective#8wouldnotworkcorrectlyinthiscase.
TheItemDatapropertycanbeusedtoassociateaspecificnumberwitheachelementofalistboxorcombobox.TheItemDatapropertyfor
eachelementwillnotchangewhenthelistboxissorted.UsetheItemDatapropertyjustasyouwouldtheListIndexpropertyinthiscase.
YoucanalsousetheItemDatapropertytoassignspecificvalueswitheachelementofalistboxifyoudonotwanttorefertotheitemsas
havingpositions(ListIndexproperties)runningfrom0ton1(wherenisthenumberoftotalitems.)
IfyouchoosetousetheAddItemmethodtoaddanewlistboxitemduringruntime,thenewitemwillbeaddedtotheendofthelistbox.The
ListIndexpropertyofthenewitemwouldbethenextavailableindexnumbernotalreadyassigned.TheItemDatapropertyforthenewitem
howevermustbespecificallyassigned.Ifthelistboxwasalreadysortedthough,AddItemaddsanewitemtotheappropriatesortedposition.In
thiscasetheItemDatapropertyofthenewitemisdeterminedbyVisualBasicandstoredinthelistboxes'NewIndexproperty.Youcan
referencetheNewIndexpropertyuntilAddItemisusedagain.
Objective#10:Storedatainmultidimensionalarrays.
http://www.minich.com/education/racc/visualbasic/cis230ch8/ch8notes1.htm 5/6
1/29/2017 VisualBasicCh.8Notes,page1
Ifthedatathatyouwouldliketostorecanbeconvenientlyarrangedinrowsandcolumnslikespreadsheetdata,thenyoushoulduseatwo
dimensionalarray.Atwodimensionalarray(calledatableoramatrix)usestwosubscriptstoidentifyeachelement.Thesubscriptsare
usuallyreferredtoastherowandthecolumn.
AnelementinatwodimensionalarrayisreferredtowithnotationlikeName(3,4)where3referstotherowoftheelementand4referstothe
column.
Example:
13 54 0 29 18
48 71 1 82 46
Ifyouwishtorefertotheelement29inthetwodimensionaltable,Demo,above,youmustusethereferenceDemo(0,3).
Rememberthatthefirstrowisrow0andthatthefirstcolumniscolumn0.Ifyouwishtorefertothe13,yourefertoDemo(0,0).Ialways
rememberthesoftdrinkRCColatorememberwhichsubscriptcomesfirst,roworcolumn.
AnysizedmultidimensionalarraycanbeusedinVB.Thereforethearraycouldusemorethantwosubscriptstoreferenceeachelement.
However,multidimensionalarraysgreaterwithmorethan2dimensionsarerarelyused.
CIS230HomePage|Mr.Minich'sEducationHomePage|Minich.comWebDesign
http://www.minich.com/education/racc/visualbasic/cis230ch8/ch8notes1.htm 6/6