Sei sulla pagina 1di 6

1/29/2017

VisualBasicCh.4Notes,page1

CIS230,VisualBasic

Ch.4Notes,page1

Objective#1:UseblockIfstocontroltheflowoflogic.

Conditionalstatementsareusedinmostprogramminglanguagestoallowaprogramtofollowdifferentcontrolpaths.Thatis,yourprogram

canrespondtouserinputsorarithmeticexpressionsindifferentwayswhenyouuseaconditionalstatement.TheIfstatementisanexampleof

aconditionalstatement.

ThegeneralformfortheIfstatementis

If (condition) Then statement(s) [ElseIf (condition) Then statement(s)] [Else statement(s)] EndIf

Notethatthereisnospaceinthekeyword,ElseIf,andthatthereisaspaceinthelastline,EndIf.

Inthegeneralformabove,bracketsindicatethatthesectionisoptional.

Therefore,anIfstatementcouldbeassimpleasthefollowingexample:

If(condition)Then

X=50

EndIf

Thelastline,EndIf,isNOToptionalthough.ThislineindicatesthattheIfstatementhasended.

Ontheotherhand,thefollowingIfstatementcouldbeusedfollowingthegeneralform:

If(condition)Then

X=50

ElseIf(condition)Then

1/29/2017

VisualBasicCh.4Notes,page1

X=60

EndIf

AnotherexampleofamildlycomplicatedIfstatementis:

If(condition)Then

X=50

ElseIf(condition)Then

X=60

Else

X=100

EndIf

YetanotherexampleofavalidIfstatementis:

If(condition)Then

X=50

ElseIf(condition)Then

X=60

ElseIf(condition)Then

X=70

ElseIf(condition)Then

X=80

ElseIf(condition)Then

X=90

Else

X=100

EndIf

Thatis,youmayhaveasmanyElseIfportionsasyouneedbutyoucanonlyuseone(ifany)Elseportion.Eitherwayyoumustendthe

wholeIfstatementwithanEndIfline.

TheIfstatementsabovearecalled"blocks"becausetheyhavemultiplelinesofcodebutyettheyeachconsistofonlyoneexecutablestatement.

Also,itisproper(butnotabsolutelynecessary)toindentthestatementsundertheThenandElseclauses.Thismakesiteasierforothersto

understandyourcode.

ItispossibletowriteanIfstatementononelineofcodeasinthefollowingexample:

If(condition)ThenX=50

inwhichcase,noEndIflineisnecessary.InthiscaseyouwouldnotconsidertheIfstatementtobeablockofcode.Thisshouldonlybedone

forverysimpleIfstatementsthatwouldbeeasyforfellowprogrammerstounderstand.

1/29/2017

VisualBasicCh.4Notes,page1

TheconditionsreferredtointhegeneralformoftheIfstatementandtheexamplesaboveareBooleanexpressions.ABooleanexpressionis

onethatevaluatestoaBooleanTRUEvalueoraBooleanFALSEvalue.Anexampleofaconditionis(Total<100).IfthevariableTotalis

lessthan100,thentheBooleanexpressionevaluatestoTRUE.IfthevariableTotalisequalto100,theBooleanexpressionevaluatesto

FALSE.IfTotalisgreaterthan100,thentheexpressionevaluatestoFALSEaswell.

Writingconditionsthatreflectthelogicnecessarytomakeyouralgorithmworkcorrectlyisthedifficultpart.Havingonesymbolmisplacedor

reversedcaneasilycauseyourIfstatementtoworkincorrectly.

WhileyoumayuseasmanyElseIfclausesasyouwouldlikeinoneIfblock,thefirstconditiontoevaluatetoTRUEwillcausethenext

statementtoexecute.BasicwillthensendtheflowoftheprogramtothenextstatementaftertheEndIf.IfneithertheinitialIfconditionnor

anyoftheElseIfconditionsevaluatetoTRUEthentheElsestatementwillexecuteifthereisone.TheElsestatementcanbeconsidereda

defaultstatementwhichevaluatesifnootherstatementsexecute.

Objective#2:UnderstandandusenestedIfs.

IfanIfstatementisentirelycontainedbetweentheThenandtheEndIfofanotherIfstatement,thestatementisconsideredtobeanestedIf

statement.

Example:

If(condition)Then

[statement(s)]

If(condition)Then

statement(s)

EndIf

[statement(s)]

EndIf

(andIf/ElseIf)statementsbutitisyourresponsibilitytomakesurethatyouralgorithmisintelligible.

formaluseofsuchflowchartsthoughinclass.

Diamond­shapesymbolsinflowchartsrefertoconditionsandshowhowtheflowofcontrolcanbranchoneoftwoways.

Objective#4:Evaluateconditionsusingtherelationaloperators.

alsouse6differentrelationaloperatorscanbeusedwithintheBooleanexpressionsthatmakeupconditions.Relationaloperatorsare

sometimescalledcomparisonoperators.The6relationaloperatorsare:

1/29/2017

VisualBasicCh.4Notes,page1

< lessthan

> greaterthan

= equalto (inthiscontextthe=symbolisusedasarelationaloperator,notasanassignmentoperator)

<> notequalto

>= greaterthanorequalto(thereisnospacebetweenthetwosymbols)

<= lessthanorequalto

Whenyouuserelationaloperators,youshouldmakesurethatthetwooperands(variablesorvalues)thatyouarecomparinghavethesamedata

