croceldon
croceldon

Reputation: 4595

Is it possible to sort a TDBGrid on a lookup field?

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!

Upvotes: 10

Views: 4517

Answers (4)

Kachwahed
Kachwahed

Reputation: 542

DevExpress ExpressQuantumGrid can do it, check it out: http://www.devexpress.com/products/vcl/exquantumgrid/

Upvotes: 0

Jeroen Wiert Pluimers
Jeroen Wiert Pluimers

Reputation: 24493

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:

  1. Load the data from your regular into the ClientDataSet,
  2. add a calculated field to the ClientDataSet that contains the value obtained from the lookup,
  3. then add an index to that calculated field.

--jeroen

Upvotes: 4

John Thomas
John Thomas

Reputation: 4135

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)

Contacts

  • ID - Integer (PK)
  • NAME - Varchar(40)
  • COUNTRYID - Integer

Countries

  • ID - Integer (PK)
  • NAME - Varchar(40)

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.

Upvotes: 1

Erwin
Erwin

Reputation: 1926

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.

Upvotes: 6

Related Questions