Home

C++Builder Windows Controls: The Date Picker Control

   

Introduction to the Date/Time Picker Control

 

Description

 

The date and 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 

One of the advantages of the date/time picker 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. By default, the date time picker allows a user to see a date or a time on the control. In most cases, unless the control is disabled, the user can also change the value of the control.

ApplicationApplication: Introducing the Date/Time Picker

  1. Start Embarcadero RAD Studio
  2. To create new application, on the main menu, click File -> New -> VCL Forms Application - C++Builder
  3. In the Object Inspector, change the properties of the form as follows:
    BorderStyle: bsDialog
    Caption: Simple Interest Evaluation
    Name: frmEvaluation
    Position: poScreenCenter

Adding a Date/Time Picker

To support the a date/time picker, the VCL provides a class named TDateTimePicker. The TDateTimePicker class implements the TCommonCalendar class, which is also the parent of the month calendar:

TDateTimePicker Inheritance

To visually create a date time picker, in the Win32 section of the Tool Palette, click the TDateTimePicker icon TDateTimePicker and click a form or other container. As mentioned already, the date/time picker can be considered as two controls in one: you just have to choose which one of both controls you want to use.

ApplicationApplication: Adding a Date Picker

  • Design the form as follows:
     
    Simple Interest
    Control Alignment Text Name
    TGroupBox GroupBox   Loan Preparation  
    TLabel Label   Principal  
    TEdit TextBox taRightJustify 0.00 edtPrincipal
    TLabel Label   Interest Rate:  
    TEdit TextBox taRightJustify 0.00 edtInterestRate
    TLabel Label   %  
    TLabel Label   Loan Start Date:  
    TDateTimePicker DateTimePicker     dtpLoanStartDate
    TLabel Label   Loan End Date:  
    TDateTimePicker DateTimePicker     dtpLoandEndDate
    TLabel Label   Periods:  
    TTEdit TextBox taRightJustify 0 edtPeriods
    TLabel Label   Days  
    TButton Button   Calculate btnCalculate
    TGroupBox GroupBox   Results  
    TLabel Label   Interest Earned:  
    TEdit TextBox taRightJustify 0.00 edtInterestEarned
    TLabel Label   Future Value:  
    TEdit TextBox taRightJustify 0.00 edtFutureValue
    TButton Button   Close btnClose

The Kind of Date/Timer Picker

To let you specify whether you want a date picker or a time picker, the TDateTimePicker class is equipped with a property named Kind, which is of type TDateTimeKind:

__property Comctrls::TDateTimeKind Kind = {read=FKind,write=SetKind};

 The TDateTimeKind enumeration has two members:

enum TDateTimeKind{
	dtkDate,
	dtkTime
};

Introduction to the Date Picker

After adding a date/time picker to a form, to make it a date picker, set the Kind property to dtkDate. You can do this visually using the Object Inspector of the control or programmatically by assigning the desired value to the property.

 
 
 

Characteristics of the Date Picker

 

Using a Date Picker

As its name indicates, the date picker either displays a date or it allows the user to specify a date. The control follows the format of the date values specified in the regional settings of Control Panel. Consequently, the date is made of various sections including the name of the day, the name of the month, the numeric day in the month, and the year.

In a later section, we will see that the date picker can display a combo box or a spin button. If the control is displaying as a combo box, to change the date, the user can click the arrow of the combo box. This would display a month calendar:

Date-Time Picker

When the calendar displays, the control throws an OnDropDown event:

//---------------------------------------------------------------------------
void __fastcall TfrmExercise::DateTimePicker1DropDown(TObject *Sender)
{

}
//---------------------------------------------------------------------------

 The OnDropDown event is of type TNotifyEvent, which means that it doesn't carry any significant information, other than to let you know that the calendar of the control has been dropped to display.

