Вы находитесь на странице: 1из 5

1/29/2017 VisualBasicCh.

7Notes,page1

CIS230,VisualBasic

Ch.7Notes,page1

Objective#1:Createanduselistboxesandcomboboxes.

TohandleinformationwithinaVBform,youcanusethelistboxandcomboboxcontrols.
Therearethreestylesofcomboboxes:simplecomboboxes,dropdowncomboboxes,anddropdownlists.Nodoubtyouhavealreadyseen
allthreeoftheseincommercialWindowsapplications.
ComboboxescanprovidechoicestotheuseratRuntime.Insteadofsimplydisplayinginformation,acomboboxallowstheuserto
selectoneitem.
ComboboxesalsohaveaTextpropertywhichdisplaysonthescreenfor2ofthe3comboboxstyles.
Usetheprefix"cbo"whennamingcomboboxes.
Listboxescanbeusedtodisplayinformationonaform.
Ifalistboxistoosmalltodisplayallofitsitems,VBaddsascrollbartothelistbox.
Usetheprefix"lst"whennamingalistbox.
Threeeventsassociatedwithlistboxesandcomboboxesareparticularlyuseful.YouwilllearnhowtousetheChange,GotFocus,and
LostFocuseventsinalaterchapter.

Objective#2:EnteritemsintolistboxesusingthePropertieswindowandtheAddItemmethod.

Thereareacoupleofwaystoinputdataintoalistbox.
YoucantypethedataforalistboxoracomboboxintoitsListpropertyduringdesigntime.BesuretopressControl+Enterbetween
items.
YoucanusetheAddItemmethodduringRuntimeinordertoadditemstotheListproperty.IfthenameofyourlistboxislstPlayers
thenthestatementlstPlayers.AddItem"MickeyMantle"wouldaddanitemtotheendofthelistbox.Youcanplaceanitemina
specificpositionbyspecifyingthepositioninastatementlike,lstPlayers.AddItem"MickeyMantle",4Thismethodwould
movetheoriginalitemsinpositions4andbeyondbackoneplace.

Objective#3:Determinewhichiteminalistisselected.

Whenauserselectsaniteminalistbox,theindexnumber(thatis,position)ofthatitemisstoredintheListIndexpropertyofthelistboxora
combobox.Ifnolistitemisselectedbytheuser,theListIndexpropertyissetto1.Youcanthendisplaythatitemwhichwasselectedbythe
usersomewhereelseinyourproject,inalabelperhaps.

Objective#4:UsetheListCountpropertytodeterminethenumberofitemsinalist.

Todisplaythenumberofitemsthatarecontainedinalistboxoracombobox,youcanusetheListCountproperty.Thestatement
lblNumPlayers=lstPlayers.ListCountwoulddisplaythenumberofitemsinthelistboxlstPlayersinthelabellblNumPlayers.

Objective#5:Displayaselecteditemfromalist.
http://www.minich.com/education/racc/visualbasic/cis230ch7/ch7notes1.htm 1/5
1/29/2017 VisualBasicCh.7Notes,page1

Ifyousimplyneedtodisplayanitemfromthelistboxthatisinaspecificposition,youcanusetheListpropertyofthelistbox.Forexample,if
"YogiBerra"isinthethirdpositionofthelistboxthenthestatement
lblCatcher=lstPlayers.List(3)wouldplacehisnameinthelabellblCatcher.Notethattheindexpositionofthestring"YogiBerra"is2
sincethefirstitemofalistboxisstoredinindexposition0.

Objective#6:Differentiateamongtheavailabletypesofcomboboxes.

Unlikelistboxes,comboboxeshaveaStylepropertywhichdetermineswhichofthreestylesthecomboboxistobe:
dropdowncomboallowstheusertoseetheTextpropertyandtoselectanitemfromadropdownlistofindividualitems.
simplecomboboxdoesnotallowtheusertoseetheTextpropertyandonlyallowstheusertoentertextintothetextboxareaatRun
time.
dropdownlistdoesnotallowtheusertoseetheTextpropertybutdoesallowtheusertoselectfromadropdownlistofindividual
items.

