Link to home
Start Free TrialLog in
Avatar of Softtech
Softtech

asked on

Sorting a TStringGrid

What is the best/easiest way to sort the contents of a TStringGrid?  I have a TStringGrid which has 100 rows and 5 columns.  I want the rows to be sorted based upon the contents of column #1.

Thanks.
Avatar of hhamster
hhamster
Flag of Croatia image

Use any sort algorithm on the 1st column. Some of them can do it on the same TStringGrid component and some can do it by copying sorted values to a new instance of the TStringGrid component. Which one you choose result in the amount coding and the speed of executing.

Do something like this:
i,j.minimuRow : LongInt;
tempRow : TStrings;

for i:=0 to RowCount-2 do
begin
  // sg - your StringGrid
  // 1 for column 1
  currentValue:=sg.Cells(i,1);

  // supose the min row
  minimumRow:=i;

  // search till rest for real min row
  for j:=i+1 to RowCount - 1 do
    if sg.Cells(j,1)<sg.Cells(minimumRow,1) then
      minimumRow:=j;

  // swap if some other row is min
  if minimumRow<>i then
  begin
    tempRow:=sg.Rows[i];
    sg.Rows[i]:=sg.Rows[minimumRow];
    sg.Rows[minimumRow]:=tempRow;
  end;
end;

ASKER CERTIFIED SOLUTION
Avatar of Igor UL7AAjr
Igor UL7AAjr
Flag of Kazakhstan image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of DValery
DValery

Hi Softtech,
I did answer on like question:

http://www1.experts-exchange.com/bin/Q.10326262