I have a DBGrid with a column based on a lookup field.
How can I set it up so that when a user clicks on the column title, it will sort by that field.
My problem here is that I can't figure out a way to create an index on a lookup field.
I'm using Absolute Database for this, but most things that work with the BDE or TClientDataSet will work with Absolute.
Thanks!
I don't think it is possible to create an index on a lookup field. It is possible to create an index on an internally calculated field of a ClientDataSet though. In the OnCalcFields event handler set its value to the value of the lookup field. And set the visible property of the lookup field to false. Now you can sort on the internally calculated field.
What you could do (especially if the data is readonly, and does not have zillions of rows) is use a ClientDataSet to display data in your grid.
Roughly the steps would be like this:
--jeroen
You cannot sort by a lookup field. But you can 'fake' this. Let's suppose that you have the following tables: (PK means Primary Key)
Then you can have the following query in the dataset which is linked to the TDBGrid:
SELECT C.ID, C.NAME, C.COUNTRYID, CO.NAME
FROM CONTACTS C
JOIN COUNTRIES CO ON C.COUNTRYID=CO.ID
(Not tested but I think that you got the idea)
Also you can put this in a view.
Then you'll display in your TDBGrid (as columns) only the ID, NAME and the desired lookup field which you already have (let's call it COUNTRYLOOK).
When one clicks on the Title Header you can change the query by adding in the 4th line an ORDER BY . For the specific column of the lookup field (COUNTRYLOOK), instead of using the 1:1 mapping you can put in the 4th line of your query ORDER BY CO.NAME. Reopen the query and that's it. In practice is much more simpler than my description here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With