Archive for the ‘datetimepicker’ category

Force TDateTimePicker to drop down

August 30, 2007

Unfortunately there’s no message to send to TDateTimePicker which would cause it to drop down the calendar. Since the picker is designed to drop down by pressing either F4 or Alt-Down arrow, one can mimic the keypress and get the desired result with the following code:

  ...
  DateTimePicker1.Perform(WM_KEYDOWN, VK_F4, 0);
  DateTimePicker1.Perform(WM_KEYUP, VK_F4, 0);
  ...

TDateTimePicker and NULL dates

September 6, 2006

Using TDateTimePicker control with database can be a PITA. The main problem is that <NULL> dates are shown as 30.12.1899 and after posting changes to DB, the same date will appear in the DB as well. Here’s a hack I did using an empty TComboBox.

Hide the TDateTimePicker with <NULL> dates:

procedure TForm1.DisplayData;
begin
  ..
  if DataModule1.IBDataset1.FieldByName('DateColum').IsNull then
    ComboBox1.BringToFront()
  else begin
    ComboBox1.SendToBack();
    DateTimePicker1.Date :=
      DataModule1.IBDataset1.FieldByName('DateColumn').AsDateTime;
  end;
  ..
end;

In the OnEnter event handler hide the hack TComboBox and make the TDateTimePicker as the active control:

procedure TForm1.ComboBox1Enter(Sender: TObject);
  Combobox1.SendToBack();
  ActiveControl := DateTimePicker1;
end;

Let the OnEnter event handler to handle OnChange and OnClick events as well.

Now that we have TDateTimePicker visible, user can change a date and we must save it to database using the OnChange event handler:

procedure TForm1.DateTimePicker1Change(Sender: TObject);
begin
  DataModule1.IBDataSet1.FieldByName('DateColumn').AsDateTime :=
    StrToDate(DateToStr(DateTimePicker1.Date));
end;

And of course we want to clear the date in DB as well and we will do this in TDateTimePicker’s OnKeyDown event handler by cathring the Delete-key:

procedure TForm1.DateTimePicker1KeyDown(Sender: TObject;
  var Key: Word; Shift: TShiftState);
begin
  if Key = vk_Delete then begin
    DataModule1.IBDataSet1.FieldByName('DateColum').Clear();
    ComboBox1.BringToFront();
    // move control away from here
    ActiveControl := NextControlInTheForm;
  end;
end;