Search code examples
delphidelphi-2010datetimepicker

How can my program react to changes in a TDateTimePicker?


I would like to know how to change a label's caption when the user chooses a particular date from the TDateTimePicker component.

Say for example: If 06/02/2012 was marked on the TDateTimePicker component, label1's caption would become 'Hello World' otherwise nothing would happen if it was any other date.


Solution

  • You need to write an OnChange event handler for the date time picker. You will also need to make sure that this event handler is run when the form first shows:

    procedure TForm1.UpdateDateTimeLabel;
    var
      SelectedDate, SpecialDate: TDateTime;
    begin
      SelectedDate := DateTimePicker1.DateTime;
      SpecialDate := EncodeDate(2012, 2, 16);
      if IsSameDay(SelectedDate, SpecialDate) then
        Label1.Caption := 'Hello World'
      else
        Label1.Caption := '';
    end;
    
    procedure TForm1.DateTimePicker1Change(Sender: TObject);
    begin
      UpdateDateTimeLabel;
    end;
    
    procedure TForm1.FormShow(Sender: TObject);
    begin
      UpdateDateTimeLabel;
    end;