microsoft visual basic: reloaded chapter eight sub and function procedures

64
Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

Post on 21-Dec-2015

218 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

Microsoft Visual Basic: Reloaded

Chapter EightSub and Function Procedures

Page 2: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

■ 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■ DateTimerPicker Control■ Timer Control

Overview

Page 3: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

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.

Page 4: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

Classes and Procedures

■ The key to creating large applications is tobreak 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 inthe .NET Framework Class Library.

Using preexisting code saves time, effort and money.

The concept of reusing code increases efficiency for application developers.

Page 5: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

Classes and Procedures (Cont.)

■ Several pre-existing Visual Basic methods.

Procedure Description Example

Val(x) Returns the numeric value of x Val("5") is 5 Val("5a8") is 5 Val("a5") is 0

String.Format (formatString, listOfArguments)

Returns a formatted String. The first parameter, formatString, specifies the formatting and listOfArguments specifies the values to format

String.Format("{0:C}", 1.23) is "$1.23"

Procedure Description Example

Math.Max(x, y) Returns the larger value of x and y Math.Max(2.3, 12.7) is 12.7

Math.Max(-2.3, -12.7) is -2.3

Math.Min(x, y) Returns the smaller value of x and y Math.Min(2.3, 12.7) is 2.3

Math.Min(-2.3, -12.7) is -12.7

Math.Sqrt(x) Returns the square root of x Math.Sqrt(9) is 3.0

Math.Sqrt(2) is 1.4142135623731

Pmt(x, y, z) Calculates loan payments where x specifies the interest rate, y specifies the number of payment periods and z specifies the principal value of the loan

Pmt(0.05, 12, -4000) is 451.301640083261

Page 6: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

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 applicationNot associated with an eventProcessed only when called (invoked)

Page 7: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

Page 8: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

Calling a Sub Procedure

Page 9: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

9

Calling a Sub Procedure

Figure 8-2: Lanza Trinkets application

Page 10: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

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

Page 11: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

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 valueBy 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

Page 12: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

Passing Variables by Value

■ Use the keyword ByVal before the parameter in the procedure declaration

■ ByVal 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

Page 13: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

Figure 8-6: Partial code for the Pet Information application

Page 14: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

Passing Variables by Reference

■ Use the keyword ByRef before the parameter in the procedure declaration

■ Procedure receives the address of the variable and is able to change the variable’s value

Page 15: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

Figure 8-8: CalcGrossPay procedure and calcButton_click event procedure

Page 16: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

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

Page 17: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

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 functionEnds the function

Page 18: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

Page 19: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

Function Procedures (cont'd.)

Page 20: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

Figure 8-20: Partial code for the Circle Area Calculator application

The Circle Area Calculator Application

Page 21: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

Creating a Function ProcedureThat Returns the Largest of Three Numbers

Figure 13.11 | Maximum application in Design view.

TextBoxes used toinput three values

Page 22: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

Creating a Function Procedure ThatReturns 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).

Figure 13.12 | Invoking Function procedure Maximum.

Calling a procedurethat has not yet been

defined is an error

Page 23: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

Creating a Function Procedure ThatReturns 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 finalMaximum.

Figure 13.14 | Math.Max returns the larger of its two arguments.

Calling Math.Max to determine the maximum of two values

Page 24: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

Introducing the EnhancedWage 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.

Page 25: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

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.

Page 26: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

Creating a Sub Procedure within theWage Calculator Application

■ Double click the Calculate Button to generatean event handler (Fig. 13.16).

Figure 13.16 | calculateButton_Click calls DisplayPay.

Call to DisplayPay

Page 27: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

Creating a Sub Procedure withinthe Wage Calculator Application (Cont.)

Figure 13.17 | Sub procedure DisplayPay definition.

DisplayPay calculates and displays the user’s gross earnings

Page 28: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

Creating a Function Procedure withinthe 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.

Figure 13.18 | Function procedure CheckOverTime definition.

CheckOvertime determines ifthe user has worked overtime

Page 29: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

Creating a Function Procedure within theWage Calculator Application (Cont.)

■ In Sub procedure DisplayPay, replace the statement on line 26 (Fig. 13.19).

Figure 13.19 | DisplayPay calls Function procedure CheckOvertime.

