본문 바로가기

카테고리 없음

[일반/컴포넌트] StringGrid의 모든 Cell 선택/해제하기

unit Unit1;

interface

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

type
  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    StringGrid1: TStringGrid;
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure StringGridSelectAll(SG: TStringGrid; Select: Boolean);
var
  SelectedRectangle: TGridRect;
  CoordTopLeft, CoordBottomRight: TGridCoord;
begin
  if not Select then
  begin
    // 선택된 Cell들을 전부 선택취소 시킨다
    SG.Selection := TGridRect(Rect(-1, -1, -1, -1));
    Exit;
  end;  

  with SG do
  begin
    CoordTopLeft.X:= SG.FixedCols; // 첫번째 컬럼부터 선택
    CoordTopLeft.Y:= SG.FixedRows; // 첫번째 행부터 선택
    CoordBottomRight.X:= SG.RowCount - SG.FixedRows; // 마지막 컬럼
    CoordBottomRight.Y:= SG.ColCount - SG.FixedCols; // 마지막 행

    // 직사각형 영역을 TGridRect 에 할당한다
    SelectedRectangle.TopLeft     := CoordTopLeft;
    SelectedRectangle.BottomRight := CoordBottomRight;

    SG.Selection:= SelectedRectangle;
  end;
end;


procedure TForm1.FormCreate(Sender: TObject);
var
  i, j: Integer;
begin
  // Column의 title을 만든다
  for i := 1 to StringGrid1.ColCount - 1 do
   StringGrid1.Cells[i, 0] := Char(Ord('A')+i-1);

  // Row의 title을 만든다
  for i := 1 to StringGrid1.RowCount - 1 do
   StringGrid1.Cells[0, i] := IntToStr(i);;

  // 임의의 자료를 만들어서 각 cell에 입력합니다
  for i := 1 to StringGrid1.ColCount - 1 do
    for j := 1 to StringGrid1.RowCount - 1 do
      StringGrid1.Cells[i, j] := Format('%.0n', [i * j * 10000.0]);
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  // 모든 Cell을 선택한다
  StringGridSelectAll(StringGrid1, True);
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  // 선택된 Cell들을 전부 선택취소 시킨다
  StringGridSelectAll(StringGrid1, False);
end;

end.