While the calendar is displaying, the user can change the month, change the year, or click a date to select one. This would cause the month calendar to close and the control would display the date that was selected. We will see that there are other ways the user can change the value of the control. However it is done, on the text box or on the calendar, when the date of the control has been changed, the control fires an OnChanged event:

//---------------------------------------------------------------------------
void __fastcall TfrmExercise::DateTimePicker1Change(TObject *Sender)
{

}
//---------------------------------------------------------------------------

 The OnChanged event, which is the default event of the control, is of type TNotifyEvent, meaning it does not give you any detail about the date that was selected or about anything the user did. You would use your own means of finding out what date the user had selected or specified. This can easily be done by getting the Value property of the control.

If the control is displaying a calendar, once the user clicks a date, the calendar disappears and the control becomes a combo box again. When the calendar retracts, the control fires an OnCloseUp event:

//---------------------------------------------------------------------------
void __fastcall TfrmExercise::DateTimePicker1CloseUp(TObject *Sender)
{

}
//---------------------------------------------------------------------------

The OnCloseUp event is of type TNotifyEvent, which means it does not carry any particular information other than letting you know that the calendar has been closed.

ApplicationApplication: Using the Date Picker Control

  1. On the form, click the bottom date picker (the End Loan Date control)
  2. In the Object Inspector, click the Events tab
  3. Double-click the box on the right side of OnCloseUp to generate its event
  4. Implement the event as follows:
    //---------------------------------------------------------------------------
    void __fastcall TfrmEvaluation::dtpLoanEndDateCloseUp(TObject *Sender)
    {
        double Principal = 0.00, InterestRate = 0.00, Periods = 0.00;
        double InterestEarned, FutureValue;
        TDateTime StartDate, EndDate;
        int Days;
    
        // Get the value of the principal
        try {
    	   Principal = edtPrincipal->Text.ToDouble();
        }
        catch(EConvertError *)
        {
    	ShowMessage(L"Invalid Principal Value");
        }
    
        // Get the interest rate
        try {
            InterestRate  = edtInterestRate->Text.ToDouble() / 100;
        }
        catch(EConvertError *)
        {
    	ShowMessage(L"Invalid Interest Rate");
        }
    
        // Get the start and end dates
        StartDate = dtpLoanStartDate->Date;
        EndDate = dtpLoanEndDate->Date;
    
        // Make sure the end date doesn't occur before the start date
        if(EndDate < StartDate)
        {
    	ShowMessage(L"Invalid Date Sequence: "
    	 	    L"the end date must occur after the start date");
    	dtpLoanEndDate->Date = Date();
    	return;
        }
    
        // Get the difference in days
        // The will be the periods
        Days = EndDate - StartDate;
        edtDays->Text = Days;
        double p = 0.00;
    
        // Because we will allow the user to directly specify
        // the number of days, let's get the period from its text box
        try {
    	p = edtDays->Text.ToDouble();
        }
        catch (EConvertError *)
        {
    	ShowMessage(L"Invalid number of days");
        }
    
        // The actual period is gotten as follows
        Periods = p / 365;
        // Now we can perform the calculations
        InterestEarned = Principal * InterestRate * Periods;
        FutureValue = Principal + InterestEarned;
    
        // Display the values
        edtInterestEarned->Text = FloatToStrF(InterestEarned, ffCurrency, 8, 2);
        edtFutureValue->Text    = FloatToStrF(FutureValue, ffCurrency, 8, 2);
    }
    //---------------------------------------------------------------------------
  5. Press F12 to return to the form
  6. Click the Periods edit box
  7. On the Object Inspector, click Events
  8. Double-click the right side of OnExit
  9. Implement the event as follows:
    //---------------------------------------------------------------------------
    void __fastcall TfrmEvaluation::edtDaysExit(TObject *Sender)
    {
    	dtpLoanEndDateCloseUp(Sender);
    }
    //---------------------------------------------------------------------------
  10. Press F12 to return to the form
  11. Double-click the Close button
  12. Implement the event as follows:
    //---------------------------------------------------------------------------
    void __fastcall TfrmEvaluation::btnCloseClick(TObject *Sender)
    {
    	Close();
    }
    //---------------------------------------------------------------------------
  13. Press F12 to return to the form
  14. In the Object Inspector, click the Properties tab
  15. Press F9 to execute the application
     
    Simple Interest
  16. Close the form and return to your programming environment

