delphi TStringGrid add CheckBox

思路:

重载DrawCell函数,根据Cell的值画Checked 和 UnChecked。

重载SelectCell函数,根据指定的列。变为只读然后修改cell的值进行重画。

代码如下:

procedure TForm1.FormCreate(Sender: TObject);
var
i,j : integer;
begin
// 行数和列数
StringGrid1.ColCount := 10;
StringGrid1.RowCount := 10;

// 缺省行高和列宽
StringGrid1.DefaultColWidth := 20;
StringGrid1.DefaultRowHeight := 20;

// 标题行数,标题列数
StringGrid1.FixedCols := 1;
StringGrid1.FixedRows := 1;

// 填充表格
for i := 0 to StringGrid1.ColCount do
begin
for j := 0 to StringGrid1.RowCount do
begin
if (j < 1) or (i < 1) then
StringGrid1.Cells[i,j] := IntToStr(j * StringGrid1.ColCount + i)
else
StringGrid1.Cells[i,j] := IntToStr(random(2));
end;
end;
end;

procedure TForm1.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
var
sg : TStringGrid;
rct : TRect;
begin
if(Sender = nil) then exit;
sg := sender as TStringGrid;

if((ACol >= sg.FixedCols) and (ARow >= sg.FixedRows)) then
begin
rct.Left := (Rect.Right - Rect.Left - 16) div 2 + rect.Left;
rct.Top := (rect.Bottom - rect.top - 16) div 2 + rect.top;
rct.Right := rct.Left + 16;
rct.Bottom := rct.Top + 16;
if sg.Cells[ACol,ARow] = '1' then
DrawFrameControl(sg.Canvas.Handle, rct, DFC_BUTTON, DFCS_BUTTONCHECK or DFCS_CHECKED)
else
DrawFrameControl(sg.Canvas.Handle, rct, DFC_BUTTON, DFCS_BUTTONCHECK);
end;
end;

procedure TForm1.StringGrid1SelectCell(Sender: TObject; ACol,
ARow: Integer; var CanSelect: Boolean);
var
sg : TStringGrid;
begin
sg := sender as TStringGrid;

if (ACol = 2) then
begin
Stringgrid1.Options := Stringgrid1.Options-[goEditing];

if sg.Cells[ACol,ARow] = '1' then
sg.Cells[ACol,ARow] := '0'
else
sg.Cells[ACol,ARow] := '1';
end
else
begin
Stringgrid1.Options := Stringgrid1.Options+[goEditing];
end;
end;

你可能感兴趣的:(delphi TStringGrid add CheckBox)