Author: Tomas Rutkauskas How to sort rows in a TStringGrid Answer: 1 type 2 TMoveSG = class(TCustomGrid); {reveals protected MoveRow procedure} 3 4 procedure SortGridByCols(Grid: TStringGrid; ColOrder: array of integer); 5 var 6 i, j: integer; 7 Sorted: boolean; 8 9 function Sort(Row1, Row2: integer): integer; 10 var 11 C: integer; 12 begin 13 C := 0; 14 result := AnsiCompareStr(Grid.Cols[ColOrder[C]][Row1], 15 Grid.Cols[ColOrder[C]][Row2]); 16 if result = 0 then 17 begin 18 Inc(C); 19 while (C <= High(ColOrder)) and (result = 0) do 20 begin 21 result := AnsiCompareStr(Grid.Cols[ColOrder[C]][Row1], 22 Grid.Cols[ColOrder[C]][Row2]); 23 Inc(C); 24 end; 25 end; 26 end; 27 28 begin 29 if SizeOf(ColOrder) div SizeOf(i) <> Grid.ColCount then 30 exit; 31 for i := 0 to High(ColOrder) do 32 if (ColOrder[i] < 0) or (ColOrder[i] >= Grid.ColCount) then 33 exit; 34 j := 0; 35 Sorted := false; 36 repeat 37 inc(j); 38 with Grid do 39 for i := 0 to RowCount - 2 do 40 if Sort(i, i + 1) > 0 then 41 begin 42 TMoveSG(Grid).MoveRow(i + 1, i); 43 Sorted := false; 44 end; 45 until 46 Sorted or (j = 1000); 47 Grid.Repaint; 48 end; 49 50 procedure TForm1.Button1Click(Sender: TObject); 51 var 52 c, r: integer; 53 begin 54 {just fills with random numbers for example} 55 for r := 0 to StringGrid1.RowCount - 1 do 56 begin 57 for c := 0 to StringGrid1.ColCount - 1 do 58 begin 59 StringGrid1.Cols[c][r] := Format('%.3d', [Random(255)]); 60 end; 61 end; 62 end; 63 64 procedure TForm1.Button2Click(Sender: TObject); 65 begin 66 {example} 67 SortGridByCols(StringGrid1, [1, 0, 2, 3, 4]); 68 end; 69 70 procedure TForm1.FormCreate(Sender: TObject); 71 begin 72 Randomize; 73 end;