The Format of a Date/Time Picker

The date picker supports two categories of date values, referred to as long date format and short date format. They are defined in the Region and Language section of the Control Panel:

Region and Language

You can also get the categories in the Date section of the Customize Format dialog box:

Customize Format

To support the type of date, the TDateTimeFormat class is equipped with a UnicodeString property named DateFormat that is of type TDTDateFormat:

__property Comctrls::TDTDateFormat DateFormat = {read=FDateFormat,write=SetDateFormat};

The TDTDateFormat enumeration is defined as follows:

enum TDTDateFormat{
	dfShort,
	dfLong
};

To make the control display long date formats, specify its DateFormat property as dfLong. For a short date format, set the property to dfShort.

ApplicationApplication: Setting the Date Format

  1. On the form, click the top date picker control
  2. In the Object Inspector, click DateFormat, then click the arrow of its combo box and select dfLong
  3. In the same way, on the form, click the second date picker
  4. In the Object Inspector, double-click DateFormat to change its value to dfLong

The Spin Button

After adding a date time picker control and setting its DateFormat property to either dfLong (the default) or dfShort, the control becomes a combo box (the default):

Date-Time Picker

 

We saw already how the user can select a date using the combo box. If you don't like the combo box, you can display a spin button instead. The ability to display a combo box or a spin button is controlled by a property named DateMode that is of type TDTDateMode:

__property Comctrls::TDTDateMode DateMode = {read=FDateMode,write=SetDateMode};

The TDTDateMode enumeration has two members:

enum TDTDateMode{
	dmComboBox,
	dmUpDown
};

The default value is dmComboBox. If you want the control to display a spin button, set its DateMode property to dmUpDown:

Date Picker

If the control is displaying a spin button, to change a part of the value, such as the day, the month, or the year, the user must click that part, and it becomes highlighted:

  •  The user can type a value
  • The user can click the arrows of the spin button to change the value
  • The user can press the up or down keys on the keyboard to increase or decrease the value

In reality, the ability to change the value of a section works also if the control is displaying a combo box.

The Check Box

In some cases, you may want to decide when to allow the user to select a date or when to disable it. There are two ways you can do. You can use the TControl's Enabled property that all Windows controls inherit. Another technique you can use is to display a check box on the left side of the text box section of the control. The presence or absence of the check box is controlled by the ShowCheckBox Boolean property:

__property bool ShowCheckbox = {read=FShowCheckbox,write=SetShowCheckbox};

The default value of the ShowCheckBox property is False. If you set it to True, a check box appears:

Date Picker

If the check box is checked, the user can change the displayed date. If the check box is unchecked, the label that displays the value of the control is disabled (the label or value, not the control itself):

  • If the control is displaying a combo box:
    • The user cannot click a section to change its value because the label that shows the date is disabled
    • To change the value, the user can click the arrow of the combox. This would enable the value. The user can then select from the month calendar
  •  If the control is displaying a spin button, since the label that holds the value of the control is disabled, the user cannot change the value of the control

Since the ShowCheckBox property is read-write, you can also use it to find out whether the control is currently equipped with a check box.

The Calendar Visual Characteristics

If the date picker control displays like a combo box, as mentioned already, if the user clicks the arrow button, a calendar appears. The calendar shares the same functionality and characteristics as the month calendar control. The colors are managed by the CalColors property that is based on the properties of the TMonthCalColors class:

  • The background color of the title bar is represented by the TitleBackColor property
  • The color of the text on the calendar is handled by the TextColor property
  • The background color of the calendar is set by the BackColor property
  • The background color of the current month of the calendar is set by the MonthBackColor property
  • The font color of the title bar is controlled by the TitleTextColor property
  • The minimum and the maximum dates are specified using the MinDate and the MaxDate properties
  • The color of the days of the trailing months is held by the TrailingTextColor property

