T U T O R I A L Shipping Time Application Using Dates and Timers  2009 Pearson Education, Inc.

Download Report

Transcript T U T O R I A L Shipping Time Application Using Dates and Timers  2009 Pearson Education, Inc.

1
T U T O R I A L
14
Shipping Time
Application
Using Dates and Timers
 2009 Pearson Education, Inc. All rights reserved.
2
Outline
14.1 Test-Driving the Shipping Time Application
14.2 Date Variables
14.3 Creating the Shipping Time Application:
Design Elements
14.4 Creating the Shipping Time Application:
Inserting Code
 2009 Pearson Education, Inc. All rights reserved.
3
Objectives
In this tutorial you will learn:
■ Create and manipulate Date variables.
■ Execute code at regular intervals using a Timer
control.
■ Retrieve Date input with a DateTimePicker
control.
■ Group controls using a GroupBox control.
 2009 Pearson Education, Inc. All rights reserved.
4
14.1 Test-Driving the Shipping Time Application
Application Requirements
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.
5
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.
DateTimePicker with
up and down arrows
GroupBoxes
Figure 14.1 | Shipping Time application.
 2009 Pearson Education, Inc. All rights reserved.
6
14.2 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
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.
7
14.2 Date Variables (Cont.)
■ Figure 14.2 explains the values used in Date’s
constructor.
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 | Date constructor arguments.
 2009 Pearson Education, Inc. All rights reserved.
8
Error-Prevention Tip
Always store dates in a Date variable. Storing dates in
variables of other types can lead to conversion errors
and loss of data.
 2009 Pearson Education, Inc. All rights reserved.
9
14.2 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.
– Often, method overloading is used to create several
methods with the same name that perform similar tasks.
– If a type provides overloaded constructors or methods,
Parameter Info Window shows a tooltip (Fig. 14.3)
containing one of the available overloads.
 2009 Pearson Education, Inc. All rights reserved.
10
14.2 Date Variables (Cont.)
Figure 14.3 | Parameter Info Window showing overloaded Date constructors.
 2009 Pearson Education, Inc. All rights reserved.
11
14.2 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
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
Dim second = delivery.Second ' retrieves Date delivery's second
 2009 Pearson Education, Inc. All rights reserved.
12
14.2 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).
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.
Figure 14.4 | Date methods that perform various
 2009 Pearson Education, Inc. All rights reserved.
13
Common Programming Error
Date methods do not modify the Date value on which
they are called. You must assign the result of the
method to a variable of type Date.
 2009 Pearson Education, Inc. All rights reserved.
14.3 Creating the Shipping Time
Application: Design Elements
14
When the Form loads:
Set range of possible drop-off times to any time in the
current day
Call 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
 2009 Pearson Education, Inc. All rights reserved.
14.3 Creating the Shipping Time
Application: Design Elements (Cont.)
15
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 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.
Action/Control/Event (ACE) Table for the
16
Shipping Time Application
■ Use an ACE table to convert pseudocode into Visual Basic (Fig. 14.5).
Action
Control
Event/Method
Label the application’s controls
currentTimeIsLabel,
Application is run
dropOffLabel,
deliveryTimeLabel
ShippingTimeForm
Set range of possible drop-off times to any
time in the current day
Call sub procedure DisplayDevliveryTime to
determine and display the shipment’s
delivery time
dropOffDateTimePicker
dropOffDateTimePicker,
lasVegasTimeLabel
dropOffDateTimePicker
Call sub procedure DisplayDevliveryTime to
determine and display the shipment’s
delivery time
Load
ValueChanged
dropOffDateTimePicker,
lasVegasTimeLabel
Figure 14.5 | ACE table for the Shipping Time application. (Part 1 of 3.)
 2009 Pearson Education, Inc. All rights reserved.