Call to procedureCheckOvertime

Page 30: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

1 Public Class WageCalculatorForm

2 ' handles Calculate Button's Click event

3 Private Sub calculateButton_Click(ByVal sender As System.Object, _

4 ByVal e As System.EventArgs) Handles calculateButton.Click

5

6 ' declare variables

7 Dim userHours As Double

8 Dim wage As Decimal

9

10 ' assign values from user input

11 userHours = Val(hoursTextBox.Text)

12 wage = Val(wageTextBox.Text)

13

14 ' call DisplayPay Sub procedure

15 DisplayPay(userHours, wage)

16 End Sub ' calculateButton_Click

(1 of 3 )

Call to Sub procedure that calculates and displays wages

Page 31: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

17

18 ' calculate and display wages

19 Sub DisplayPay(ByVal hours As Double, ByVal rate As Decimal)

20

21 ' declare variables

22 Dim earnings As Decimal

23 Const HOUR_LIMIT As Integer = 40

24

25 ' determine wage amount

26 If CheckOvertime(hours, HOUR_LIMIT) = False Then

27 ' earnings for regular wages

28 earnings = hours * rate

29 Else

30 ' regular wages for first HOUR_LIMIT hours

31 earnings = HOUR_LIMIT * rate

32

33 ' time and a half for overtime

34 earnings += ((hours - HOUR_LIMIT) * (1.5 * rate))

35 End If

(2 of 3 )

Call to Function procedure that determines if user has worked overtime

Sub procedure header specifies parameter names and types

Page 32: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

36

37 ' display result

38 earningsResultLabel.Text = String.Format("{0:C}", earnings)

39 End Sub ' DisplayPay

40

41 ' determine whether overtime pay has been earned

42 Function CheckOvertime(ByVal total As Double, _

43 ByVal limit As Integer) As Boolean

44

45 If total > limit Then

46 Return True ' return True if over limit

47 Else

48 Return False ' return False otherwise

49 End If

50 End Function ' CheckOvertime

51 End Class ' WageCalculatorForm