ApplicationApplication: Coloring the Month Calendar Control

  1. On the form, click the top date picker control
  2. In the Object Inspector, click the + button of CalColors
  3. Change the following values:
    BackColor: clGradientActiveCaption
    MonthBackColor: clSkyBlue
    TextColor: clBlue
    TitleBackColor: clNavy
    TitleTextColor: clCream
    TrailingTextColor: clYellow
  4. Double-click an unoccupied area of the form to generate its OnCreate event
  5. Implement the event as follows:
    //---------------------------------------------------------------------------
    void __fastcall TfrmEvaluation::FormCreate(TObject *Sender)
    {
    	dtpLoanEndDate->CalColors->BackColor = RGB(155, 50, 0);
    	dtpLoanEndDate->CalColors->MonthBackColor = RGB(255, 165, 65);
    	dtpLoanEndDate->CalColors->TextColor = RGB(128, 0, 0);
    	dtpLoanEndDate->CalColors->TitleBackColor = RGB(190, 95, 0);
    	dtpLoanEndDate->CalColors->TitleTextColor = RGB(255, 255, 0);
    	dtpLoanEndDate->CalColors->TrailingTextColor = RGB(128, 128, 128);
    }
    //---------------------------------------------------------------------------
  6. To execute the application, on the main menu, click Run -> Run
     
    Simple Interest
    Simple Interest
    Simple Interest
  7. Close the form and return to your programming environment

The Alignment of the Calendar

This calendar displays to the bottom-left or the bottom-right side of the combo box. To control this alignment, change the value of the CalAlignment property that is of type TDTCalAlignment:

__property Comctrls::TDTCalAlignment CalAlignment = 
{
    read=FCalAlignment,
    write=SetCalAlignment
};

The TDTCalAlignment enumeration is defined as follows:

enum TDTCalAlignment{
	dtaLeft,
	dtaRight
};

The default value of the CalAlignment property is dtaLeft. value is dtaRight.

The Minimum and the Maximum Dates

If you want to control the range of dates the user can select, use the MinDate and the MaxDate properties of the TCommonCalendar class.

The Value of the Calendar

When you add the date time picker control to your form or container, it displays the date of the computer at the time the control was added. If you want the control to display a different date, set the desired value in the Date field of the Object Inspector. At any time, you can find out what value the date picker has by retrieving the value of the Date property.

The Custom Format of the Calendar

If you set the DateFormat property to dfLong, the date displays using the Long Date formats of Control Panel. If you set the DateFormat value to dfShort, the control uses the Short Date value of Control Panel. To let you customize the way the date is displayed, the TDateTimePicker class is equipped with a string property named Format:

__property System::UnicodeString Format = {read=FFormat,write=SetFormat};

Use this property create a custom format. The format is created by combining the following characters:

Format Used For Description
d Days Displays the day as a number from 1 to 31
dd Days Displays the day as a number with a leading 0 if the number is less than 10
ddd Weekdays Displays a weekday name with 3 letters as Mon, Tue, etc
dddd Weekdays Displays the complete name of a week day as Monday, etc
M Months Displays the numeric month from 1 to 12
MM Months Displays the numeric month with a leading 0 if the number is less than 10
MMM Months Displays the short name of the month as Jan, Feb, Mar, etc
MMMM Months Displays the complete name of the month as January, etc
yy Years Displays two digits for the year as 00 for 2000 or 03 for 2003
yyyy Years Displays the numeric year with 4 digits

This means that you should be reluctant to let the users type whatever they want. The less they type, the less checking you need to do.

 
 
   
 

Home Copyright © 2010-2016, FunctionX