Solved

# How To Sort a StringGrid

Posted on 1998-10-27
216 Views
any ideas ?

0
Question by:k6__
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points
• 3

LVL 8

Expert Comment

ID: 1344558
how big are the stringgrids?
0

LVL 8

Expert Comment

ID: 1344559
ps. why not using great freeware components?

look at supergrid and hypergrid :

http://www.pablop.demon.co.uk/

Zif.
0

LVL 8

Accepted Solution

ZifNab earned 50 total points
ID: 1344560
Hi,

If you want to it yourself, then you can use TStringList's.

Here is some code (not by me, this one explains it already)

Put the columns into TStringLists, put the original order number of the ordered column in the object of that column string list, sort the ordered column, put the ordered column back in the stringgrid, put the unordered column items  against the ordered column items (original order in object of ordered column is                   index into un-ordered column TStringList).

Like this :-

var
Col1StrLst, Col2StrLst : TStringList;
i : integer;
begin
{put first column into the strings of a string list}
Col1StrLst := TStringList.Create;
with Col1StrLst do begin
Assign(StringGrid1.Cols[1]);
{put the original order number into the objects of the TStrings}
for i := 0 to Count - 1 do
Objects[i] := pointer(i); {note the type-cast}
{now sort the strings - the objects (with references to the
original position) stay with each string}
Sorted := true;
end;
{put ordered strings back into first column}
StringGrid1.Cols[1].Assign(Col1StrLst);
{put second column into the strings of a string list}
Col2StrLst := TStringList.Create;
Col2StrLst.Assign(StringGrid1.Cols[2]);
{put strings of second column in appropriate row for first column strings - the row number is in the object of the sorted first column}
for i := 0 to Col0StrLst.Count - 1 do
StringGrid1.Cells[2, i] :=
Col2StrLst.Strings[integer(Col1StrLst.Objects[i])];        {note type-cast}
{free the TStringLists}
Col1StrLst.Free;
Col2StrLst.Free;
end;

The above assumes you have no headings, if you do you would have to save them to variables, set them to blank strings, then sort the rows, then set the heading strings back to the top row. The blank strings in the columns would always sort to the top.

Zif.
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

### Suggested Solutions

Create Database on Android via Delphi dbExpress 3 143
oracle global variables 4 80
Firemonkey Queue list 1 51
"Could not obtain OLE control window handle" under Delphi XE8 8 81
This article explains how to create forms/units independent of other forms/units object names in a delphi project. Have you ever created a form for user input in a Delphi project and then had the need to have that same form in a other Delphi proj…