| Sorting records in Delphi DBGrid by Clicking on Column Title | |||||||||||||||
| How to sort records in Delphi DbGrid by clicking on the column title. Plus: how to change the appearance of the selected column title to reflect the sort order. Even more: how to change the cursor when moving over the DBGrid column titles. | |||||||||||||||
Delphi DBGrid ... what a powerful component! If you are developing data aware applications you are probably using the DBGrid component every day. Following the concepts set in the Beginners Guide to Delphi Database Programming, examples below use ADO components (AdoQuery/AdoTable connected to ADOConnection, DBGrid connected to AdoQuery over DataSource) to display the records from a database table in a DBGrid component. All the component names were left as Delphi named them when dropped on the form (DBGrid1, ADOQuery1, AdoTable1, ...) Mouse moves over DBGrid title area?
Sort on column click? Change font of the sorted column title?
ADOTable1.Sort := 'Year DESC, ArticleDate ASC'
The OnTitleClick event of the DBGrid component has a Column parameter indicating the Column the user has clicked on. Now, each Column (object of type TColumn) has a Field property indicating the Field (TField) represented by the Column - and the Field in its FieldName property holds the name of the field in the underlying dataset. Therefore, to sort an ADO dataset by field/column a simple line can be used:
with TCustomADODataSet(DBGrid1.DataSource.DataSet) do Below you can find the code for the OnTitleClick even handler that sorts the records by column click. The code, as always, extends the idea. For the sake of simplicity, to mark the column that "sorts" the records we'll simply change the font style of the column title to Bold, and remove it when dataset is sorted using another column.
Note: the code above uses typed constants to preserve the value of the previously "selected" column for sort order.
That's it. Simple and powerful - this is why you have picked Delphi. If you want more articles describing how to use various Delphi data aware component, go for Using Delphi DB components. A Beginner's Guide to Delphi Database Programming >> |
|||||||||||||||