(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

Page 33: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

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 Optionalparameters:

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.

Page 34: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

Optional Parameters (Cont.)

■ Consider the Function BoxVolume:Function BoxVolume( Optional ByVal length As Integer = 1, _

Optional ByVal width As Integer = 1, _ Optional ByVal height As Integer = 1 ) As Integer

Return length * width * heightEnd Function ' BoxVolume

■ Each parameter has a default value specified with an = and a literal value (1).

Page 35: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

Optional Parameters (Cont.)

■ You can now invoke Function BoxVolume several different ways:

BoxVolume() ' returns 1; default values used for length, width, height

BoxVolume(10) ' returns 10; default values used for width, height

BoxVolume(10, 20) ' returns 200; default value used for height

BoxVolume(10, 20, 30) ' returns 6000; no default values usedBoxVolume(, 20, 30) ' returns 600; default value used for

lengthBoxVolume(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.

Page 36: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

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

Page 37: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

Figure 8-15: Some of the Gadis Antiques application’s code from Figure 8-4

Page 38: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

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

Page 39: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

Figure 8-16: ClearLabels procedure

Associating a Procedure with Different Objects and Events (cont'd.)

Page 40: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

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 thesix-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.

Page 41: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

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: Labelupdates to the current time once each second.

Figure 14.1 | Shipping Time application.

GroupBoxes

DateTimePicker with up and down arrows

Page 42: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

Introducing the Shipping TimeApplication: Design Elements

When the Form loads:Set range of possible drop-off times to any time in the

current dayCall sub procedure DisplayDeliveryTime to determine

and display the shipment’s delivery time

When the user changes the drop-off time:Call sub procedure DisplayDeliveryTime to determine

and display the shipment’s delivery time

After one second has elapsed:Update and display the current time

When the DisplayDeliveryTime procedure gets called:Call function DepartureTime to determine the time

the shipment’s flight departs

Page 43: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

Introducing the Shipping TimeApplication: 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 DepartureTime 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 23Delivery set to depart on noon flight of next

day

Case where none of the preceding Cases matchDelivery set to depart on midnight flight of

current day

Page 44: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

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 DateTime type in the .NET Framework Class Library.

■ You use the New keyword when creating a Date value. In the code, the statement

Dim delivery As Date = New Date(2003, 1, 1, 0, 0, 0)

■ The New keyword calls the Date’s constructor. A constructor is a procedure that initializes an object when it’s created.

Date constructor

Date variable

Page 45: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

Figure 14.2 | Date constructor arguments.

Date Variables (Cont.)

Argument Range Description

Initializing a Date variable using New Date(year, month, day, hour, minute, second)

year Integer values 1–9999 Specifies the year.

month Integer values 1–12 Specifies the month of the year.

day Integer values 1–number of days in month

Specifies the day of the month. Each month has 28 to 31 days depending on the month and year.

hour Integer values 0–23 Specifies the hour of the day on a 24 hour clock. The value 0 represents 12:00 A.M.

minute Integer values 0–59 Specifies the minute of the hour.

second Integer values 0–59 Specifies the number of elapsed seconds in the current minute.

■ Figure 14.2 explains the values used in Date’s constructor.

Page 46: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

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.

Page 47: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

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 year = delivery.Year ' retrieves Date delivery's yearDim month = delivery.Month ' retrieves Date delivery's monthDim day = delivery.Day ' retrieves Date delivery's dayDim hour = delivery.Hour ' retrieves Date delivery's hourDim minute = delivery.Minute ' retrieves Date delivery's

minuteDim second = delivery.Second ' retrieves Date delivery's

second

Page 48: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

■ 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

Date Variables (Cont.)

Visual Basic 2008 statement Result

Assume delivery has been initialized with a Date value.

delivery = delivery.AddHours(3) Add 3 hours.

delivery = delivery.AddMinutes(-5) Subtract 5 minutes.

delivery = delivery.AddDays(1) Add 1 day.

delivery = delivery.AddMinutes(30) Add 30 minutes.

delivery = delivery.AddHours(-12) Subtract 12 hours.

Page 49: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

■ To add a DateTimePicker to your application, drag a DateTimePicker control

from the Toolbox and drop it to the right of the Enter drop-off time: Label to place the DateTimePicker in the GroupBox (Fig. 14.8).

Creating and Customizing the DateTimePicker

Page 50: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

Creating and Customizing theDateTimePicker (Cont.)

■ When the DateTimePicker’s Format property is set to Custom, it uses the format that you specify in the CustomFormat property.

■ Set the value of the CustomFormat property to hh:mm tt.

The CustomFormat 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 DateTimePicker also prevents the user from specifying an invalid time, such as 32:15.

Page 51: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

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.

Page 52: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

Creating a Timer Control (Cont.)

■ Rename the Timer to clockTimer (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.

Component tray

Figure 14.10 | Timer control is displayed in the component tray.

Timer control

Page 53: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

■ Double click the Timer control in the component tray to generate the empty event handler for the Tick event (Fig. 14.11).

Coding the Shipping Time Application’s Clock

Printing the current time

Figure 14.11 | Inserting code for a Tick event.

■ The event handler formats its information to match the format you specify, "{hh:mm:ss tt}".

Page 54: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

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.

Figure 14.12 | Storing the current time.

Storing the current timein currentTime

Page 55: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

■ These lines (Fig. 14.13) set the MinDate and MaxDate properties for dropOffDateTimePicker.

Figure 14.13 | Setting the MinDate and MaxDate properties.

Using Code to Display a Delivery Time (Cont.)

Page 56: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

■ DisplayDeliveryTime is underlined in blue (Fig. 14.14) because the procedure has not yet been written.

■ The DisplayDeliveryTime 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 DisplayDeliveryTime procedure.

Using Code to Display a Delivery Time (Cont.)

Page 57: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

■ Double click the DateTimePicker controldropOffDateTimePicker to generate itsValueChanged event handler (Fig. 14.15).

Calculating and displaying the delivery time

Figure 14.15 | Inserting code in the ValueChanged event handler.

Coding the ValueChanged Event Handler

Page 58: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

Displaying the delivery time

Figure 14.16 | DisplayDeliveryTime procedure.

Adding the travel time

Determining the departure time

Coding the DisplayDeliveryTimeProcedure (Cont.)

Page 59: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

■ Line 51 (Fig. 14.17) stores the current date in the Date variable currentDate.

■ Line 52 declares the Date variable departTime, the variable you use to store the DepartureTime Function procedure’s return value.

Declaring variables

Figure 14.17 | Inserting procedure DepartureTime into the application.

Coding the DepartureTime Procedure

Page 60: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

Midnight departure time

Figure 14.18 | Determining the seafood shipment’s flight departure time.

Coding the DepartureTime Procedure (Cont.)

Noon (the next day) departure time

Noon departure time

Using the hour value stored in the DateTimePicker to

determine departure time

Returning the departure time

Page 61: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

1 Public Class ShippingTimeForm

2 ' handles clockTimer's Tick event

3 Private Sub clockTimer_Tick(ByVal sender As System.Object, _

4 ByVal e As System.EventArgs) Handles clockTimer.Tick

5

6 ' print current time

7 currentTimeLabel.Text = String.Format("{0:hh:mm:ss tt}", _

8 Date.Now)

9 End Sub ' clockTimer_Tick

10

11 ' initialize DateTimePicker status when Form loads

12 Private Sub ShippingTimeForm_Load(ByVal sender As _

13 System.Object, ByVal e As System.EventArgs) _

14 Handles MyBase.Load

15

16 Dim currentTime As Date = Date.Now ' store current time

17

Event raised when the Timer raises a Tick event

(1 of 4 )

Displaying current time

Event raised whenthe Form loads

Page 62: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

18 ' set range of possible drop-off times

19 dropOffDateTimePicker.MinDate = New Date(currentTime.Year, _

20 currentTime.Month, currentTime.Day, 0, 0, 0)

21

22 dropOffDateTimePicker.MaxDate = _

23 dropOffDateTimePicker.MinDate.AddDays(1)

24

25 ' display the delivery time

26 DisplayDeliveryTime()

27 End Sub ' ShippingTimeForm_Load

28

29 ' handles the DateTimePicker's ValueChanged event

30 Private Sub dropOffDateTimePicker_ValueChanged(ByVal sender As _

31 System.Object, ByVal e As System.EventArgs) _

32 Handles dropOffDateTimePicker.ValueChanged

33

34 ' display the delivery time

35 DisplayDeliveryTime()

36 End Sub ' dropOffDateTimePicker_ValueChanged

(2 of 4 )

Setting the DateTimePicker’s minimum and maximum values

Event raised when the user changes the value of the DateTimePicker

Page 63: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

37

38 ' calculates and displays the delivery time

39 Sub DisplayDeliveryTime()

40 ' get initial delivery time

41 Dim delivery As Date = DepartureTime()

42

43 ' add 3 hours to departure and display result

44 delivery = delivery.AddHours(3)

45 lasVegasTimeLabel.Text = delivery.ToLongDateString _

46 & " at " & delivery.ToShortTimeString

47 End Sub ' DisplayDeliveryTime

48

49 ' return flight departure time for selected drop-off time

50 Function DepartureTime() As Date

51 Dim currentDate As Date = Date.Now ' store current date

52 Dim departTime As Date ' store departure time

(3 of 4 )

Calculating and displaying the delivery time in Las Vegas

Page 64: Microsoft Visual Basic: Reloaded Chapter Eight Sub and Function Procedures

2009 Pearson Education, Inc. All rights reserved.

53

54 ' determine which flight the shipment takes

55 Select Case dropOffDateTimePicker.Value.Hour

56 Case 0 To 10 ' seafood will be on the noon flight

57 departTime = New Date(currentDate.Year, _

58 currentDate.Month, currentDate.Day, 12, 0, 0)

59 Case 23 ' seafood will be on tomorrow's noon flight

60 currentDate = currentDate.AddDays(1)

61 departTime = New Date(currentDate.Year, _

62 currentDate.Month, currentDate.Day, 12, 0, 0)

63 Case Else ' seafood will be on midnight flight

64 currentDate = currentDate.AddDays(1)

65 departTime = New Date(currentDate.Year, _

66 currentDate.Month, currentDate.Day, 0, 0, 0)

67 End Select

68

69 Return departTime ' return the flight's departure time

70 End Function ' DepartureTime

71 End Class ' ShippingTimeForm

(4 of 4 )

Using a Select Case statement to determine departure time