We have seen that the csdn document has introduced that this function can be conveniently implemented through the sort attribute of adoquery or other dataset components in combination with the ontitleclick event of DBGrid. Because the sort attribute allows the active dataset to be sorted by specified fields, you can also select the sorting method (ascending/descending ). This function is indeed very practical. Http://blog.csdn.net/jlee084/archive/2004/12/20/223284.aspx ). I have improved this function. After clicking the title, add the triangle (▲) and inverted triangle (triangle) to the title to indicate that the current sorting method is ascending or descending; writing a function is convenient for reuse:
Function titlesort (DBGrid: TDBGrid; adoquery: tadoquery; column: tcolumn): Boolean;
VaR
I, II: integer;
CSTR: string;
C: tcolumn;
Begin
For II: = 0 to DBGrid. Columns. Count-1 do
Begin
C: = DBGrid. Columns [II];
CSTR: = C. Title. Caption;
If (Pos ('▲ ', CSTR) = 1) or (Pos ('hour', CSTR) = 1) then
Begin
Delete (CSTR, 1, 2 );
C. Title. Caption: = CSTR;
End;
End;
For I: = 1 to DBGrid. Columns. Count do
Begin
// Restore all title fonts to default
DBGrid. Columns [I-1]. Title. Font. Color: = clwindowtext;
DBGrid. Columns [I-1]. Title. Font. Style: = [];
End;
If adoquery. Sort <> (column. fieldname + 'asc ') Then // judge the original sorting method
Begin
Adoquery. Sort: = column. fieldname + 'asc ';
Column. Title. Font. Style: = [fsbold];
Column. Title. Caption: = '▲' + column. Title. Caption; // Add a triangle to the title to indicate that the current sorting method is ascending;
End
Else
Begin
Adoquery. Sort: = column. fieldname + 'desc ';
Column. Title. Font. Style: = [fsbold];
Column. Title. Caption: = 'hangzhou' + column. Title. Caption; // The inverted triangle in the title indicates that the current sorting method is in descending order;
End;
End;
Call time:
Procedure tform1.dbgrid1titleclick (column: tcolumn );
Begin
Titlesort (dbgrid1, adoquery1, column );
End;