Home

Windows Control: The Time Picker Control

 

Introduction to the Date/Time Picker Control

 

Description

The date/time picker is a control that allows the user to select either a date or a time value. This control provides two objects in one:

Date/Time Picker

Date/Time Picker

Date/Time Picker

One of the advantages of the date/time picker control is that it allows the user to select a time or a date value instead of typing it. This tremendously reduces the likelihood of mistakes.

Creating a Date/Time Picker

To create a date/time picker control, from the Common Controls section of the Toolbox, click DateTimePicker DateTimePicker and click the form or another container. The DateTimePicker control is based on the DateTimePicker class. Therefore, to programmatically, declare a variable of type DateTimePicker and initialize it appropriately. Here is an example:

Imports System.Drawing
Imports System.Windows.Forms

Module Exercise

    Public Class Starter
        Inherits Form

        Private DateOrTime As DateTimePicker

        Dim components As System.ComponentModel.Container

        Public Sub New()
            InitializeComponent()
        End Sub

        Public Sub InitializeComponent()
            DateOrTime = New DateTimePicker

            Controls.Add(DateOrTime)
        End Sub

    End Class

    Function Main() As Integer

        Dim frmStart As Starter = New Starter

        Application.Run(frmStart)

        Return 0
    End Function

End Module

In reality, the DateTimePicker control can be considered as two controls in one: you just have to choose which one of both controls you want to use.

Introduction to the Date Picker

After adding the DateTimePicker control to the form, to allow the user to set the dates and not the times on the control, set its Format property either to Long or to Short. If you are working programmatically, use the DateTimePickerFormat enumeration to select Long or Short and assign it to the Format property of the control. Here is an example:

Imports System.Drawing
Imports System.Windows.Forms

Module Exercise

    Public Class Starter
        Inherits Form

        Private Calendar As DateTimePicker

        Dim components As System.ComponentModel.Container

        Public Sub New()
            InitializeComponent()
        End Sub

        Public Sub InitializeComponent()
            Calendar = New DateTimePicker
            Calendar.Format = DateTimePickerFormat.Long

            Controls.Add(Calendar)
        End Sub

    End Class

    Function Main() As Integer

        Dim frmStart As Starter = New Starter

        Application.Run(frmStart)

        Return 0
    End Function

End Module

Introduction to the Time Picker

 

Introduction

As described already, the date time picker is two controls in one object. To transform a date time picker into a time picker control, change its Format property to a Time value. You can also do this programmatically. Here is an example:

Imports System.Drawing
Imports System.Windows.Forms

Module Exercise

    Public Class Starter
        Inherits Form

        Private ShowTime As DateTimePicker

        Dim components As System.ComponentModel.Container

        Public Sub New()
            InitializeComponent()
        End Sub

        Public Sub InitializeComponent()
            ShowTime = New DateTimePicker
            ShowTime.Format = DateTimePickerFormat.Time

            Controls.Add(ShowTime)
        End Sub

    End Class

    Function Main() As Integer

        Dim frmStart As Starter = New Starter

        Application.Run(frmStart)

        Return 0
    End Function

End Module

Time Picker

Although optional, you should (with emphasis) also set the ShowUpDown Boolean property to True. Here is an example:

Public Sub InitializeComponent()
            ShowTime = New DateTimePicker
            ShowTime.Format = DateTimePickerFormat.Time
            ShowTime.ShowUpDown = True

            Controls.Add(ShowTime)
End Sub

This makes it a true time picker control:

Time Picker
 

If you do not set the ShowUpDown property to true, the control would display as a combo box and when the user clicks the arrow button, a calendar would come up, which does not make sense since the purpose of the control is to deal with time values.

