首页  编辑  

如何编写使StringGrid中的一列具有Check功能,和CheckBox效果一样

Tags: /超级猛料/VCL/Grid控件/   Date Created:
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  Grids;

type
  TForm1 = class(TForm)
    grid: TStringGrid;
    procedure FormCreate(Sender: TObject);
    procedure gridDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect;
      State: TGridDrawState);
    procedure gridClick(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;
  fcheck, fnocheck: tbitmap;

implementation

{$R *.DFM}

procedure TForm1.FormCreate(Sender: TObject);
var
  i: SmallInt;
  bmp: tbitmap;
begin
  fcheck := tbitmap.Create;
  fnocheck := tbitmap.Create;
  bmp := tbitmap.Create;
  try
    bmp.handle := LoadBitmap(0, PChar(OBM_CHECKBOXES));
    With fnocheck Do
    Begin
      width := bmp.width div 4;
      height := bmp.height div 3;
      canvas.copyrect(canvas.cliprect, bmp.canvas, canvas.cliprect);
    End;
    With fcheck Do
    Begin
      width := bmp.width div 4;
      height := bmp.height div 3;
      canvas.copyrect(canvas.cliprect, bmp.canvas,
        Rect(width, 0, 2 * width, height));
    End;
  finally
    bmp.free
  end;
end;

procedure TForm1.gridDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect;
  State: TGridDrawState);
begin
  if not(gdFixed in State) then
    with TStringGrid(Sender).canvas do
    begin
      brush.Color := clWindow;
      FillRect(Rect);
      if grid.Cells[ACol, ARow] = 'yes' then
        Draw((Rect.right + Rect.left - fcheck.width) div 2,
          (Rect.bottom + Rect.top - fcheck.height) div 2, fcheck)
      else
        Draw((Rect.right + Rect.left - fcheck.width) div 2,
          (Rect.bottom + Rect.top - fcheck.height) div 2, fnocheck);
    end;
end;

procedure TForm1.gridClick(Sender: TObject);
begin
  if grid.Cells[grid.col, grid.row] = 'yes' then
    grid.Cells[grid.col, grid.row] := 'no'
  else
    grid.Cells[grid.col, grid.row] := 'yes';
end;

end.