DBGrid中插入DateTimePicker

时间:2021-07-15 22:50:33

DateTimePicker inside a DBGrid  
 
Heres how to place a TDateTimePicker into a DBGrid. Create visually more attractive user interfaces for editing date/time fields inside a DBGrid - place a drop down calendar into a cell of a DBGrid.  

procedure TForm1.DBGrid1DrawColumnCell
  (Sender: TObject; 
   const Rect: TRect; 
   DataCol: Integer; 
   Column: TColumn; 
   State: TGridDrawState);
begin
  if (gdFocused in State) then
  begin
    if (Column.Field.FieldName = DateAdded) then
    with DateTimePicker do 
    begin
      Left := Rect.Left   DBGrid1.Left   1;
      Top := Rect.Top   DBGrid1.Top   1;
      Width := Rect.Right - Rect.Left   2;
      Width := Rect.Right - Rect.Left   2;
      Height := Rect.Bottom - Rect.Top   2;

      Visible := True;
    end;
  end
end;

procedure TForm1.DBGrid1ColExit(Sender: TObject);
begin
  if DBGrid1.SelectedField.FieldName = DateAdded then 
    DateTimePicker.Visible := False
end;

procedure TForm1.DBGrid1KeyPress(Sender: TObject; var Key: Char);
begin
  if (key = Chr(9)) then Exit;

  if (DBGrid1.SelectedField.FieldName = DateAdded) then
  begin
    DateTimePicker.SetFocus;
    SendMessage(DateTimePicker.Handle, WM_Char, word(Key), 0);
  end
end;

procedure TForm1.DateTimePickerChange(Sender: TObject);
begin
  if DBGrid1.DataSource.State in [dsEdit, dsInsert] then
    ADOTable1DateAdded.Value := DateTimePicker.DateTime;
end;

procedure TForm1.DateTimePickerDropDown(Sender: TObject);
begin
  DBGrid1.DataSource.Edit;
end;