Re: Sort a stringgrid

Posted by Fred Green on November 05, 2007

In Reply to Sort a stringgrid posted by Diana on September 30, 2007

: What's the Delphi source code for sorting a StringGrid component?

There's no ready-made Delphi procedure for this, you'll have to write your own. If there are not too may rows in the grid, say only a couple of hundreds, you can use a simple "exchange sort" routine.

For each row, compare the value in the column that you want to sort on with the corresponding value in all the next rows, in order to find the smallest value. If necessary, exchange (swap) the contents of the cells of the two rows. I hope that an example in pseudo-code makes this clearer:

var
  Row1, FirstRow, LastRow, SmallestRow, SortColumn, Col: integer;
  SmallestValue: string;  
...
for Row1 := FirstRow to LastRow - 1 do

  SmallestRow := Row1;
  SmallestValue := Grid.Cells[SortColumn, Row1);

  for Row2 := Row1 to LastRow do begin
    if Grid.Cells[SortColumn, Row2] < Row1 then begin
      SmallestRow := Row2;
      SmallestValue := Grid.Cells[SortColumn, Row2);
    end;
  end;   

  if SmallestRow <> Row1 then begin
    // Exchange Row1 and SmallestRow
    for Col := FirstCol to LastCol do begin
      TempValue := Grid.Cells[Col, Row1];   
      Grid.Cells[Col, Row1] := Grid.Cells[Col, SmallestRow];
      Grid.Cells[Col, SmallestRow] := TempValue;
    end;
  end;

end;