Saturday, May 25, 2013

FreePascal/Lazarus: How to use lookup combo in DBGrid

I recently worked on a project where I used FreePascal in order to create an app that consisted of a single EXE and which did not need to be installed (portable app).

I had some difficulty in getting a lookup column in the grid and, after lots of searches pointing to convoluted solutions, I came across the following 2 pages, which gave me the info I needed to solve the problem.

Defining a Lookup List Column

Defining a lookup field

In a nutshell, you need to create a lookup field in the TSqlQuery (or whatever query type you use).
You then add a new field in the grid control and link it to the lookup field you created in the query.

Using this method means that you must specify the UPDATE and INSERT SQL (just in case you used to rely on what FreePascal/Delphi generated).


For example, in this case, the CrewMembers table contains a CrewID but not the CrewName.

A lookup field is created in the CrewMembers query, as show below



I want to show the CrewName from the Crew table when I am editing the CrewMembers table.
The CrewMembers table contains only the CrewID, not the name.


LookupDataSet= A Dataset that loads data from the Crew table
LookupKeyField= The name of the key field in the Crew table that I will link to via my CrewID
keyFields=The name of the key field in my table/grid (in this case, CrewID)

This is a just a quick overview. Leave a comment if you'd like more info.

[Blatant plug! See my article about my album on Google Play.]


ps: Comments and/or links to this article are most welcome!