Practical LearningPractical Learning: Introducing the Date Picker

  1. Start a new Windows Application named GeorgetownCleaningServices2
  2. In the Solution Explorer, right-click Form1.vb and click Rename
  3. Type CleaningServices.vb and press Enter
  4. Design the form as follows:
     
    Georgetown Cleaning Services
     
    Control Name Text Additional Properties
    GroupBox GroupBox   Order Identification  
    Label Label   Customer Name:  
    TextBox TextBox txtCustomerName    
    Label Label   Customer Phone:  
    TextBox TextBox txtCustomerPhone    
    Label Label   Date Left:  
    DateTimePicker DateTimePicker dtpDateLeft    
    Label Label   Time Left:  
    DateTimePicker Date Time Picker dtpTimeLeft   Format: Time
    Label Label   Date Expected:  
    DateTimePicker DateTimePicker dtpDateExpected    
    Label Label   Time Expected:  
    DateTimePicker DateTimePicker dtpTimeExpected   Format: Time
    GroupBox GroupBox   Order Processing  
    Label Label   Item Type  
    Label Label   Unit Price  
    Label Label   Qty  
    Label Label   Sub Total  
    Label Label   Shirts  
    TextBox TextBox txtShirtsUnitPrice 1.25 TextAlign: Right
    TextBox TextBox txtShirtsQuantity 0 TextAlign: Right
    TextBox TextBox txtShirtsSubTotal 0.00 TextAlign: Right
    Label Label   Pants  
    TextBox TextBox txtPantsUnitPrice 1.95 TextAlign: Right
    TextBox TextBox txtPantsQuantity   TextAlign: Right
    TextBox TextBox txtPantsSubTotal 0.00 TextAlign: Right
    ComboBox ComboBox cbxItem1 None Items:
    None
    Women Suit
    Dress
    Regular Skirt
    Skirt With Hook
    Men's Suit 2Pc
    Men's Suit 3Pc
    Sweaters
    Silk Shirt
    Tie
    Coat
    Jacket
    Swede
    TextBox TextBox txtItem1UnitPrice 0.00 TextAlign: Right
    TextBox TextBox txtItem1Quantity 0 TextAlign: Right
    TextBox TextBox txtItem1SubTotal 0.00 TextAlign: Right
    ComboBox ComboBox cbxItem2 None Items:
    None
    Women Suit
    Dress
    Regular Skirt
    Skirt With Hook
    Men's Suit 2Pc
    Men's Suit 3Pc
    Sweaters
    Silk Shirt
    Tie
    Coat
    Jacket
    Swede
    TextBox TextBox txtItem2UnitPrice 0.00 TextAlign: Right
    TextBox TextBox txtItem2Quantity 0 TextAlign: Right
    TextBox TextBox txtItem2SubTotal 0.00 TextAlign: Right
    ComboBox ComboBox cbxItem3 None Items:
    None
    Women Suit
    Dress
    Regular Skirt
    Skirt With Hook
    Men's Suit 2Pc
    Men's Suit 3Pc
    Sweaters
    Silk Shirt
    Tie
    Coat
    Jacket
    Swede
    TextBox TextBox txtItem3UnitPrice 0.00 TextAlign: Right
    TextBox TextBox txtItem3Quantity 0 TextAlign: Right
    TextBox TextBox txtItem3SubTotal 0.00 TextAlign: Right
    ComboBox ComboBox cbxItem4 None Items:
    None
    Women Suit
    Dress
    Regular Skirt
    Skirt With Hook
    Men's Suit 2Pc
    Men's Suit 3Pc
    Sweaters
    Silk Shirt
    Tie
    Coat
    Jacket
    Swede
    TextBox TextBox txtItem4UnitPrice 0.00 TextAlign: Right
    TextBox TextBox txtItem4Quantity 0 TextAlign: Right
    TextBox TextBox txtItem4SubTotal 0.00 TextAlign: Right
    GroupBox GroupBox   Order Summary  
    Button Button btnCalculate Calculate  
    Label Label   Cleaning Total:  
    TextBox TextBox txtCleaningTotal 0.00 TextAlign: Right
    Label Label   Tax Rate:  
    TextBox TextBox txtTaxRate 7.75 TextAlign: Right
    Label Label   %  
    Label Label   Tax Amount:  
    TextBox TextBox txtTaxAmount 0.00 TextAlign: Right
    Label Label   Net Total:  
    TextBox TextBox txtNetPrice 0.00 TextAlign: Right
    Button Button btnClose Close  
  5. Right-click the form and click View Code