Objective#7:UseDo/LoopsandFor/Nextstatementstoiteratethroughaloop.

Programmersmakemuchuseofrepetitionstatements.Onetypeofrepetitionstatementisaloop.Therearetwokindsofloops,
indeterminateloopsanddeterminantloops.Do/LoopsarecommonlyusedindeterminateloopsinVBandFor/Nextloopsaredeterminant
ones.
Do/Loopsareindeterminatebecausetheyrepeatasequenceofstatementsuntilagivenconditionismet.Howmanytimestheloopwilliterate
(i.e.repeat)cannotbedeterminedbytheprogrammeratDesigntime.Theconditionisspecifiedinacontrolexpressionthatisplacedatthe
"topoftheloop"(i.e.onitsfirstline)oratthe"bottomoftheloop"(i.e.onitslastline.)Ifthecontrolexpressionislocatedatthetopofthe
loopthentheloopcanbecalledapretest.Otherwise,itisaposttest.Pretestsarealsocalledtopcheckingloopsandposttestsarebottom
checkingloops.
Onetypicalformatofapretestis:

DoUntil(controlexpression)
statements
Loop

wherethecontrolexpressionisanyconditionthatevaluatestoTrueorFalse.IfthetheexpressionisFalse,thenthecomputerskipsthe
remainingstatementsoftheloopandtheprogramcontinueswiththefirststatementaftertheloop.Anynumberofstatementscanbe
placed(andshouldbeindented)intheloop.
Atypicalformatofaposttestis:

Do
statements
LoopUntil(controlexpression)
InbothexamplesabovethekeywordUntilcanbereplacedbyWhiletochangethelogicofthealgorithm.
Booleanvariablesusedasflagsareveryusefulinindeterminateloopcontrolexpressions.ABooleanvariablecanonlyholdthevalueof
TrueorFalse.BysettingaBooleanvariableblnDonetoTrue,aprogrammercouldexittheloopsuchas
http://www.minich.com/education/racc/visualbasic/cis230ch7/ch7notes1.htm 2/5
1/29/2017 VisualBasicCh.7Notes,page1

blnDone=False

DoUntilblnDone
statements
Loop
Becarefulnottowriteinfinite(orendless)loops.Indeterminateloopscanbeinfiniteifthecontrolexpressionnevercausestheloopto
terminate.
For/Nextloopsontheotherhandaredeterminantloops.AprogrammercantellhowmanyiterationsaForloopwillhaveatdesigntime.Aloop
index(sometimescalledaloopvariable)canbeusedtostepthroughtheloopapredeterminednumberoftimes.
AnexampleofaFor/Nextloopis:

Forj=1To10
statements
Nextj

inwhichcasetheloopwoulditerate10timesexactly.Notethatj'sfinalvaluewillbe11.
AFor/Nextloopcanuseofastepvalue.Intheexample,

Form=1To100Step20
statements
Nextm

Theloopwoulditerate5timeswithmtakingonthevalues1,21,41,61,and81.Whilem'sfinalvaluewouldbe101,theloopwouldnot
iteratewhenmequals101.
Donotattempttochangethevalueoftheloopindexwithinthestatementsoftheloop.Thisisbadprogrammingstyleandwillcause
errors.
Ifyouwishtobreakoutofaloopinsomesituation,youmayuseanExitForstatementinsidetheloop.Thiswillcausetheprogram
controltomovetothefirstlineoftheprogramoutsideoftheloop.

Objective#8:UsetheMsgBoxfunctiontodeterminethebuttonpressedbytheuser.

