Home

Windows Controls: The Time Picker

Introduction to the Time Picker

Description

The time picker is a control that allows the user to select a time value:

 Date/Time Picker

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

Creating a Date/Time Picker

To create a time picker, add a DateTimePicker control DateTimePicker to a form or other container. The DateTimePicker control is based on the DateTimePicker class. 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 Time Picker

Overview

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:

using System;
using System.Drawing;
using System.Windows.Forms;

public class Exercise : System.Windows.Forms.Form
{
    DateTimePicker dtpTimeArrived;

    public Exercise()
    {
        InitializeComponent();
    }

    void InitializeComponent()
    {
        dtpTimeArrived = new DateTimePicker();
        dtpTimeArrived.Location = new Point(12, 12);
        dtpTimeArrived.Format = DateTimePickerFormat.Time;

        Controls.Add(dtpTimeArrived);
        Text = "Time Picker";
    }
}

public class Program
{
    static int Main()
    {
        System.Windows.Forms.Application.Run(new Exercise());
        return 0;
    }
}

Although optional, you should (with emphasis) also set the ShowUpDown Boolean property to True:

 void InitializeComponent()
{
    dtpTimeArrived = new DateTimePicker();
    dtpTimeArrived.Location = new Point(12, 12);
    dtpTimeArrived.ShowUpDown = true;
    dtpTimeArrived.Format = DateTimePickerFormat.Time;
}

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, 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. 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  
  3. Save the form

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 value 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. Here is an example of using it:

using System;
using System.Drawing;
using System.Windows.Forms;

public class Exercise : System.Windows.Forms.Form
{
    DateTimePicker dtpTimeArrived;

    public Exercise()
    {
        InitializeComponent();
    }

    void InitializeComponent()
    {
        dtpTimeArrived = new DateTimePicker();
        dtpTimeArrived.Location = new Point(12, 12);
        dtpTimeArrived.ShowUpDown = true;
        dtpTimeArrived.Format = DateTimePickerFormat.Time;
        dtpTimeArrived.ValueChanged += new EventHandler(dtpTimeArrivedValueChanged);

        Controls.Add(dtpTimeArrived);
        Text = "Date Time Picker Example";
    }

    void dtpTimeArrivedValueChanged(object sender, EventArgs e)
    {

    }
}

public class Program
{
    static int Main()
    {
        System.Windows.Forms.Application.Run(new Exercise());
        return 0;
    }
}

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

Here is an example of using it:

void dtpTimeArrivedValueChanged(object sender, EventArgs e)
{
    MessageBox.Show("Time Arrived: " + dtpTimeArrived.Value.ToShortTimeString());
}

