This function can be easily implemented in conjunction with the Ontitleclick event of the DBGRID through the Sort property of AdoQuery or other data set components. Since the sort property allows the active data set to sort by the specified field, you can also select a sort mode (ascending / descending order). This feature is indeed practical. (http://blog.9cbs.net/jlee084/archive/2004/12/20/223284.aspx). I improved this feature, in clicking the title, add the triangle (▲) and inverted triangles (▼) after the title, indicating the current sort mode as ascending order; written into a function, it can be easily reused:
Function Titlesort (DBGRID: TDBGRID; 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 ('▼', cstr) = 1) The Begin delete (CSTR, 1, 2); c.Title.caption: = cstr; end; end; for i: = 1 to dbgrid.columns.count do begin // Restore all title fonts for default dbgrid.columns [i-1] .title. Font.color: = CLWindowText; dbgrid.columns [i-1] .title.font.style: = []; end; if adoquery.sort <> (column.fieldname ASC ') THEN / / Judgment Original Sort by Begin AdoQuery.Sort: = column.fieldname 'asc'; column.title.font.style: = [fsbold]; color = [fsbold]; color ▲ column.title.caption; // Title plus triangle representation Current Sort mode is ascending; end else begin adoquery.sort: = column.fieldname 'desc'; column.title.font.style: = [fsbold]; colorn.title.caption: = '▼' column.title.caption; // Title plus inverted triangle Shape represents the current ordering mode is descending; end; end; call time: procedure tform1.dbgrid1titleclick (Column: tcolumn); Begin Titlesort (DBGRID1, AdoQuery1, Column); END;