Messageboxescanbeusedtodisplaymorethanonebutton.Infact,youcandeterminewhichbuttontheuserpressed.
ThesyntaxforusingtheMsgBoxfunctionisMsgBox(Prompt[,Buttons][,Title])wherePromptisthepromptstringthetheuser
readsinthemessagebox.ButtonsreferstoacombinationofVisualBasicbuttonsthatappearinthemessagebox.Titlereferstothecaptionon
themessagebox.Thefunctionreturnsanintegervaluebetween1and7indicatingwhichbuttonwaspressed.Seethechartsonp.262for
detailsofusingtheMsgBoxfunction.

Objective#9:UsethestringfunctionsLeft,Right,andMidtorefertopartofastringandusetheLenfunctiontocountthenumberof
charactersinastring.

http://www.minich.com/education/racc/visualbasic/cis230ch7/ch7notes1.htm 3/5
1/29/2017 VisualBasicCh.7Notes,page1

ThereareanumberofstringfunctionsthatcanbeusedinVBtoformatstringsnicelyforoutputordisplay.Forexample,ifapersonenterstheir
nameas"JohnDoe",youmaywishatalaterpointintheprogramtodisplaythename"Mr.Doe".Youcouldusestringconcatenationalong
withtheRightfunctiontodothis.
TheLeft,Right,andMidstringfunctionseachreturnaselectedportionofastring.
TheLeftfunctionreturnsaspecificnumberofcharactersfromtheleftendofastringvariable,astringliteral,oratextbox.
ThegeneralformoftheLeftfunctionisLeft(StringExpression,NumberOfCharacters)
Examples:
Left("John",2)returns"Jo"'notethat"John"isastringliteral
Left(strName,5)returns"Sally"ifthestringvariablestrName="SallyFields"
Left(txtEntry,3)returns"113"iftheTextpropertyofthetextbox,txtEntryis"113,456"
TheRightfunctionreturnsaspecificnumberofcharactersfromtherightendofastringexpression.
ThegeneralformoftheRightfunctionisRight(StringExpression,NumberOfCharacters)
Examples:
Right("John",3)returns"ohn"
Right(strName,5)returns"ields"ifthestringvariablestrName="SallyFields"
Right(txtEntry,3)returns"456"iftheTextpropertyofthetextbox,txtEntryis"113,456"
TheMidfunctionreturnsasubstringthatbeginswithaparticularcharacteroftheoriginalstringandendswithaspecifiedspot.
ThegeneralformoftheMidfunctionisMid(StringExpression,StartPosition,NumberOfCharacters).Thethirdargument
NumberOfCharactersisoptional.IfitisnotspecifiedthenthewholesubstringformedbythecharactersaftertheStartPositionis
returned.
Examples:
Mid("John",3,1)returnstheletter"h"
Mid(strName,5,3)returns"Fi"(atotalof3characterswiththefirstonebeingaspace)ifthestringvariablestrName=
"SallyFields"
Mid(txtEntry,3)returns"3,456"
TheLenfunctionreturnsthelengthofastringexpressionasaninteger.Allofthecharactersinthestringexpressionarecountedaspart
ofthelengthincludingspacesandpunctuationsymbols.
Examples:
Length("Mississippi")=11
Length(strName)=12wherestrName="SallyFields"
Length("Bill"&"Gates")=9
Length(Right("Visual",3)&"Basic")=8
TheSelStartandSelLengthpropertiesoftextboxescanbeusefulwiththestringformattingfunctions.Whenthefocusisplacedintoa
textbox,theusercanselectanynumberofcharactersinthestringexpressionofitsTextproperty.TheSelStartpropertyofatextboxcan
setorreturnthepositionofthefirstselectedcharacter.TheSelLengthpropertycansetorreturnthenumberofselectedcharacters.
Examples:
ThiseventsubroutinecausesthetextwithinthetextboxnamedtxtExampletobeselectedassoonasitreceivesthefocus:

