TDBGrid 編輯時實際是在儲存格上浮動一個 TDBEdit。同樣可將任何資料感知元件 (如 TDBComboBox, TDBCheckBox) 浮動至獲得焦點的儲存格,實現就地下拉選擇、核取方塊等功能。
TTable, TDataSource, TDBGrid, TDBComboBox。DBComboBox1.Visible := False (平時隱藏)。DBGrid1.OnDrawDataCell:若焦點欄位 = ComboBox 對應欄位,移動 ComboBox 至儲存格矩形並顯示。DBGrid1.OnColExit:離開該欄位時隱藏 ComboBox。DBGrid1.OnKeyPress:將按鍵訊息轉發給 ComboBox (SendMessage(Handle, WM_CHAR, ...)) 使其接收輸入。
procedure TForm1.DBGrid1DrawDataCell(Sender: TObject; const Rect: TRect; Field: TField; State: TGridDrawState);
begin
if (gdFocused in State) and (Field.FieldName = DBComboBox1.DataField) then
begin
DBComboBox1.Left := Rect.Left + DBGrid1.Left;
DBComboBox1.Top := Rect.Top + DBGrid1.Top;
DBComboBox1.Width := Rect.Right - Rect.Left;
DBComboBox1.Height := Rect.Bottom - Rect.Top;
DBComboBox1.Visible := True;
end;
end;
procedure TForm1.DBGrid1ColExit(Sender: TObject);
begin
if DBGrid1.SelectedField.FieldName = DBComboBox1.DataField then
DBComboBox1.Visible := False;
end;
procedure TForm1.DBGrid1KeyPress(Sender: TObject; var Key: Char);
begin
if (Key <> #9) and (DBGrid1.SelectedField.FieldName = DBComboBox1.DataField) then
begin
DBComboBox1.SetFocus;
SendMessage(DBComboBox1.Handle, WM_CHAR, Word(Key), 0);
end;
end;
Table1.TableName := 'teacher.dbf' (欄位 SEX: '男'/'女')DBComboBox1.DataField := 'SEX'; DataSource := DataSource1; Items := '男|女'; Visible := False同樣手法可嵌入 TDBCheckBox (布林欄位)、TDBDateTimePicker (日期欄位)、甚至自訂對話框 (雙擊儲存格彈出)。