Mirror

Sort rows in a TStringGrid (Views: 100)


Problem/Question/Abstract:

How to sort rows in a TStringGrid

Answer:

type
  TMoveSG = class(TCustomGrid); {reveals protected MoveRow procedure}

procedure SortGridByCols(Grid: TStringGrid; ColOrder: array of integer);
var
  i, j: integer;
  Sorted: boolean;

  function Sort(Row1, Row2: integer): integer;
  var
    C: integer;
  begin
    C := 0;
    result := AnsiCompareStr(Grid.Cols[ColOrder[C]][Row1],
      Grid.Cols[ColOrder[C]][Row2]);
    if result = 0 then
    begin
      Inc(C);
      while (C <= High(ColOrder)) and (result = 0) do
      begin
        result := AnsiCompareStr(Grid.Cols[ColOrder[C]][Row1],
          Grid.Cols[ColOrder[C]][Row2]);
        Inc(C);
      end;
    end;
  end;

begin
  if SizeOf(ColOrder) div SizeOf(i) <> Grid.ColCount then
    exit;
  for i := 0 to High(ColOrder) do
    if (ColOrder[i] < 0) or (ColOrder[i] >= Grid.ColCount) then
      exit;
  j := 0;
  Sorted := false;
  repeat
    inc(j);
    with Grid do
      for i := 0 to RowCount - 2 do
        if Sort(i, i + 1) > 0 then
        begin
          TMoveSG(Grid).MoveRow(i + 1, i);
          Sorted := false;
        end;
  until
    Sorted or (j = 1000);
  Grid.Repaint;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  c, r: integer;
begin
  {just fills with random numbers for example}
  for r := 0 to StringGrid1.RowCount - 1 do
  begin
    for c := 0 to StringGrid1.ColCount - 1 do
    begin
      StringGrid1.Cols[c][r] := Format('%.3d', [Random(255)]);
    end;
  end;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  {example}
  SortGridByCols(StringGrid1, [1, 0, 2, 3, 4]);
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  Randomize;
end;

<< Back to main page