Post by CooperYes, i have thinked about string grid, but problem is that in this grid i
need sort too for column, thing that with string grid i can't to do; just
only with tdgrid.
TStringGrid has a property Rows, which is a TStrings with the column
contents as individual elements in the TStrings (accessed as a
TStringList).
To sort you write a loop for all rows which checks whether any element
of one row is greater or less than the same element in the next row.
If it is greater then you swap the two rows (there is a TStringGrid
function to swap rows). You keep looping until the grid is sorted
(that is, the appropriate element in each row is less than the element
in the next row).
To do the actual check you write a compare function which takes
references to two rows and does the comparison on the stated elements
of the two rows, returning 0 if they're the same, negative if the
first is less than the second, and positive if the first is greater
than the second. What is "less" or "greater" is up to you when you
write the compare function.
Here is one I use ...
type
TMoveStrGrid = class(TCustomGrid);
(necessary to access the protected MoveRow procedure)
TGridSortCompare = function(Row1, Row2 : TStrings) : integer;
{returns -1 if Row1 < Row2, 0 if Row1 = Row2, & +1 if Row1 > Row2}
implementation
function GridSortCompare(RowA, RowB : TStrings ) : integer;
{must return 0 if equal, negative if RowA < RowB, positive if RowA >
RowB
const
TextCol = 4; // index of column to sort on
begin
Result := AnsiCompareText(RowA[TextCol], RowB[TextCol]);
end;
procedure SortStringGrid(StringGrid : TStringGrid;
CompareProc : TGridSortCompare);
{*D 14/11/2000}
{sort a stringgrid}
var
Sorted : boolean;
SelRow, TopVisibleRow, i : integer;
begin
with StringGrid do begin
TopVisibleRow := TopRow;
SelRow := Row;
repeat {until Sorted}
Sorted := true;
for i := 2 to RowCount - 1 do begin // row 0 is a fixed row
if CompareProc(Rows[i-1], Rows[i]) > 0 then begin
{... then Row[i-1] is > Row[i] but should be <, therefore
swap}
Sorted := false; // set flag for continuing to sort
{swap stringgtid rows, MoveRow is protected so typecast to
descendant}
TMoveStrGrid(StringGrid).MoveRow(i, i-1);
end {if CompareProc(Rows[i-1], Rows[i]) > 0}
end; {for i := 2 to RowCount - 1}
until Sorted;
{restore top row & selected row}
TopRow := TopVisibleRow;
Row := SelRow;
end; {with StringGrid}
end;
Alan Lloyd