4、 DrawDataCell事件是繪制單元格,當獲得焦點網格所對應的字段與組合框所對應的字段一致時,移動組合框到獲得焦點的網格上,并且 使組合框可視,從而達到在DBGrid指定列上顯示DBComboBox的功能。設置DBGrid1的OnDrawDataCell事件如下: procedure TForm1.DBGrid1DrawDataCell(Sender: TObject; const Rect: TRect; Field: TField; State: TGridDrawState); begin if (gdFocused in State) then begin if (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; end;
5、 DBGrid指定單元格未獲得焦點時不顯示DBComboBox,設置DBGrid1的OnColExit事件如下: procedure TForm1.DBGrid1ColExit(Sender: TObject); begin If DBGrid1.SelectedField.FieldName = DBComboBox1.DataField then begin DBComboBox1.Visible := false; end; end;
6、 當DBGrid指定列獲得焦點時DrawDataCell事件只是繪制單元格,并顯示DBComboBox,但是DBComboBox并沒有獲得焦點,數據的輸入還是在單元格上進行。在DBGrid1的KeyPress事件中調用SendMessage這個 Windows API函數將數據輸入傳輸到DBComboBox上,從而達到在DBComboBox上進行數據輸入。因此還要設置KeyPress事件如下: procedure TForm1.DBGrid1KeyPress(Sender: TObject; var Key: Char); begin if (key < > chr(9)) then begin if (DBGrid1.SelectedField.FieldName =DBComboBox1.DataField) then begin DBComboBox1.SetFocus; SendMessage(DBComboBox1.Handle, WM_Char, Word(Key), 0); end; end; end;