Action/Control/Event (ACE) Table for the
17
Shipping Time Application (Cont.)
Action
Update and display the current time
Control
Event/Method
clockTimer
Tick
currentTimeLabel
DisplayDeliveryTime
Call function DepartureTime to determine
the time the shipment’s flight departs
dropOffDateTimePicker
Add three hours to determine the delivery
time
Display the delivery time
lasVegasTimeLabel
Figure 14.5 | ACE table for the Shipping Time application. (Part 2 of 3.)
 2009 Pearson Education, Inc. All rights reserved.
Action/Control/Event (ACE) Table for the
18
Shipping Time Application (Cont.)
Action
Event/Method
Control
DepartureTime
Select correct Case based on the hour the
shipment was dropped off
dropOffDateTimePicker
Case where drop-off hour is 0–10
Delivery set to depart on noon flight
Case where 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
Figure 14.5 | ACE table for the Shipping Time application. (Part 3 of 3.)
 2009 Pearson Education, Inc. All rights reserved.
19
Placing Controls in a GroupBox
■ Add a GroupBox named dropOffGroupBox
by double clicking the GroupBox control in the
Containers tab of the Toolbox.
– Change the Text property to Drop Off.
– Place the GroupBox above the provided GroupBox
and make them the same size (Fig. 14.6).
 2009 Pearson Education, Inc. All rights reserved.
20
Placing Controls in a GroupBox (Cont.)
Newly created GroupBox
displaying the text Drop Off
GroupBoxes
Figure 14.6 | GroupBox controls on the Shipping Time Form.
 2009 Pearson Education, Inc. All rights reserved.
21
GUI Design Tip
GroupBox titles should be concise and should use
book-title capitalization.
 2009 Pearson Education, Inc. All rights reserved.
22
Good Programming Practice
Append the GroupBox suffix to GroupBox control
names.
 2009 Pearson Education, Inc. All rights reserved.
23
Placing Controls in a GroupBox (Cont.)
■ Click the Label control in the Toolbox, then click
inside the GroupBox that you just created.
– Change the Label’s Text property to Enter drop-off
time: and its Name property to dropOffLabel.
– Then change the position of the Label by setting its
Location property to 6, 33 (Fig. 14.7).
 2009 Pearson Education, Inc. All rights reserved.
24
Placing Controls in a GroupBox (Cont.)
Before clicking inside
the GroupBox
Figure 14.7 | Adding a Label to a GroupBox.
■ Location values are measured from the top-left
corner of the GroupBox, not from the top-left corner
of the Form.
 2009 Pearson Education, Inc. All rights reserved.
25
GUI Design Tip
Use GroupBoxes to group related controls in a box
with a title.
 2009 Pearson Education, Inc. All rights reserved.
26
Creating and Customizing the DateTimePicker
■ 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).
 2009 Pearson Education, Inc. All rights reserved.
Creating and Customizing the
DateTimePicker (Cont.)
27
DateTimePicker control
before modification
Figure 14.8 | DateTimePicker control on the Form.
– Change its Name property to dropOffDateTimePicker.
– Align the DateTimePicker with its descriptive Label.
– Next, change its Format property to Custom.
 2009 Pearson Education, Inc. All rights reserved.
28
GUI Design Tip
Each DateTimePicker should have a corresponding
descriptive Label.
 2009 Pearson Education, Inc. All rights reserved.
29
Error-Prevention Tip
If the user is to specify a date and/or time, use a
DateTimePicker control to prevent the user from
entering invalid date or time values.
 2009 Pearson Education, Inc. All rights reserved.
30
GUI Design Tip
If the user is to specify a time of day or a date and time,
set the DateTimePicker’s ShowUpDown property to
True. If the user is to specify only a date, set the
DateTimePicker’s ShowUpDown property to False to
allow the user to select a day from the month calendar.
 2009 Pearson Education, Inc. All rights reserved.
Creating and Customizing the
DateTimePicker (Cont.)
31
■ 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.
 2009 Pearson Education, Inc. All rights reserved.
Creating and Customizing the
DateTimePicker (Cont.)
32
■ Set the DateTimePicker’s ShowUpDown property to
True.
■ The user needs to enter only the time of day, so you
use up and down arrows to allow the user to select
the time (Fig. 14.9).
Up and down arrows for
DateTimePicker (note that the
appearance is similar to a
NumericUpDown control)
Figure 14.9 | Customized DateTimePicker control on the Form.
 2009 Pearson Education, Inc. All rights reserved.
