Topik3.4Subprocedures Function
Topik3.4Subprocedures Function
F5227 VISUALBASIC.NETPROGRAMMING
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.
Procedures
Procedure aunitofcodethatexecuteswhencalledfrom anotherplace. Notanewface
Subproceduredefinition abuttonclickevent PrivateSub btnDisplay_Click(ByValsenderAsSystem.Object, ByValeAsSystem.EventArgs)HandlesbtnDisplay.Click
Procedures
Aproceduremusthaveanamefollowingby().
E.g. lstOutput.Items.Clear() lstOutput.Items.Add(******) CDbl(txtInputOne.Text)
.
EndSub Or: lstOutput.Items.Clear() subprocedurecall
Procedures
Without Using Procedures: Button click event: Create variables Take two user inputs, and store them to variables Perform the addition and display the result Perform the subtraction and display the result Perform the multiplication and display the result Perform the division and display the result (handle divide by 0 situation here) End of event Using Procedures: Create variables Button click event: Take two user inputs, and store them to variables Add() Subtract() Multiply() Divide() End of event Define Add(): Perform the addition and display the result Define Subtract(): Perform the subtraction and display the result Define Divide() Perform the division and display the result(handle divide by 0 situation here)
Cont.
TherearetwotypesofproceduresinVisual Basic.NET: Subprocedures Functionsprocedures i d
3/29/2012
Subprocedure
ASubprocedureisablockofcodethatis executedinresponsetoaneventthatyoucan callwithparameterswhichdoesntreturna value. value BybreakingthecodeinamoduleintoSub procedures,itbecomesmucheasiertofindor modifythecodeinyourapplication.
Cont.
Subproceduresare methods whichdonot returnavalue. EachtimewhentheSubprocedureiscalled thestatementswithinitareexecuteduntilthe matchingEndSubisencountered. SubMain(), thestartingpointoftheprogram itselfisasubprocedure.
SubProcedures
Sub procedure executeablockofcodeswhencalled DefineaSubprocedure:
Private Sub name() actionshere EndSub End Sub
SubProcedures
E.g.auserdefinedSubdefinitionandSubcall
PrivateSubbtnCompute_Click(ByVal senderAsSystem.Object,ByVal eAs System.EventArgs)HandlesbtnDisplay.Click intFirst =CInt(nudFirst.Value) intSecond =CInt(nudSecond.Value) Add()Subcall.TheprogramwilllookforaSubdefinitionwiththesame
nametodecidewhattodo t d id h t t d
SubProcedures
SubMain(bytradition)isasubprocedurethat isthefirstsubtobeexecuted,itiswherethe programstarts. Whentheapplicationstartsexecution, control istransferredtoMainSubprocedure automaticallywhichiscalledbydefault. Subprocedurescanhavedifferentformal parameters,andtheseformalparameterscan beseparatedwithlinecontinuationsfora morereadablesourcetext. Itcantakearguments,suchasconstants, variables,orexpressions,thatarepassedtoit bythecallingcode.
3/29/2012
Syntax
[Private|Public][Static]Subprocedurename (arguments)
CallingaSubProcedure
Onceyouhaveaprocedure,whetheryou createditoritispartofVBasic,youcanuseit. Usingaprocedureisalsoreferredtoascalling it. it Beforecallingaprocedure,youshouldfirst locatethesectionofcodeinwhichyouwant touseit.
statements
EndSub Example: PrivateSubMain() Console.WriteLine("Hellothere!") Console.WriteLine("PressEntertocontinue...") Console.ReadLine() EndSub
ExampleCodeProgram1
Tocallasimpleprocedure,typeitsname followedbyparenthesesinthesectionwhere youwanttouse. ModuleModule1
SubMain() System.Console.WriteLine("HellofromVisualBasic") EndSub End Sub
EndModule
CodeProgram2
ModuleModule1
SubMain() DisplayMessage() EndSub End Sub SubDisplayMessage() System.Console.WriteLine("HellofromVisual Basic") EndSub
FunctionProcedures
Functionisamethodwhichreturnsavalue. Functionsareusedtoevaluatedata,make calculationsortotransformdata. DeclaringaFunctionissimilartodeclaringa g g Subprocedure. FunctionsaredeclaredwiththeFunction keyword
EndModule
3/29/2012
Example
ModuleModule1
SubMain() EndSub FunctionAddem(ByValint1AsInteger,ByValint2As Function Addem(ByVal int1 As Integer ByVal int2 As Integer)AsLong Returnint1+int2 EndFunction
Explaination
Returnavaluefromafunctionwiththe Return statement Theprogramreturningthesumofthetwo argumentspassedtous. arguments passed to us Whencallafunctionbyusingitsnameandan argumentlistenclosedinparentheses,that nameisreplacedbythevaluereturnedbythe function
EndModule
Example
ModuleModule1
SubMain() DimintValueAsInteger=2 System.Console.WriteLine("{0}+{1}={2}",_intValue, intValue,Addem(intValue,intValue)) i tV l Add (i tV l i tV l )) EndSub FunctionAddem(ByValint1AsInteger,ByValint2AsInteger) AsLong Returnint1+int2 EndFunction
PassingParameters
Parameterscanbepassedtoaprocedurein oneoftwoways. Eitherbyreference(ByRef)orbyvalue(ByVal). Whenyouusethebyreference method, y y f , changesmadetoparameters'valuesinasub procedureareknownwhencontrolreturns backtothecallingprocedure
EndModule
ByVal
ByRefisthedefaultmethodofparameter passinginVB6andpriorversionswhenthe parameter'sdatatypeisanintrinsiconesuch asInteger,Long,Boolean,String,etc Thensecondmethodispassbyvalue(ByVal). Thisisthedefaultforallnonintrinsicdata types. Whenpassedbyvalue,thecallingprocedure h db l h lli d knowsnothingaboutchangesmadetothe parameter'svalueinasubprocedure.
3/29/2012
Accessibility
TheaccessibilitycanbePublic,Protected, Friend,ProtectedFriend,orPrivate. YoucandefineSub proceduresinmodules, classes,andstructures. classes and structures TheyarePublic bydefault,whichmeansyou cancallthemfromanywhereinyour application.
Syntax
[accessibility]Subsubname[(argumentlist)] 'StatementsoftheSubproceduregohere. EndSub Example:
PrivateSubDisplayMessage(ByValstrTextAsString)
ArgumentDeclaration
Youdeclareeachargumentforaprocedure thesamewayyoudeclareavariable, specifyingtheargumentnameanddatatype. You can also specify the passing mechanism Youcanalsospecifythepassingmechanism, andwhethertheargumentisoptional.
ArgumentSyntax
[Optional][ByVal|ByRef][ParamArray]argumentname Asdatatype Iftheargumentisoptional,youmustalsosupplyadefaultvalueinits declaration,asfollows: CopyOptional[ByVal|ByRef]argumentnameAsdatatype=defaultvalue
3/29/2012
LocalVariablesandGlobalVariables
LocalVariables:
Purpose:foraspecificproceduretouse Scope:onlyusedinsidethatprocedure Where:createdinsideaprocedure
LocalVariablesandGlobalVariables
Local Variables: Add Button click event procedure:
3 local variables, only used inside this procedure
Global Variables:
Create 2 global variables outside of any procedure, can be used anywhere
GlobalVariables:
Purpose:avariablesharedbydifferent procedures Scope:theform,alsocalledformvariables,can beusedanywhereinthesameform Where:createdatthebeginningoftheClass, 31 outsideofanyprocedures
Create variables 1, 2, and 3 Take user input and store in variable 1 and 2 Add variable 1 to variable 2 and store the result to variable 3 End of event procedure
Create variables 1, 2 Add Button click event procedure: Add() End of event procedure Procedure Add():
1 local variable, only used 1 variable inside this procedure
Create variable 3
use global variable 1 and 2
Add variable 1 to variable 2 and store the result to variable 3 End of Add procedure
Conclusion
ASub procedureisaseriesofVisualBasic statementsenclosedbytheSub andEndSub statements. Eachtimetheprocedureiscalled,its statementsareexecuted,startingwiththefirst executablestatementaftertheSub statement andendingwiththefirstEndSub,ExitSub,or Returnstatementencountered.