在Delphi XE中如何使用TComboBox作为单元格编辑器,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes,
Vcl.Controls, Vcl.Forms, Vcl.StdCtrls, Vcl.Grids,
//必须将重定义的TStringGrid单元引用放置在Vcl.Grids之后
Unit2;
type
TForm1 = class(TForm)
StringGrid1: TStringGrid;
procedure FormCreate(Sender: TObject);
procedure StringGrid1SelectCell(Sender: TObject; ACol, ARow: Integer;
var CanSelect: Boolean);
private
FComboBox: TComboBox;
procedure OnComboBoxChange(Sender: TObject);
procedure OnComboBoxExit(Sender: TObject);
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
//创建ComboBox,也可以直接拖拽到Form
//此处只需要设置Parent := StringGrid1
FComboBox := TComboBox.Create(StringGrid1);
FComboBox.Parent := StringGrid1;
FComboBox.Items.Add('Item1');
FComboBox.Items.Add('Item2');
FComboBox.OnChange := OnComboBoxChange;
FComboBox.OnExit := OnComboBoxExit;
FComboBox.Visible := False;
//ComboBox高度是固定不能改变的
//因此设置StringGrid1的行高与ComboBox高度一致
StringGrid1.DefaultRowHeight := FComboBox.Height;
end;
procedure TForm1.OnComboBoxChange(Sender: TObject);
begin
StringGrid1.Cells[StringGrid1.Col, StringGrid1.Row] := FComboBox.Text;
end;
procedure TForm1.OnComboBoxExit(Sender: TObject);
begin
FComboBox.Visible := False;
end;
procedure TForm1.StringGrid1SelectCell(Sender: TObject; ACol, ARow: Integer;
var CanSelect: Boolean);
var
ARect: TRect;
begin
//示例代码仅在第二列中使用ComboBox作为编辑器
if CanSelect and (ACol = 1) then
begin
FComboBox.ItemIndex := FComboBox.Items.IndexOf
(StringGrid1.Cells[ACol, ARow]);
//使ComboBox显示并覆盖住选中单元格
ARect := StringGrid1.CellRect(ACol, ARow);
FComboBox.Left := ARect.Left;
FComboBox.Top := ARect.Top;
FComboBox.Width := ARect.Right - ARect.Left;
FComboBox.Visible := True;
FComboBox.SetFocus;
end;
end;
end.
unit Unit2;
interface
uses
Vcl.Grids, Winapi.Windows, Winapi.Messages, Vcl.Controls;
type
TStringGrid = class(Vcl.Grids.TStringGrid)
private
procedure WMCommand(var AMessage: TWMCommand); message WM_COMMAND;
end;
implementation
{ TStringGrid }
procedure TStringGrid.WMCommand(var AMessage: TWMCommand);
begin
//如果当前是StringGrid内置编辑框,调用父类方法
//否则向控件发送CN_COMMAND事件
if (InplaceEditor <> nil) and (AMessage.Ctl = InplaceEditor.Handle) then
inherited
else if AMessage.Ctl <> 0 then
begin
AMessage.Result := SendMessage(AMessage.Ctl, CN_COMMAND,
TMessage(AMessage).WParam, TMessage(AMessage).LParam);
end;
end;
end.