希望以下代码对你有帮助:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Grids;
type
TForm1 = class(TForm)
StringGrid1: TStringGrid;
procedure StringGrid1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure FormCreate(Sender: TObject);
procedure StringGrid1TopLeftChanged(Sender: TObject);
private
{ Private declarations }
public
procedure cbxOnExit(Sender: TObject);// 定义释放Combobox过程
{ Public declarations }
end;
var
Form1: TForm1;
Last_ACol : integer = -1;
Last_ARow : integer = -1;
implementation
{$R *.DFM}
procedure TForm1.cbxOnExit(Sender: TObject); //定义释放Combobox过程
var i : integer;
begin
for i := Form1.ComponentCount -1 downto 0 do
if Form1.Components is TCombobox then
if (Form1.Components as TCombobox).Tag = 100 then
begin
if (Last_ARow <> -1) and (Last_ACol <> -1) then
begin //把combobox的取值赋予格子
StringGrid1.Cells[Last_ACol, Last_ARow]:= (Form1.Components as TCombobox).Text;
end;
(Form1.Components as TCombobox).Free;
StringGrid1.refresh;
end;
end;
procedure TForm1.StringGrid1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
function GetLeft(aCol: Integer): Integer;//获得左边距坐标函数
var ii,jj: integer;
begin
JJ := 1;
for ii := 0 to ACol -1 do
JJ := JJ + StringGrid1.ColWidths[ii]+1;
Result := JJ;
end;
function GetTop(ARow:Integer): Integer; //获得TOP坐标函数
var ii, JJ : integer;
begin
JJ := 1;
for ii := 0 to ARow-1 do
JJ := JJ + StringGrid1.RowHeights[ii]+1;
Result := JJ;
end;
var cbx : TCombobox;
i, J : Integer;
aCol, ARow : Integer;
begin
cbxOnExit(Sender);//释放在本列生成的combobox
j := 1;
ACol := -1;
for i := 0 to StringGrid1.ColCount -1 do
begin
J := J + StringGrid1.ColWidths+1;
if J >= X then
begin
ACol := i;
Break;
end;
end;
J := 1;
ARow := -1;
for i := 0 to StringGrid1.RowCount -1 do
begin
J := J + StringGrid1.RowHeights+1;
if J >= Y then
begin
ARow :=i;
Break;
end;
end;
ACol := ACol + StringGrid1.LeftCol -1; //相对
ARow := ARow + StringGrid1.TopRow -1;
Last_ARow := ARow;
Last_ACol := ACol;
if (ARow = -1) or (ACol=-1) then Exit;
if (ACol = 1) and ( ARow <> 0 ) then //绝对
begin
cbx := TCombobox.Create(Self);
cbx.Parent := form1; //combobox的拥有者是form1;
cbx.Tag := 100; //作窗体元件标志;
cbx.Items.Add('空闲');
cbx.Items.Add('占用');
cbx.Left := StringGrid1.Left + GetLeft(ACol-StringGrid1.LeftCol +1 ) ;
cbx.Top := StringGrid1.Top + GetTop(ARow -StringGrid1.TopRow +1) ;
cbx.Width := StringGrid1.ColWidths[ACol]+ 1;
cbx.Style := csDropDownList;
cbx.ItemIndex := cbx.Items.IndexOf(StringGrid1.Cells[ACol, ARow]);
onExit := cbxOnExit;
cbx.Visible := True;
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
var i :integer;
begin
for i := 0 to StringGrid1.RowCount -1 do
StringGrid1.Cells[0, i] := intToStr(i);
for i := 0 to StringGrid1.ColCount -1 do
StringGrid1.Cells[i, 0] := intToStr(i);
end;
procedure TForm1.StringGrid1TopLeftChanged(Sender: TObject);
begin
cbxOnExit(Sender);
end;
end.