Microsoft Visual Basic Reloaded Chapter Eight Sub and
Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures
Overview ■ ■ ■ ■ ■ Classes and Procedures Function and Sub Procedures Passing Variables by Value and by Reference Using Function and Sub Procedures in the Wage Calculator Application Optional Parameters The Shipping Time Application Date Variables Date. Timer. Picker Control Timer Control 2009 Pearson Education, Inc. All rights reserved.
Introduction ■ The best way to develop and maintain a large application is to construct it from smaller, more manageable pieces. This technique is known as divide and conquer (also called componentization). ■ Manageable pieces include program components —known as procedures. 2009 Pearson Education, Inc. All rights reserved.
Classes and Procedures ■ The key to creating large applications is to break them into smaller pieces. ■ In object-oriented programming, these pieces consist primarily of classes, which can be further broken down into methods. ■ Programmers combine programmer-defined classes and methods with preexisting code in the. NET Framework Class Library. Using preexisting code saves time, effort and money. The concept of reusing code increases efficiency for application developers. 2009 Pearson Education, Inc. All rights reserved.
Classes and Procedures (Cont. ) ■ Several pre-existing Visual Basic methods. 2009 Pearson Education, Inc. All rights reserved.
Functions and Sub Procedures ■ Procedure: a block of program code that performs a specific task ■ Function procedure: returns a value after performing its task ■ Sub procedure: does not return a value • Event procedure: Sub procedure that is associated with a specific object and event Automatically processed when the associated event occurs • Independent Sub procedure: Collection of code that can be invoked from one or more places in an application Not associated with an event Processed only when called (invoked) 2009 Pearson Education, Inc. All rights reserved.
2009 Pearson Education, Inc. All rights reserved.
Calling a Sub Procedure 2009 Pearson Education, Inc. All rights reserved.
Calling a Sub Procedure Figure 8 -2: Lanza Trinkets application 9 2009 Pearson Education, Inc. All rights reserved.
Including Parameters in a Sub Procedure ■ Parameter: stores data that is passed to the procedure when the procedure is invoked ■ When calling a procedure with parameters, you must pass: The same number of arguments The same type of arguments The arguments in the same order as declared in the procedure ■ Can pass a variable, named constant, literal constant, or keyword as parameter 2009 Pearson Education, Inc. All rights reserved.
Passing Variables ■ Each variable has a value and a unique memory address ■ Variable can be passed to a procedure in two ways: By value: you pass the variable’s value By reference: you pass the variable’s address ■ Passing by value: the procedure receives only the value and cannot change the actual variable’s value ■ Passing by reference: the procedure receives the address and can make changes to the variable’s value 2009 Pearson Education, Inc. All rights reserved.
Passing Variables by Value ■ Use the keyword By. Val before the parameter in the procedure declaration ■ By. Val is the default method of passing variables ■ Procedure cannot change the actual variable’s value Figure 8 -5: Sample run of the Pet Information application 2009 Pearson Education, Inc. All rights reserved.
Figure 8 -6: Partial code for the Pet Information application 2009 Pearson Education, Inc. All rights reserved.
Passing Variables by Reference ■ Use the keyword By. Ref before the parameter in the procedure declaration ■ Procedure receives the address of the variable and is able to change the variable’s value 2009 Pearson Education, Inc. All rights reserved.
Figure 8 -8: Calc. Gross. Pay procedure and calc. Button_click event procedure 2009 Pearson Education, Inc. All rights reserved.
Function Procedures ■ Function procedure (or Function): Block of code that performs a specific task Returns a value after completing its task ■ Visual Basic contains many built-in functions ■ You can create your own functions with or without parameters ■ A function is invoked by including its name with any arguments in a statement 2009 Pearson Education, Inc. All rights reserved.
Function Procedures (cont'd. ) ■ Function procedure header: As datatype clause indicates the type of the return value ■ Function procedure footer statement: End Function ■ Return keyword: Sets the value to be returned by the function Ends the function 2009 Pearson Education, Inc. All rights reserved.
2009 Pearson Education, Inc. All rights reserved.
Function Procedures (cont'd. ) 2009 Pearson Education, Inc. All rights reserved.
The Circle Area Calculator Application Figure 8 -20: Partial code for the Circle Area Calculator application 2009 Pearson Education, Inc. All rights reserved.
Creating a Function Procedure That Returns the Largest of Three Numbers Text. Boxes used to input three values Figure 13. 11 | Maximum application in Design view. 2009 Pearson Education, Inc. All rights reserved.
Creating a Function Procedure That Returns the Largest of Three Numbers (Cont. ) ■ Double click the Maximum Button to create an event handler. ■ Note that Maximum has been underlined in blue, because Function procedure Maximum has not yet been defined (Fig. 13. 12). Calling a procedure that has not yet been defined is an error Figure 13. 12 | Invoking Function procedure Maximum. 2009 Pearson Education, Inc. All rights reserved.
Creating a Function Procedure That Returns the Largest of Three Numbers (Cont. ) ■ Create the Function procedure Maximum ■ The maximum is determined by using the Max method of . NET Framework Class Library class Math (Fig. 13. 14). ■ The Return statement terminates execution of the procedure and returns the result of final. Maximum. Calling Math. Max to determine the maximum of two values Figure 13. 14 | Math. Max returns the larger of its two arguments. 2009 Pearson Education, Inc. All rights reserved.
Introducing the Enhanced Wage Calculator Application ■A payroll company calculates the gross earnings per week of employees. Employees’ weekly salaries are based on the number of hours they worked and their hourly wages. Create an application that accepts this information and calculates each employee’s total earnings. The application assumes a standard work week of 40 hours. The wages for 40 or fewer hours are calculated by multiplying the employee’s hourly wage by the number of hours worked. Any time worked over 40 hours in a week is considered “overtime” and earns time and a half. Salary for time and a half is calculated by multiplying the employee’s hourly wage by 1. 5 and multiplying the result of that calculation by the number of overtime hours worked. The total overtime earned is added to the user’s gross earnings for the regular 40 hours of work to calculate the total earnings for that week. 2009 Pearson Education, Inc. All rights reserved.
The Enhanced Wage Calculator Application Figure 13. 1 | Wage Calculator running. ■ Click the Calculate Button. The result ($475. 00) is displayed in the Gross earnings: Label. 2009 Pearson Education, Inc. All rights reserved.
Creating a Sub Procedure within the Wage Calculator Application ■ Double click the Calculate Button to generate an event handler (Fig. 13. 16). Call to Display. Pay Figure 13. 16 | calculate. Button_Click calls Display. Pay. 2009 Pearson Education, Inc. All rights reserved.
Creating a Sub Procedure within the Wage Calculator Application (Cont. ) Display. Pay calculates and displays the user’s gross earnings Figure 13. 17 | Sub procedure Display. Pay definition. 2009 Pearson Education, Inc. All rights reserved.
Creating a Function Procedure within the Wage Calculator Application ■ Note that the return type of the procedure is Boolean (Fig. 13. 18)—the value returned by the procedure must be a Boolean. Check. Overtime determines if the user has worked overtime Figure 13. 18 | Function procedure Check. Over. Time definition. 2009 Pearson Education, Inc. All rights reserved.
Creating a Function Procedure within the Wage Calculator Application (Cont. ) ■ In Sub procedure Display. Pay, replace the statement on line 26 (Fig. 13. 19). Call to procedure Check. Overtime Figure 13. 19 | Display. Pay calls Function procedure Check. Overtime. 2009 Pearson Education, Inc. All rights reserved.
(1 of 3 ) Call to Sub procedure that calculates and displays wages 2009 Pearson Education, Inc. All rights reserved.
(2 of 3 ) Sub procedure header specifies parameter names and types Call to Function procedure that determines if user has worked overtime 2009 Pearson Education, Inc. All rights reserved.
(3 of 3 ) End Sub keywords indicate the end of Sub procedure definition Function procedure header specifies parameter names and types as well as a return type End Function keywords indicate the end of Function procedure definition 2009 Pearson Education, Inc. All rights reserved.
Optional Parameters ■ When a procedure is invoked repeatedly with the same argument value, you can specify that such a parameter is an Optional parameter. ■ When the argument for an Optional parameter is omitted, the compiler rewrites the procedure call, inserting the default value. ■ There are three rules for using Optional parameters: Each Optional parameter must have a default value. The default value must be a constant expression. All parameters after an Optional parameter must also be Optional parameters. 2009 Pearson Education, Inc. All rights reserved.
Optional Parameters (Cont. ) ■ Consider the Function Box. Volume: Function Box. Volume( Optional By. Val length As Integer = 1, _ Optional By. Val width As Integer = 1, _ Optional By. Val height As Integer = 1 ) As Integer Return length * width * height End Function ' Box. Volume ■ Each parameter has a default value specified with an = and a literal value (1). 2009 Pearson Education, Inc. All rights reserved.
Optional Parameters (Cont. ) ■ You can now invoke Function Box. Volume several different ways: Box. Volume() ' returns 1; default values used for length, width, height Box. Volume(10) ' returns 10; default values used for width, height Box. Volume(10, 20) ' returns 200; default value used for height Box. Volume(10, 20, 30) ' returns 6000; no default values used Box. Volume(, 20, 30) ' returns 600; default value used for length Box. Volume(10, , 30) ' returns 300; default value used for width ■ Comma placeholders are used when an omitted argument is not the last argument in the call. 2009 Pearson Education, Inc. All rights reserved.
Associating a Procedure with Different Objects and Events ■ Handles keyword: Appears in event procedure header Indicates the object and event associated with the procedure Controls when the procedure is invoked ■ By default, the event procedure name matches the name of the associated object and event 2009 Pearson Education, Inc. All rights reserved.
Figure 8 -15: Some of the Gadis Antiques application’s code from Figure 8 -4 2009 Pearson Education, Inc. All rights reserved.
Associating a Procedure with Different Objects and Events (cont'd. ) ■ Event procedure: Name of event procedure can be changed Can be associated with more than one object and event as long as each event has the same parameters ■ Add the additional object/events to the Handles clause ■ Sender parameter: contains the memory address of the object that raised the event ■ e parameter: contains additional information about the object that raised the event 2009 Pearson Education, Inc. All rights reserved.
Associating a Procedure with Different Objects and Events (cont'd. ) Figure 8 -16: Clear. Labels procedure 2009 Pearson Education, Inc. All rights reserved.
Shipping Time Application ■A seafood distributor has asked you to create an application that calculates the delivery time for fresh seafood shipped from Portland, Maine, to its distribution center in Las Vegas, Nevada. The distributor has arrangements with local airlines to guarantee that seafood ships on flights that leave either at noon or at midnight. However, the airport requires the distributor to drop off the seafood at the airport at least one hour before each flight. When the distributor specifies the drop-off time, the application should display the delivery time in Las Vegas. This application should take into account the three-hour time difference and the six-hour flight time between the two cities. The application should allow the user to select drop-off times within the current day. The application should also include a running clock that displays the current time. 2009 Pearson Education, Inc. All rights reserved.
Test-Driving the Shipping Time Application ■ The default drop-off time (Fig. 14. 1) is set to your computer’s current time when you execute the application. ■ The time displayed in the Current time is: Label updates to the current time once each second. Date. Time. Picker with up and down arrows Group. Boxes Figure 14. 1 | Shipping Time application. 2009 Pearson Education, Inc. All rights reserved.
Introducing the Shipping Time Application: Design Elements When the Form loads: Set range of possible drop-off times to any time in the current day Call sub procedure Display. Delivery. Time to determine and display the shipment’s delivery time When the user changes the drop-off time: Call sub procedure Display. Delivery. Time to determine and display the shipment’s delivery time After one second has elapsed: Update and display the current time When the Display. Delivery. Time procedure gets called: Call function Departure. Time to determine the time the shipment’s flight departs 2009 Pearson Education, Inc. All rights reserved.
Introducing the Shipping Time Application: Design Elements (Cont. ) Add three hours to determine the delivery time (takes into account 6 hours for time of flight minus 3 hours for the time difference) Display the delivery time When the Departure. Time procedure gets called: Select correct Case based on the hour the shipment was dropped off Case where the drop-off hour is between the values 0 and 10 Delivery set to depart on noon flight of current day Case where the drop off hour is 23 Delivery set to depart on noon flight of next day Case where none of the preceding Cases match Delivery set to depart on midnight flight of current day 2009 Pearson Education, Inc. All rights reserved.
Date Variables ■ The primitive type Date simplifies manipulation, storage and display of date (and time) information. ■ Date corresponds to the Date. Time type in the. NET Framework Class Library. ■ You use the New keyword when creating a Date value. In the code, the statement Date constructor Dim delivery As Date = New Date(2003, 1, 1, 0, 0, 0) Date variable ■ The New keyword calls the Date’s constructor. A constructor is a procedure that initializes an object when it’s created. 2009 Pearson Education, Inc. All rights reserved.
Date Variables (Cont. ) ■ Figure 14. 2 explains the values used in Date’s constructor. Figure 14. 2 | Date constructor arguments. 2009 Pearson Education, Inc. All rights reserved.
Date Variables (Cont. ) ■ Method overloading allows you to create multiple methods with the same name but different signatures. This means different numbers and types of parameters, or with parameters ordered differently (by type). When an overloaded method is called, the compiler selects the proper method by examining the number, types and order (by type) of the arguments. 2009 Pearson Education, Inc. All rights reserved.
Date Variables (Cont. ) ■ After assigning a value to a Date variable, you can access its properties using the member-access (dot) operator, as follows: Dim Dim Dim year = delivery. Year ' retrieves Date delivery's year month = delivery. Month ' retrieves Date delivery's month day = delivery. Day ' retrieves Date delivery's day hour = delivery. Hour ' retrieves Date delivery's hour minute = delivery. Minute ' retrieves Date delivery's minute second = delivery. Second ' retrieves Date delivery's second 2009 Pearson Education, Inc. All rights reserved.
Date Variables (Cont. ) ■ Instead of using arithmetic operators to add or subtract values in Date variables, you must call the correct method, using the member-access operator (Fig. 14. 4). Figure 14. 4 | Date methods that perform various 2009 Pearson Education, Inc. All rights reserved.
Creating and Customizing the Date. Time. Picker ■ To add a Date. Time. Picker to your application, drag a Date. Time. Picker control from the Toolbox and drop it to the right of the Enter drop-off time: Label to place the Date. Time. Picker in the Group. Box (Fig. 14. 8). 2009 Pearson Education, Inc. All rights reserved.
Creating and Customizing the Date. Time. Picker (Cont. ) ■ When the Date. Time. Picker’s Format property is set to Custom, it uses the format that you specify in the Custom. Format property. ■ Set the value of the Custom. Format property to hh: mm tt. The Custom. Format property is case sensitive. The Format property eliminates the problem of a user’s entering a letter or symbol when the application expects a number. The Date. Time. Picker also prevents the user from specifying an invalid time, such as 32: 15. 2009 Pearson Education, Inc. All rights reserved.
Creating a Timer Control ■ A Timer control is an object that can run code every millisecond by generating a Tick event. By default, the Timer runs code every 100 milliseconds. Each time the Tick event occurs, its event handler executes. ■ Add a Timer to the Form by clicking the Timer control in the Components tab of the Toolbox. 2009 Pearson Education, Inc. All rights reserved.
Creating a Timer Control (Cont. ) ■ Rename the Timer to clock. Timer (Fig. 14. 10). ■ Set the Timer’s Enabled property to True, then set its Interval property to 1000, which specifies the number of milliseconds between Tick events. Timer control Component tray Figure 14. 10 | Timer control is displayed in the component tray. 2009 Pearson Education, Inc. All rights reserved.
Coding the Shipping Time Application’s Clock ■ Double click the Timer control in the component tray to generate the empty event handler for the Tick event (Fig. 14. 11). Printing the current time Figure 14. 11 | Inserting code for a Tick event. ■ The event handler formats information to match the format you specify, "{hh: mm: ss tt}". 2009 Pearson Education, Inc. All rights reserved.
Using Code to Display a Delivery Time ■ To run code when the application first opens, create an event handler for the Form’s Load event (Fig. 14. 12). Double click an empty area in the Form or the title bar to generate the Load event handler and enter Code view. Be careful not to double click a control on the Form; this generates the control’s event handler instead. Storing the current time in current. Time Figure 14. 12 | Storing the current time. 2009 Pearson Education, Inc. All rights reserved.
Using Code to Display a Delivery Time (Cont. ) ■ These lines (Fig. 14. 13) set the Min. Date and Max. Date properties for drop. Off. Date. Time. Picker. Figure 14. 13 | Setting the Min. Date and Max. Date properties. 2009 Pearson Education, Inc. All rights reserved.
Using Code to Display a Delivery Time (Cont. ) ■ Display. Delivery. Time is underlined in blue (Fig. 14) because the procedure has not yet been written. ■ The Display. Delivery. Time procedure calculates the delivery time in Las Vegas and displays the result in the Delivery time: Label. Displaying the delivery time Figure 14. 14 | Calling the Display. Delivery. Time procedure. 2009 Pearson Education, Inc. All rights reserved.
Coding the Value. Changed Event Handler ■ Double click the Date. Time. Picker control drop. Off. Date. Time. Picker to generate its Value. Changed event handler (Fig. 14. 15). Calculating and displaying the delivery time Figure 14. 15 | Inserting code in the Value. Changed event handler. 2009 Pearson Education, Inc. All rights reserved.
Coding the Display. Delivery. Time Procedure (Cont. ) Determining the departure time Adding the travel time Displaying the delivery time Figure 14. 16 | Display. Delivery. Time procedure. 2009 Pearson Education, Inc. All rights reserved.
Coding the Departure. Time Procedure ■ Line 51 (Fig. 14. 17) stores the current date in the Date variable current. Date. ■ Line 52 declares the Date variable depart. Time, the variable you use to store the Departure. Time Function procedure’s return value. Declaring variables Figure 14. 17 | Inserting procedure Departure. Time into the application. 2009 Pearson Education, Inc. All rights reserved.
Coding the Departure. Time Procedure (Cont. ) Using the hour value stored in the Date. Time. Picker to determine departure time Noon (the next day) departure time Midnight departure time Returning the departure time Figure 14. 18 | Determining the seafood shipment’s flight departure time. 2009 Pearson Education, Inc. All rights reserved.
(1 of 4 ) Event raised when the Timer raises a Tick event Displaying current time Event raised when the Form loads 2009 Pearson Education, Inc. All rights reserved.
(2 of 4 ) Setting the Date. Time. Picker’s minimum and maximum values Event raised when the user changes the value of the Date. Time. Picker 2009 Pearson Education, Inc. All rights reserved.
(3 of 4 ) Calculating and displaying the delivery time in Las Vegas 2009 Pearson Education, Inc. All rights reserved.
(4 of 4 ) Using a Select Case statement to determine departure time 2009 Pearson Education, Inc. All rights reserved.
- Slides: 64