Using the Time Picker

The time picker is meant either to only display a time to the user or to both display time and allow the user to specify a time. The control follows the format of the time values set in the regional settings of Control Panel. By default, in US English, the time is divided in four sections that include the hour value, the minute value, the second value, and the AM/PM side. These sections are separated by standard characters that also are specified in the regional settings of Control Panel.

To change the time, the user can click a section, such as the hour, the minute, the second, or the AP/PM side, then click one of the arrows of the spin button. The up button increases (only) the value of the selected section while the down button decreases (only) the value of the selected section. The user can also use the arrow keys to change the value of a section.

After changing the of the time, even the change occurs for only one section, the control fires a ValueChanged event, which is the default event of the control.

Characteristics of the Time Picker

 

The Value of the Time Picker

As mentioned already, the user changes the time by using the various sections of the controls. If the user changes the value of a section, it is considered that the whole time has been changed. At any time, the (current) time of the control is stored in the Value property. You can use this property either to programmatically change the time on the control or to get the time on the control.

Practical LearningPractical Learning: Using the Time Picker

  1. In the Class Name combo box, select dtpTimeLeft
  2. In the Method Name combo box, select ValueChanged and implement the event as follows:
     
    Private Sub dtpTimeLeftValueChanged(ByVal sender As Object, 
                                             ByVal e As System.EventArgs) 
                                             Handles dtpTimeLeft.ValueChanged
            Dim dateLeft As DateTime
            Dim timeLeft As DateTime
            Dim time9AM As DateTime
    
            dateLeft = dtpDateLeft.Value
            timeLeft = dtpTimeLeft.Value
            time9AM = New DateTime(timeLeft.Year, 
    			timeLeft.Month, timeLeft.Day, 9, 0, 0)
    
            ' If the customer leaves clothes before 9AM...
            If timeLeft <= time9AM Then
    
                ' ... then they should be ready the same day after 5PM
                dtpDateExpected.Value = dateLeft
                dtpTimeExpected.Value = New DateTime(dateLeft.Year, 
                                                     dateLeft.Month, 
                                                     dateLeft.Day, 17, 0, 0)
            Else
    
                ' If the clothes were left after 9AM, 
    	    ' they will be available the following morning at 8AM
                dtpDateExpected.Value = New DateTime(dateLeft.Year, 
                                                     dateLeft.Month, 
                                                     dateLeft.Day + 1)
                dtpTimeExpected.Value = New DateTime(dateLeft.Year, 
                                                     dateLeft.Month, 
                                                     dateLeft.Day + 1, 8, 0, 0)
            End If
    End Sub
  3. In the Class Name combo box, select btnCalculate
  4. In the Method Name combo box, select Click and implement the event as follows:
     
    Private Sub btnCalculateClick(ByVal sender As Object, 
                                       ByVal e As System.EventArgs) 
                                       Handles btnCalculate.Click
            Dim UnitPriceShirts As Double, UnitPricePants As Double
            Dim UnitPriceItem1 As Double, UnitPriceItem2 As Double
            Dim UnitPriceItem3 As Double, UnitPriceItem4 As Double
            Dim SubTotalShirts As Double, SubTotalPants As Double
            Dim SubTotalItem1 As Double, SubTotalItem2 As Double
            Dim SubTotalItem3 As Double, SubTotalItem4 As Double
            Dim QuantityShirts As Integer, QuantityPants As Integer = 1
            Dim QuantityItem1 As Integer, QuantityItem2 As Integer = 1
            Dim QuantityItem3 As Integer, QuantityItem4 As Integer = 4
    
            Dim CleaningTotal As Double, TaxRate As Double
            Dim TaxAmount As Double, NetPrice As Double
    
            ' Retrieve the unit price of this item
            ' Just in case the user types an invalid value, 
    	' we are using a try...catch
            Try
                UnitPriceShirts = CDbl(txtUnitPriceShirts.Text)
            Catch ex As Exception
                MsgBox("The value you entered for the price " & 
    		   "of shirts is not valid" & 
                       vbCrLf & "Please try again")
                Exit Sub
            End Try
    
            ' Retrieve the number of this item
            ' Just in case the user types an invalid value, 
    	' we are using a try...catch
            Try
                QuantityShirts = CInt(txtQuantityShirts.Text)
            Catch ex As Exception
                MsgBox("The value you entered for the number of & 
    		   "shirts is not valid" & 
                                vbCrLf & "Please try again")
                Exit Sub
            End Try
    
            Try
                UnitPricePants = CDbl(txtUnitPricePants.Text)
            Catch ex As Exception
                MsgBox("The value you entered for the price of & 
    		   "pants is not valid" & 
                                vbCrLf & "Please try again")
                Exit Sub
            End Try
    
            Try
                QuantityPants = CInt(txtQuantityPants.Text)
            Catch ex As Exception
                MsgBox("The value you entered for the number of & 
    		   "pants is not valid" & 
                                vbCrLf & "Please try again")
                Exit Sub
            End Try
    
            If (cbxItem1.Text = "None") Or (cbxItem1.Text = "") Then
                QuantityItem1 = 0
                UnitPriceItem1 = 0.0
            Else
    
                Try
                    UnitPriceItem1 = CDbl(txtUnitPriceItem1.Text)
                Catch ex As Exception
                    MsgBox("The value you entered for the price is not valid" & 
                                vbCrLf & "Please try again")
                    Exit Sub
                End Try
    
                Try
                    QuantityItem1 = CInt(txtQuantityItem1.Text)
                Catch
                    MsgBox("The value you entered is not valid" & 
                            vbCrLf & "Please try again")
                    Exit Sub
                End Try
            End If
    
            If (cbxItem2.Text = "None") Or (cbxItem2.Text = "") Then
                QuantityItem2 = 0
                UnitPriceItem2 = 0.0
            Else
                Try
                    UnitPriceItem2 = CDbl(txtUnitPriceItem2.Text)
                Catch
    
                    MsgBox("The value you entered for the price is not valid" & 
                            vbCrLf & "Please try again")
                    Exit Sub
                End Try
    
                Try
                    QuantityItem2 = CInt(txtQuantityItem2.Text)
                Catch
                    MsgBox("The value you entered is not valid" & 
                            vbCrLf & "Please try again")
                    Exit Sub
                End Try
            End If
    
            If (cbxItem3.Text = "None") Or (cbxItem3.Text = "") Then
                QuantityItem3 = 0
                UnitPriceItem3 = 0.0
            Else
    
                Try
                    UnitPriceItem3 = CDbl(txtUnitPriceItem3.Text)
                Catch ex As Exception
                    MsgBox("The value you entered for the price is not valid" & 
                            vbCrLf & "Please try again")
                    Exit Sub
                End Try
    
                Try
                    QuantityItem3 = CInt(txtQuantityItem3.Text)
                Catch ex As Exception
                    MsgBox("The value you entered is not valid" & 
                            vbCrLf & "Please try again")
                    Exit Sub
                End Try
            End If
    
            If (cbxItem4.Text = "None") Or (cbxItem4.Text = "") Then
                QuantityItem4 = 0
                UnitPriceItem4 = 0.0
            Else
                Try
                    UnitPriceItem4 = CDbl(txtUnitPriceItem4.Text)
                Catch ex As Exception
                    MsgBox("The value you entered for the price is not valid" & 
                            vbCrLf & "Please try again")
                    Exit Sub
                End Try
    
                Try
                    QuantityItem4 = CInt(txtQuantityItem4.Text)
                Catch ex As Exception
                    MsgBox("The value you entered is not valid" & 
                            vbCrLf & "Please try again")
                    Exit Sub
                End Try
            End If
    
            ' Calculate the sub-total for this item
            SubTotalShirts = QuantityShirts * UnitPriceShirts
            SubTotalPants = QuantityPants * UnitPricePants
            SubTotalItem1 = QuantityItem1 * UnitPriceItem1
            SubTotalItem2 = QuantityItem2 * UnitPriceItem2
            SubTotalItem3 = QuantityItem3 * UnitPriceItem3
            SubTotalItem4 = QuantityItem4 * UnitPriceItem4
    
            ' Calculate the total based on sub-totals
            CleaningTotal = SubTotalShirts + SubTotalPants + 
                            SubTotalItem1 + SubTotalItem2 + 
                            SubTotalItem3 + SubTotalItem4
    
            TaxRate = CDbl(txtTaxRate.Text)
            ' Calculate the amount owed for the taxes
            TaxAmount = CleaningTotal * TaxRate / 100
            ' Add the tax amount to the total order
            NetPrice = CleaningTotal + TaxAmount
    
            ' Display the sub-total in the corresponding text box
            txtSubTotalShirts.Text = FormatNumber(SubTotalShirts)
            txtSubTotalPants.Text = FormatNumber(SubTotalPants)
            txtSubTotalItem1.Text = FormatNumber(SubTotalItem1)
            txtSubTotalItem2.Text = FormatNumber(SubTotalItem2)
            txtSubTotalItem3.Text = FormatNumber(SubTotalItem3)
            txtSubTotalItem4.Text = FormatNumber(SubTotalItem4)
    
            txtCleaningTotal.Text = FormatNumber(CleaningTotal)
            txtTaxAmount.Text = FormatNumber(TaxAmount)
            txtNetPrice.Text = FormatNumber(NetPrice)
    End Sub
  5. In the Class Name combo box, select btnClose
  6. In the Method Name combo box, select Click and implement the event as follows:
     
    Private Sub btnCloseClick(ByVal sender As Object, 
                                   ByVal e As System.EventArgs) 
                                   Handles btnClose.Click
            End
    End Sub
  7. Execute the application and create a few orders
     
    Georgetown Cleaning Services
  8. Close the form and return to your programming environment