ApplicationApplication: Using the Time Picker

  1. On the form, double-click the Time Left control and implement its ValueChanged event as follows:
    private void dtpTimeLeft_ValueChanged(object sender, EventArgs e)
    {
        DateTime dateLeft = this.dtpDateLeft.Value;
        DateTime timeLeft = this.dtpTimeLeft.Value;
    
        DateTime time9AM = new DateTime(timeLeft.Year, timeLeft.Month, timeLeft.Day, 9, 0, 0);
    
        // If the customer leaves clothes before 9AM...
        if (timeLeft <= time9AM)
        {
            // ... then they should be ready the same day after 5PM
            this.dtpDateExpected.Value = dateLeft;
            this.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
            this.dtpDateExpected.Value = new DateTime(dateLeft.Year, dateLeft.Month, dateLeft.Day + 1);
            this.dtpTimeExpected.Value = new DateTime(dateLeft.Year, dateLeft.Month, dateLeft.Day + 1, 8, 0, 0);
        }
    }
  2. Return to the form and double-click the Calculate button
  3. Implement its event as follows:
    private void btnCalculate_Click(object sender, EventArgs e)
    {
                decimal unitPriceShirts = 0.00M, unitPricePants = 0.00M,
                        unitPriceItem1 = 0.00M, unitPriceItem2 = 0.00M,
                        unitPriceItem3 = 0.00M, unitPriceItem4 = 0.00M;
                decimal subTotalShirts = 0.00M, subTotalPants = 0.00M,
                        subTotalItem1 = 0.00M, subTotalItem2 = 0.00M,
                        subTotalItem3 = 0.00M, subTotalItem4 = 0.00M;
                int qtyShirts = 1, qtyPants = 1, qtyItem1 = 1,
                    qtyItem2 = 1, qtyItem3 = 1, qtyItem4 = 4;
                decimal cleaningTotal = 0.00M, taxRate = 0.00M,
                        taxAmount = 0.00M, netPrice = 0.00M;
    
                // Retrieve the unit price of this item
                // Just in case the user types an invalid value, we are using a try...catch
                try
                {
                    unitPriceShirts = decimal.Parse(this.txtUnitPriceShirts.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("The value you entered for the price of shirts is not valid" +
                                    "\nPlease try again");
                    return;
                }
    
                // Retrieve the number of this item
                // Just in case the user types an invalid value, we are using a try...catch
                try
                {
                    qtyShirts = int.Parse(this.txtQuantityShirts.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("The value you entered for the number of shirts is not valid" +
                                    "\nPlease try again");
                    return;
                }
                try
                {
                    unitPricePants = decimal.Parse(this.txtUnitPricePants.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("The value you entered for the price of pants is not valid" +
                                    "\nPlease try again");
                    return;
                }
    
                try
                {
                    qtyPants = int.Parse(this.txtQuantityPants.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("The value you entered for the number of pants is not valid" +
                                    "\nPlease try again");
                    return;
                }
    
                if ((cbxItem1.Text == "None") || (cbxItem1.Text == ""))
                {
                    qtyItem1 = 0;
                    unitPriceItem1 = 0.00M;
                }
                else
                {
                    try
                    {
                        unitPriceItem1 = decimal.Parse(this.txtUnitPriceItem1.Text);
                    }
                    catch (FormatException)
                    {
                        MessageBox.Show("The value you entered for the price is not valid" +
                                    "\nPlease try again");
                        return;
                    }
                
                    try
                    {
                        qtyItem1 = int.Parse(this.txtQuantityItem1.Text);
                    }
                    catch (FormatException)
                    {
                        MessageBox.Show("The value you entered is not valid" +
                                "\nPlease try again");
                        return;
                    }
                }
    
                if ((cbxItem2.Text == "None") || (cbxItem2.Text == ""))
                {
                    qtyItem2 = 0;
                    unitPriceItem2 = 0.00M;
                }
                else
                {
                    try
                    {
                        unitPriceItem2 = decimal.Parse(this.txtUnitPriceItem2.Text);
                    }
                    catch (FormatException)
                    {
                        MessageBox.Show("The value you entered for the price is not valid" +
                                "\nPlease try again");
                        return;
                    }
                    try
                    {
                        qtyItem2 = int.Parse(this.txtQuantityItem2.Text);
                    }
                    catch (FormatException)
                    {
                        MessageBox.Show("The value you entered is not valid" +
                                "\nPlease try again");
                        return;
                    }
                }
    
                if ((cbxItem3.Text == "None") || (cbxItem3.Text == ""))
                {
                    qtyItem3 = 0;
                    unitPriceItem3 = 0.00M;
                }
                else
                {
                    try
                    {
                        unitPriceItem3 = decimal.Parse(this.txtUnitPriceItem3.Text);
                    }
                    catch (FormatException)
                    {
                        MessageBox.Show("The value you entered for the price is not valid" +
                                "\nPlease try again");
                        return;
                    }
                    try
                    {
                        qtyItem3 = int.Parse(this.txtQuantityItem3.Text);
                    }
                    catch (FormatException)
                    {
                        MessageBox.Show("The value you entered is not valid" +
                                "\nPlease try again");
                        return;
                    }
                }
    
                if ((cbxItem4.Text == "None") || (cbxItem4.Text == ""))
                {
                    qtyItem4 = 0;
                    unitPriceItem4 = 0.00M;
                }
                else
                {
                    try
                    {
                        unitPriceItem4 = decimal.Parse(this.txtUnitPriceItem4.Text);
                    }
                    catch (FormatException)
                    {
                        MessageBox.Show("The value you entered for the price is not valid" +
                                "\nPlease try again");
                        return;
                    }
                    try
                    {
                        qtyItem4 = int.Parse(this.txtQuantityItem4.Text);
                    }
                    catch (FormatException)
                    {
                        MessageBox.Show("The value you entered is not valid" +
                                "\nPlease try again");
                        return;
                    }
                }
    
                // Calculate the sub-total for this item
                subTotalShirts = qtyShirts * unitPriceShirts;
                subTotalPants = qtyPants * unitPricePants;
                subTotalItem1 = qtyItem1 * unitPriceItem1;
                subTotalItem2 = qtyItem2 * unitPriceItem2;
                subTotalItem3 = qtyItem3 * unitPriceItem3;
                subTotalItem4 = qtyItem4 * unitPriceItem4;
    
                // Calculate the total based on sub-totals
                cleaningTotal = subTotalShirts + subTotalPants + subTotalItem1 +
                        subTotalItem2 + subTotalItem3 + subTotalItem4;
    
                taxRate = decimal.Parse(this.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 = subTotalShirts.ToString("F");
                txtSubTotalPants.Text = subTotalPants.ToString("F");
                txtSubTotalItem1.Text = subTotalItem1.ToString("F");
                txtSubTotalItem2.Text = subTotalItem2.ToString("F");
                txtSubTotalItem3.Text = subTotalItem3.ToString("F");
                txtSubTotalItem4.Text = subTotalItem4.ToString("F");
    
                txtCleaningTotal.Text = cleaningTotal.ToString("F");
                txtTaxAmount.Text = taxAmount.ToString("F");
                txtNetPrice.Text = netPrice.ToString("F");	
    }
  4. Return to the form
  5. Double-click the Close button and implement its Click event as follows:
    private void btnClose_Click(object sender, EventArgs e)
    {
    	Close();
    }
  6. Execute the application and create a few orders
     
    Georgetown Cleaning Services
  7. 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. Here is an example:

using System;
using System.Drawing;
using System.Windows.Forms;

public class Exercise : System.Windows.Forms.Form
{
    DateTimePicker dtpTimeArrived;

    public Exercise()
    {
        InitializeComponent();
    }

    void InitializeComponent()
    {
        dtpTimeArrived = new DateTimePicker();
        dtpTimeArrived.Location = new Point(40, 12);
        dtpTimeArrived.ShowUpDown = true;
        dtpTimeArrived.Format = DateTimePickerFormat.Custom;
        dtpTimeArrived.CustomFormat = "hh:mm tt";

        Controls.Add(dtpTimeArrived);
        Text = "Time Picker Example";
    }
}

public class Program
{
    static int Main()
    {
        System.Windows.Forms.Application.Run(new Exercise());
        return 0;
    }
}
Time Picker

In the same way, at any time, you can retrieve the time value on the control by accessing the Value property.


Home Copyright © 2010-2020, FunctionX