3/14/2012
F5227VISUALBASIC.NET PROGRAMMING
CourseLearningOutcome(CLO)
Upon completion of this course, students should be able to : 1. Create a simpe VB.NET based application based on the Windows Application template. 2. Describe on essential terminology including memory, data types and graphical user interface interface. 3. Apply object oriented programming techniques to create classes, add methods and add properties. 4. create a simple VB.NET based Web forms application that uses an XML Web Service and manipulate data in database by using Microsoft ADO.NET.
Topic3.0 CommonProgrammingTechniques 3.2 ControlStructures
Introduction
VB.NethasstatementssuchasIf..Then..else andSelect.Case,whichhelpyouto conditionallyexecuteprogram.
If/Then
TheIf.Then.ElseEndifStatement TheIf/Then selectionstructureperformsan indicatedactiononlywhenthecondition evaluatestotrue;otherwise,theactionis evaluates to true; otherwise the action is skipped.
IfElse
Considerastudentmarksandgrade evaluation.ForMarksabove75thegradeisA andforbelow75isB.Inthissituationwhen youneedtoexecutesomecodebasedon you need to execute some code based on somecondition,youcanmakeuseof, Ifthenelseendif.
If(Condition) Then Statementsexecutedifconditionistrue Else Statementsexecutedifconditionisfalse EndIf WecanalsohaveElseIfblockinIfElsestatements
3/14/2012
NestingIFThenConstructs
Ifcondition Then
Ifcondition2Then Executablestatementswhenthecondition2isTRUE Else ExecutableStatements Endif
Else Executablestatements EndIf
ORusingElseifforAdvancedDecision making; IfconditionThen Executablestatements bl ElseIfconditionThen Executablestatements EndIf
Remember
Oneimportantthingtokeepinmindwhen nestingIFThenconstructsisthatyoumust havecorrespondingEndIfstatementfor everyIF..Thenstatement,unlesstheIfthen every IF Then statement unless the If then statementexecutesonlyonestatementand thatstatementappearsonthesamelineas IfThen
TheSelectCaseStatement(
TheSelectCase Statementissimilarto IfElseEndif. Theonlydifferencebetween twoisthatIfandelseifcanevaluatedifferent i h f d l if l diff expressionsineachstatement,butthe Selectstatementcanevaluateonlyone expression.
Note:
TheSelectusestheresultofanexpressionto executedifferentsetofstatements.
Select Case [expression] Case [expression list] Executable statements. Case Else Executable statements. Exit Select - to exit from the select End Select
CaseElseisusedtodefinethecodethat executesonlywhentheexpressiondoesnt evaluatetoanyofthevaluesinCase Statements. Statements UseofCaseElseisoptional
3/14/2012
Example
SelectCasevar Case1 stmt1 //executedifvar=1 Case2 Case 2 stmt2 //executedifvar=2 CaseElse stmt3 //executedifvarisotherthan1and2 EndSelect
Example
SelectCaseintmarks CaseIs>35 Executablestatements CaseIs>50 Executablestatements CaseIs>65 Executablestatements CaseIs>75 Executablestatements CaseElse Executablestatements EndSelect
EvaluatingMorethanonepossible ValueinaCaseStatement
SelectCasehelpsyoutousesomemore advancedexpressioncomparisons.Like,you canspecifymultiplecomparisonsinaSingle Casestatementbyjustusingcomma. Case statement by just using comma
Example
SelectCasestrColor CaseIs=Red,Blue,Magenta ColorisaDarkShade CaseIs=Cream,white ColorisaCoolShade EndSelect
Example
Anothercomparisonexpressionusedis keywordTo,VisualBasic.NETevaluatesthe expressionandfindsoutwhetheritisinthe rangementionedandifyestheStatementis range mentioned and if yes the Statement is executed. PleasenotethatwhenusingTo,youcant includeIs=asyoucanwiththe simpleexpression SelectCaseintmarks Case1to35 Executablestatements Case36to50 ExecutableStatements EndSelect
3/14/2012
Introduction
LoopingisaveryusefulfeatureofVisualBasic becauseitmakesrepetitiveworkseasier. Thereareseveraltypeofloopingstructurein VisualBasic.NETLoopallowsyoutorepeatan actionforanumberoftimesoruntila specifiedconditionismatched
Looping
VB.Netprovidesyouwithvariouslooping statements,suchasDoLoop,While. EndWhile,andForNext.
ForNext
TheForNextStatementsareusedrepeata setofstatementsforspecificnumberof times. S Syntax
Forcounter=<startvalue>to<endvalue>[StepValue] ExecutableStatements ExitFor Next[counter]
Explaination
Counterisanynumericvalue. Startvalueistheinitialvalueofthecounter. Endvalueis StepValueisthevaluebywhichthecounteris incremented.Itcanbepositiveornegative. Thedefaultvalueis1.
Example
ExitForisusedtoexittheForNextloopatany time.WhenExitforisencountered ,theexecutionjumpstothestatementfollowingNext Next is the statement the marks the end of the For NextisthestatementthemarkstheendoftheFor statement. AssoonastheprogramencounterstheNext statement,thestepvalueisaddedtothecounter andthenextiterationofthelooptakesplace.
DimintctrasInteger Forintctr=1to100 Debug.WriteLine(intctr) Nextintctr
ThisroutinestartsaloopwithaForstatementafteravariableintctris declared. Thisloopinitializesintctrto1andthenprints1through100totheoutput window. Itprintsinstepsof1asStephasbeenomittedhere,sothedefaultis1
3/14/2012
STEPinFor....Loop.
Dimj=1 Fori=2To20Step2
Me.lbtables.Text= Me.lbtables.Text&"2X"& j.ToString&"="&i.ToString j T St i & " " & i T St i &vbCrLf
ForEachNextStatement
TheForEachNextStatementisusedto repeatasetofstatementsforeachelement inanarrayorcollection. The For Each Next statement is executed if TheForEachNextstatementisexecutedif thereisatleastoneiteminanarrayof collection. TheLooprepeatsofeachelementinanarray orcollection.
j=j+1 Next
Output: 2X1=2 .. .. .. .. 2 X 10 = 20
Syntax
ThesyntaxfortheForEachNextstatement asfollows: ForEachComponentInSet Executablestatements bl Next
Componentisthevariableusedtorefertotheelementsofan arrayoracollection. Setreferstoanarrayoranycollectionobject
Dimweeks()AsString={"Monday","Tuesday", "Wednesday","Thursday",_ "Friday","Saturday","Sunday"} DimeachdayAsString i hd S i ForEacheachdayInweeks MsgBox(eachday) Next
WhileEndStatement
TheWhileEndStatementisusedtorepeat setofexecutablestatementsaslongasthe conditionistrue.
Syntax
ThesyntaxfortheWhileEndstatementisas follows: WhileCondition ExecutableStatements bl S EndWhile
Inthisiftheconditionissatisfiedthenthestatementsare executed.ElseitwillnotentertheWhileconditionatall.
3/14/2012
Do...LoopStatement
TheDoLoopStatementissimilarto WhileEnd.Twotypesofformattingtheloop. a)DoWhile/UntilConditionExecutable StatementsLoop Statements Loop b)DoExecutableStatementsLoopWhile/Until Condition
Difference
TheDifferenceis: a)Theloopwillbeexecutediftheconditionis satisfied,butin b)TheLoopwillbeexecutedatleastonceeven b) h ill b d l iftheconditiondoesnotsatisfy.
ForLoop
DoWhileExpression [Statements] Loop DoUntilExpression [Statements] Loop AForloopiteratesacertainnumberoftimes, thevalueofthecountervariablechanging eachiteration. Aforloophasthefollowingsyntax:
Forcounter=starttoend[stepincrement] statements Next
InexecutingaFOR..NEXTloop,VisualBasic completedthefollowingstep
Setscounterequaltostart. Teststoseeifcounterisgreaterthanend,soitexit theloopifcounterislessthanend.ifitis,itexits theloop. Executesthestatementinblock. Repeatsthestatements
ExampleshowstheFORloop:
DimiAsInteger Fori=1To10 Console.WriteLine(i) Next
3/14/2012
DoUntilLoop
ADo...LoopUntilloopisaloopthatrunsuntil theloop'sconditionistrue,thecondition beingcheckedaftereachiterationoftheloop Syntax: Do statements LoopUntilcondition ExampleshowstheDO..Untilloop:
'DO..UNTILloopinVB.NET DoUntili>10 Console.WriteLine(i) i=i+1 Loop
Do..LoopWhileLoop
ADo...LoopWhilelooprunsuntiltheloop's conditionbecomesfalse.Itsconditionis checkedaftereachiterationoftheloop. Syntax Do statements LoopWhilecondition ExampleShowstheDOwhileLoop: 'DO..LOOPWHILEinVB.NET Do Console.WriteLine(i) Console WriteLine(i) i=i+1 LoopWhilei<10
WhileEndWhileLoop
TheWhile...End Whileloopexecutesablockof statementaslongasconditionistrue. TheWhileloophasthefollowingsyntax: Whilecondition statementblock EndWhile ExampleshowstheWhile...EndWhileloop: 'While...EndWhileloopinVB.NET Whilei<10 Console.WriteLine(i) Console WriteLine(i) i=i+1 EndWhile
3/14/2012
ForLoop
For<<var>>=startToendStep<<val>> Statements Next Eg ForI=1To10Step2 Console.WriteLine(I) Next Herethevaluesprintedwillbe1,3,5,7,9
DoWhileLoop
1. DoWhile(a<>0) Console.Writeline(a) a=a 1 Loop 2.Do Console.Writeline(a) a=a 1 LoopWhile(a<>0)
DoUntilLoop
1. DoUntil(a=0) Console.Writeline(a) a=a 1 Loop 2.Do Console.Writeline(a) a=a 1 LoopUntil(a=0)