33
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.
34
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.
Timer control
Component tray
Figure 14.10 | Timer control is displayed in the component tray.
 2009 Pearson Education, Inc. All rights reserved.
35
Good Programming Practice
Append the Timer suffix to Timer control names.
 2009 Pearson Education, Inc. All rights reserved.
36
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 its information to match the
format you specify, "{hh:mm:ss tt}".
 2009 Pearson Education, Inc. All rights reserved.
37
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 currentTime
Figure 14.12 | Storing the current time.
 2009 Pearson Education, Inc. All rights reserved.
38
Using Code to Display a Delivery Time (Cont.)
■ These lines (Fig. 14.13) set the MinDate and
MaxDate properties for dropOffDateTimePicker.
Setting the range of
drop-off times
Figure 14.13 | Setting the MinDate and MaxDate properties.
 2009 Pearson Education, Inc. All rights reserved.
39
Using Code to Display a Delivery Time (Cont.)
■ The earliest drop-off time is set to 12:00 A.M. of the
current day, and the latest drop-off time is set to
12:00 A.M. the following day.
■ The Date type also provides property Today, which
returns the current date with the time set to
00:00:00 (midnight).
 2009 Pearson Education, Inc. All rights reserved.
40
Using Code to Display a Delivery Time (Cont.)
■ 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.
 2009 Pearson Education, Inc. All rights reserved.
41
Coding the ValueChanged Event Handler
■ Double click the DateTimePicker control
dropOffDateTimePicker to generate its
ValueChanged event handler (Fig. 14.15).
Calculating and displaying the
delivery time
Figure 14.15 | Inserting code in the ValueChanged event handler.
 2009 Pearson Education, Inc. All rights reserved.
42
Coding the DisplayDeliveryTime Procedure
■ DepartureTime is underlined in blue (Fig. 14.16)
because the procedure has not yet been written.
■ The DepartureTime procedure determines which
flight (midnight or noon) the seafood shipment will use.
■ A Date variable’s ToLongDateString method
returns the date as a String in the format
“Wednesday, October 30, 2008.”
■ A Date variable’s ToShortTimeString returns the
time as a String in the format “4:00 PM.”
 2009 Pearson Education, Inc. All rights reserved.
Coding the DisplayDeliveryTime
Procedure (Cont.)
43
Determining the departure time
Adding the travel time
Displaying the delivery time
Figure 14.16 | DisplayDeliveryTime procedure.
 2009 Pearson Education, Inc. All rights reserved.
44
Coding the DepartureTime Procedure
■ 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.
 2009 Pearson Education, Inc. All rights reserved.
45
Coding the DepartureTime Procedure (Cont.)
■ The Select Case statement (Fig. 14.18) uses the
hour specified by the user in the DateTimePicker
as the controlling expression.
■ The DateTimePicker’s Value property (which is of
type Date) contains the value selected by the user.
 2009 Pearson Education, Inc. All rights reserved.
46
Coding the DepartureTime Procedure (Cont.)
Using the hour value stored in
the DateTimePicker to
determine departure time
Noon departure time
Noon (the next day) departure
time
Midnight departure time
Figure 14.18 | Determining the seafood shipment’s flight departure time.
 2009 Pearson Education, Inc. All rights reserved.
47
Coding the DepartureTime Procedure (Cont.)
■ The first Case statement’s expression list determines
whether the DateTimePicker’s value is between
midnight and 10:59 A.M. (Hour = 10).
– If so, the seafood shipment takes the noon flight to Las
Vegas.
■ The next Case statement’s expression list determines
whether the value in the DateTimePicker is
between 11:00 P.M. and 11:59 P.M. (Hour = 23).
– If so, the seafood shipment takes the noon flight to Las
Vegas the next day.
 2009 Pearson Education, Inc. All rights reserved.