Using a Custom Format

By default, the time displays using the H:M:SS AM/PM format. This means that the time uses 1 digit for the hours from 0 to 9, 1 digit for the minutes from 0 to 9, 1 digit for the seconds from 0 to 9 and the AM or PM for morning or afternoon. To customize the way the time displays, first set the Format property to Custom. Then, in the CustomFormat property, use a combination of the following characters to create a custom format:

Format Used For Description
h Hour for 12-hour basis Used to display the hour with one digit if the value is less than 10
hh Hour for 12-hour basis Used to display the hour with a leading 0 if the value is less than 10
H Hour for 24-hour basis Used to display the hour with one digit if the value is less than 10
HH Hour for 24-hour basis Used to display the hour with a leading 0 if the value is less than 10
m Minute Used to display the minute with one digit if the value is less than 10
mm Minute Used to display the minute with a leading 0 if the value is less than 10
t AM/PM Displays the letter A or P for the AM or PM section
tt AM/PM Displays the letters AM or PM for the last section

You can set the format at design time using the Format field on the Properties window. To set the format at run time, assign the desired format to the DateTimePicker.CustomFormat property.

By default, after adding the control to the form or container, it assumes the time of the computer when the control was added. If you want to set a different time, apply a Format combination to the Value property. In the same way, at any time, you can retrieve the time value on the control by accessing the Value property. 

 

Home Copyright © 2008-2016, FunctionX, Inc.