본문 바로가기
Delphi Tip/그리드

Delphi 스트링그리드(StringGrid) 정렬

by MonoSoft 2021. 9. 3.
728x90
반응형

Delphi 스트링그리드(StringGrid) 정렬

 

 

 

GridSortSource.zip
0.00MB

 

스트링그리드 컬럼을 선택하면 해당 컬럼으로 정렬됩니다.

 

{ ************** SortGrid ************* }

procedure TForm1.SortGrid(Grid: TStringGrid; SortCol: Integer);

{ A simple exchange sort of grid rows }

var

I, J: Integer;

temp: TStringList;

begin

temp := TStringList.create;

with Grid do

for I := FixedRows to RowCount - 2 do { because last row has no next row }

for J := I + 1 to RowCount - 1 do { from next row to end }

if AnsiCompareText(Cells[SortCol, I], Cells[SortCol, J]) > 0 then

begin

temp.assign(Rows[J]);

Rows[J].assign(Rows[I]);

Rows[I].assign(temp);

end;

temp.free;

end;

 

procedure TForm1.FormCreate(Sender: TObject);

var

I, J: Integer;

totwidth: Integer;

begin

with StringGrid1 do

begin

{ assign some random numbers }

for J := 1 to RowCount - 1 do

for I := 1 to colcount - 1 do

Cells[I, J] := Format('%3d', [Random(1000)]);

 

{ Add row labels }

 

for I := 1 to RowCount - 1 do

Cells[0, I] := 'Row ' + Format('%2d', [I]);

{ Add column labels and change column widths }

totwidth := 0;

for I := 0 to colcount - 1 do

begin

Cells[I, 0] := 'Column ' + IntToStr(I + 1);

{ vary column widths for testing }

Colwidths[I] := DefaultColWidth + Random(48);

Inc(totwidth, Colwidths[I]);

end;

{ adjust grid width so that all column are visible }

Width := totwidth + (colcount + 3) * GridLineWidth;

end;

end;

 

{ ************ StringgridMouseUp ************** }

procedure TForm1.StringGrid1MouseUp(Sender: TObject; Button: TMouseButton;

Shift: TShiftState; X, Y: Integer);

var

c, J: Integer;

rect: TRect;

begin

with StringGrid1 do

if Y < RowHeights[0] then { make sure row 0 was clicked }

begin

for J := 0 to colcount - 1 do { determine which column was clicked }

begin

rect := CellRect(J, 0);

if (rect.Left < X) and (rect.Right > X) then

begin

c := J;

break;

end;

end;

SortGrid(StringGrid1, c);

end;

end;

 

728x90
반응형

댓글