48
Coding the DepartureTime Procedure (Cont.)
■ The Case Else’s body executes if the controlling
expression matches neither of the other two Cases
(the value in the DateTimePicker is between
11:00 A.M. and 10:59 P.M.).
– In this case, the seafood shipment takes the midnight flight
to Las Vegas.
 2009 Pearson Education, Inc. All rights reserved.
49
Coding the DepartureTime Procedure (Cont.)
■ Line 69 (Fig. 14.19) returns the Date value containing
the flight departure time.
Returning the departure time
Figure 14.19 | Returning the flight departure time.
 2009 Pearson Education, Inc. All rights reserved.
50
Outline
■ Figure 14.20 presents the source code for the
application.
(1 of 4 )
1
Public Class ShippingTimeForm
2
3
4
' handles clockTimer's Tick event
Private Sub clockTimer_Tick(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles clockTimer.Tick
5
6
7
8
9
' print current time
currentTimeLabel.Text = String.Format("{0:hh:mm:ss tt}", _
Date.Now)
End Sub ' clockTimer_Tick
Event raised when the
Timer raises a Tick
event
Displaying current time
10
11
12
' initialize DateTimePicker status when Form loads
Private Sub ShippingTimeForm_Load(ByVal sender As _
13
14
15
System.Object, ByVal e As System.EventArgs) _
Handles MyBase.Load
16
17
Dim currentTime As Date = Date.Now ' store current time
Event raised when
the Form loads
 2009 Pearson Education,
Inc. All rights reserved.
51
Outline
(2 of 4 )
18
19
20
21
22
23
24
25
' set range of possible drop-off times
dropOffDateTimePicker.MinDate = New Date(currentTime.Year, _
currentTime.Month, currentTime.Day, 0, 0, 0)
dropOffDateTimePicker.MaxDate = _
dropOffDateTimePicker.MinDate.AddDays(1)
' display the delivery time
26
27
28
29
DisplayDeliveryTime()
End Sub ' ShippingTimeForm_Load
30
31
Private Sub dropOffDateTimePicker_ValueChanged(ByVal sender As _
System.Object, ByVal e As System.EventArgs) _
32
33
34
35
36
Setting the
DateTimePicker’s
minimum and
maximum values
' handles the DateTimePicker's ValueChanged event
Handles dropOffDateTimePicker.ValueChanged
Event raised when
the user changes the
value of the
DateTimePicker
' display the delivery time
DisplayDeliveryTime()
End Sub ' dropOffDateTimePicker_ValueChanged
 2009 Pearson Education,
Inc. All rights reserved.
52
Outline
(3 of 4 )
37
38
' calculates and displays the delivery time
39
40
Sub DisplayDeliveryTime()
' get initial delivery time
41
42
Dim delivery As Date = DepartureTime()
43
44
45
' add 3 hours to departure and display result
delivery = delivery.AddHours(3)
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
52
Calculating and displaying
the delivery time in Las
Vegas
Dim currentDate As Date = Date.Now ' store current date
Dim departTime As Date ' store departure time
 2009 Pearson Education,
Inc. All rights reserved.
53
Outline
(4 of 4 )
53
54
' determine which flight the shipment takes
55
56
57
Select Case dropOffDateTimePicker.Value.Hour
Case 0 To 10 ' seafood will be on the noon flight
departTime = New Date(currentDate.Year, _
58
59
60
currentDate.Month, currentDate.Day, 12, 0, 0)
Case 23 ' seafood will be on tomorrow's noon flight
currentDate = currentDate.AddDays(1)
61
62
63
64
departTime = New Date(currentDate.Year, _
currentDate.Month, currentDate.Day, 12, 0, 0)
Case Else ' seafood will be on midnight flight
65
66
67
Using a Select Case
statement to determine
departure time
currentDate = currentDate.AddDays(1)
departTime = New Date(currentDate.Year, _
currentDate.Month, currentDate.Day, 0, 0, 0)
End Select
68
Return departTime ' return the flight's departure time
69
End Function ' DepartureTime
70
71 End Class ' ShippingTimeForm
 2009 Pearson Education,
Inc. All rights reserved.