Search code examples
delphitdatetimepicker

Trigger enable TButton with the pick of two (2) dates in TDateTimePickers


I have TButton set "not enabled" that should be triggered enabled by the two (2) TDateTimePickers when both dates are picked.

My TDateTimePicker dates are defaulted at a now() date. So, at OnChange, I created the following codes and I couldn't get it right:

procedure TfrmPayroll.EnableButton; //my created procedure
begin
  if (dtpFrom.Date = Now()) and
     (dtpTo.Date = Now()) then
  begin
    btnOpen.Enabled := False;
  end
  else
  begin
    btnOpen.Enabled := True;
  end;

The result is TButton is enabled even if I only picked one date of the 2 conditions I set.


Solution

  • Your code requires both DTPs to be set to Now in order to disable the Button, rather than either DTP being Now.

    To fix your existing code, use the or operator instead of the and operator:

    procedure TfrmPayroll.EnableButton;
    begin
      if (dtpFrom.Date = Now()) or
         (dtpTo.Date = Now()) then
      begin
        btnOpen.Enabled := False;
      end else begin
        btnOpen.Enabled := True;
      end;
    end;
    

    Which can then be simplified if you rewrite the condition to use the <> operator instead of the = operator:

    procedure TfrmPayroll.EnableButton;
    begin
      btnOpen.Enabled := (dtpFrom.Date <> Now()) and (dtpTo.Date <> Now());
    end;
    

    And FYI, you should be using Date() instead of Now() since the TDateTimePicker.Date property is not supposed to include time, but Now() does. And you should be using a local variable to avoid a race condition if the local clock changes date between the two Date() calls:

    uses
     ..., DateUtils;
    
    procedure TfrmPayroll.EnableButton;
    var
      CurrentDate: TDate;
    begin
      CurrentDate := Date();
      btnOpen.Enabled := (DateOf(dtpFrom.Date) <> CurrentDate) and (DateOf(dtpTo.Date) <> CurrentDate);
    end;