# 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.
###### Who is Participating?

Commented:
Hi all.
It must work fast, because it used native TStringList sorting algorythm.

-------------
procedure TForm1.SpeedButton1Click(Sender: TObject);
var L : TStringList;
G : TStringGrid;
I : integer;
begin
G := TStringGrid.Create(nil);
G.RowCount:=SG.RowCount;
G.ColCount:=SG.ColCount;

L := TStringList.Create;
L.Sorted:=true;
for I:=0 to SG.RowCount-1 do
begin
L.AddObject(SG.Cells[2,I],pointer(I)); // 2- column to sort
G.Rows[I].Assign(SG.Rows[I]);
end;
for I:=0 to L.Count-1 do
SG.Rows[I].Assign(G.Rows[integer(L.Objects[I])]);

L.Free;
G.Free;
end;

-----
Igor
0

ProgramerCommented:
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
// 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;

0

Commented:
Hi Softtech,
I did answer on like question:

http://www1.experts-exchange.com/bin/Q.10326262
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.