PrivateSubtxtExample_GotFocus()
WithtxtExample
.SelStart=0
http://www.minich.com/education/racc/visualbasic/cis230ch7/ch7notes1.htm 4/5
1/29/2017 VisualBasicCh.7Notes,page1

.SelLength=Len(.Text)
EndWith
EndSub

Objective#10:SendinformationtotheprinterusingthePrintmethod.

ThePrintmethodallowsyoutoprinttextonaform,onthePrinterobject,orintheDebugwindow.
EachtimethatyouusethePrinter.Printmethod,youroutputisaddedtothePrinterobjectwhichiscreatedbyVB.Whentheprintjobendsor
whenitreceivesanEndDocorNewPagemethod,VBsendsthecurrentcontentsofthePrinterobjecttotheprinter.
TheNewPagemethodactuallysendsthecurrentpagetotheprinterandclearstheprinterobjectinthememoryofthecomputersoyoucan
beginanewpage.TheEndDocmethodsendsthecurrentpagetotheprinterandterminatesthewholeprinterjob.Withincodethestatements
wouldlooklikePrinter.NewPageandPrinter.EndDocsincetheyaremethods.

Objective#11:Controltheformatofprintingusingcommas,semicolons,theTabfunction,andtheSpcfunction.

ChooseafixedpitchfontsuchasCourier,ifyouwanteverycharacterofyourprintedoutputtotakethesameamountofspace.Otherwise,you
maybeusingaproportionalfont.
AVBoutputpagehaspresettabsettingswithfivecolumnsperline.Eachcolumnisaprintzone.Acommaplacedinastringofoutputisused
toadvanceasingleprintzone.Thereforeacommaworkssimilarlytoatabinwordprocessingortyping.
Example:Printer.Print"Name","SocialSecurityNumber"causesNametoappearinthefirstprintzoneandSocialSecurity
Numberinthesecondprintzone.
Theonlywaytochangethesizeofaprintzoneistochangethefontsize.Thewidthofaprintzoneis14characters,basedontheaverage
sizeofacharacterforthefontbeingused.Somorethan14characterscouldfitinaprintzoneifyouusedaproportionalfontand
includedmanyi'sandt's.Sometimes,theitemsyouprintcouldoverflowtheprintzone.Ifthenumberofprintzonesexceedsthenumber
forasingleline,theoutputwillwordwraptothenextlineontheprintedpage.TochangetheFontpropertyofthePrinterobject,you
mustusestatementslikePrinter.Font.Name="Arial"andPrinter.Font.Size=12
Ifyouwishtwostringexpressionstobeprintednexttoeachotheryoucanuseasemicolonintheoutput.Forexample,Printer.Print
"Vis""ual"willcausethestring"Visual"tobeprintedontheprinter.
Toprintablankline,simplyusethestatementPrinter.Print
TheTabfunctioncanbeusedtospecifythecolumnpositioninwhichyouwishtopreciselyprintastringexpression.Forexample,the
statementPrinter.PrintTab(10)"Hello"printsthestringhellowherethe'H'inthe10thcolumnoftheline.
TheSpcfunctioncanbeusedtospecifyanumberofspacesbetweenseveralprinteditems.Forexample,thestatementPrinter.Print
"John"Spc(10)"Doe"causes10blankspacestoappearbetween"John"and"Doe".
ItispossibletoprintstringexpressionsnexttoeachotherwithstatementslikePrinter.PrintstrFirst&strLastwhichwouldprint
"JohnDoe"ifstrFirst="John"andstrLast="Doe".ButVBautomaticallyaddsaspaceinfrontofanumericalvalueforthesign(positiveor
negative).Therefore,thestatementPrinter.Print"123"&456wouldprint"123456"sincespaceisallowedforthesignofthenumerical
value456.

CIS230HomePage|Mr.Minich'sEducationHomePage|Minich.comWebDesign

http://www.minich.com/education/racc/visualbasic/cis230ch7/ch7notes1.htm 5/5

Вам также может понравиться