type.Forexample,thecondition(intTotal<100)isvalidbecausethevariableintTotalisanIntegerdatatypewhichcanbecomparedtothe

valueintothetextbox,UserEntry.SinceVBtreatstheTextpropertyofatextboxasText,VBwouldmakethepossiblecomparison"99"<100

whichmaycausearun­timeerror.

ThereisanabbreviatedASCIIchartonp.129ofourtextbook.Tocompare'*'with'~',youneedtolookupthenumericalASCIIcodesforthe

twocharacterswhichare42and126,respectively.Thereforethecondition('*'<'~')evaluatestoTRUE.Notethatsinglequotesareplaced

aroundanysinglecharacter,whichiscommonlycalledacharacterliteral.

NotethatconditionscanbesimplifiedinVBwhere

IfblnFinished=1Then

isequivalentto IfblnFinishedThen

Objective#5:CombineconditionsusingAndandOr.

Sometimesyouneedtousecompoundconditionstorepresentthenecessarylogicinanalgorithm.Compoundconditionsconsistofseveral Booleanexpressions,whicharejoinedbythelogicaloperators,AndandOr.Thethreelogicaloperatorsthatyouarelikelytouseinconditions areOr,And,andNot.OftentheselogicaloperatorsarereferredtoastheBooleanOr,theBooleanAnd,andtheBooleanNotasopposedtothe words"or","and",and"not"asusedintheEnglishlanguage.

Examples: (X<100AndY<50)

(Total=4OrTotal=5)

(Not(Total=4)OrTotal=5)

Theorderofoperationsamongthelogicaloperatorsis: Not,And,Or

butyoucanuseparenthesestooverridethisorder.

Objective#6:TesttheValuepropertyofoptionbuttonsandcheckboxes.

1/29/2017

VisualBasicCh.4Notes,page1

TheValuepropertyofacheckboxcanbeusedtodetermineiftheuserhasplacedacheckmarkinthatcheckbox.TheValuepropertywill

eitherbeChecked(whichequalsthevalueof1),Unchecked(whichequalsthevalueof0),orGrayed(whichequalsthevalueof2).

Bysimplyusingcodelike: IfchkColor.Value=CheckedThen checkmarked.

youcanperformanactionifindeedthecheckbox,chkColoris

TheValuepropertyofanoptionbuttoncanbeusedtodetermineiftheuserhasselectedthatparticularoption.Thevaluepropertyforan

optionbuttoniseitherTrueorFalse.

TheIfstatement IfoptYear.Value=TrueThen

canbeusedtoperformanactioniftheoptionbuttonoptYearisselected.

SincetheValuepropertiesofbothcheckboxesandoptionbuttonsarethedefaultpropertiesofthosecontrols,theIfstatementsgivenabove

couldbeshortenedto IfchkColor=CheckedThen

and IfoptYear=TrueThen

Objective#7:Performvalidationonnumericfields.

Youshouldcheckusers'inputintotextboxestomakesurethatthedatatheyenterisvalid.Ifauserentersanumberthatisnotintherangethat

youareexpecting,itcouldcauselogicorrun­timeerrors.Makingsurethattheuserentersvaliddataiscalledvalidation(orerror­checking).

SinceweoftenusetextboxestoobtainuserinputandtheTextpropertyofatextboxisconsideredastext(astring)byVB,itisawiseideato

validatethisdatawhenyouexpecttheusertoenternumericdata.

Ifyousimplywishtomakesurethatauser'sentryisavalidnumber,youcanusetheIsNumericfunction.IsNumericreturnsatrueifits argumentisavalidnumericalvalueandcanbeusedinanarithmeticexpression.Forexample, IsNumeric("13")=True whereas

IsNumeric("375­4031")=False

Youcanvalidateusers'inputtednumbertomakesurethatitfallswithinacertainrangebyusingrelationaloperatorsasin

If(Val(txtUserInputA)>10)And(Val(txtUserInputB)<=100)Then

Objective#8:Calleventproceduresfromotherprocedures.

Youcancallaneventprocedurefromwithinanothereventproceduresimplybytypingthenameoftheeventprocedureonalineofcode.

Objective#9:Createmessageboxestodisplayerrorconditions.

AmessageboxisaspecialVBwindowthatcanbedisplayedtosendanimportantmessagetotheuserthatheorshecannoteasilyignore.It

includesamessage(astring),anoptionaliconnexttothatstring,atitlebarcaptionatthetopofthewindow,andacommandbutton(s)that

requirestheusertoclicktomakethewindowdisappear.

ThegeneralformoftheMsgBoxstatementwhichproducesamessageboxis

Buttons/icon][,"Captionofthetitlebar"]

MsgBox"Messagestringdirectedtotheuser"[,

1/29/2017

VisualBasicCh.4Notes,page1

TheButtons/iconareVBconstantsthatyoucanusetomakegettheattentionoftheuser.AnexampleistheOKbuttonwhichusesthe

VBconstantvbOKOnly.

TheCaptionofthetitlebaristhewordorphraseyouwishtoappearinthetitlebaratthetopofthewindow.

Objective#10:Applythemessageboxconstants.

SeetheHands­Onprogrammingexampleinthechaptertousethemessageboxconstantswhicharelistedonp.140.

Objective#11:Debugprojectsusingbreakpoints,steppingprogramexecution,anddisplayingintermediateresults.

Followthe"DebuggingStep­by­StepTutorial"onpp.155+topracticedebuggingprograms.