根据  DBGrid中插入DateTimePicker(08)  类似 改编

DBGrid中插入ComboBox1(10)_数据库

 

procedure TForm13.ComboBox1Change(Sender: TObject);   //ComboBox1  写回  数据库
begin
    DBGrid1.DataSource.Edit;
    DBGrid1.Columns[1].Field.Value  := ComboBox1.Items[ComboBox1.ItemIndex ];    //1 为 ComboBox1 所在的列序号
    fdquery1.Post;
end;


procedure TForm13.DBGrid1ColExit(Sender: TObject);
begin
  if DBGrid1.SelectedField.FieldName = 'username' then  ComboBox1.Visible := False;
end;

procedure TForm13.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect;
  DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
  if (gdFocused in State) then
  begin
    if (Column.Field.FieldName = 'username') then
    with ComboBox1 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;

     ComboBox1.ItemIndex  := ComboBox1.Items.IndexOf( Column.Field.Value);  //  从 数据库 中读 并 设置   ComboBox1
      Visible := True;
    end;
  end
end;

procedure TForm13.FormCreate(Sender: TObject);
var
  i: Integer;
  aStringList: Tstringlist;
begin  FDQuery1.Open('select *  from userinfo ');

  aStringList := Tstringlist.Create;
  aStringList.Sorted := True;
  aStringList.Duplicates := dupIgnore;  //去重
  while not FDQuery1.Eof do
  begin
    aStringList.Add(FDQuery1.Fields[1].AsString); // 要从 字典表 中 加载, 这里 只从 数据中 提取
    FDQuery1.next;
  end;
  ComboBox1.Items.Assign(aStringList);
  aStringList.Free;
end;

DBGrid中插入ComboBox1(10)_sed_02