For the start, use dragging from the Fields editor to add data controls to a form. Drag Name, Author, Type and Description. This will add 4 DBEdit components and 4 Label components. At this point, remove the DBEdit connected with the Author field of the Applications table and replace it with a DBLookupComboBox. Name it ApplicationsAuthorLookup. We'll also need another DataSource component. Drop one on the form, change the name to AuthorsSource and link it to AuthorsTable. Finally, we need to set the lookup combo box to work properly. Use Object Inspector and set the following:
object ApplicationsAuthorLookup: TDBLookupComboBox DataSource = ApplicationsSource DataField = 'Author' ListSource = AuthorsSource KeyField = 'authorname' ListField = 'authorname,-email' end
Just for practice, replace the Type's field DBEdit with DBLookComboBox and set a lookup relation with the Types table. Note that you need one more DataSource and one more ADO Table pointing to the Types table.
Set the DataSource and DataField properties to the dataset and field where the selection will be written (Applications; Type). Set the ListSource, KeyField and ListField properties to the lookup field from which the list should be populated (Types; TypeName, TypeName).
Graphically, connections between tables, sources and ADOConnections can now be presented as:
That's it. Again, no code required. When the user selects an item from the combo box, an appropriate value of the KeyField field changes the value of the DataField. At run time, the form looks like:
Note 1: When you want to display more than one field in a LookupComboBox, as in the example above, you have to make sure that all columns are visible. This is done by setting the DropDownWidth property. However, you'll see that initially you have to set this to a very large value which results in dropped list being too wide in most cases. One workaround is to set the DisplayWidth of a particular Field shown in a drop down list. The next code snippet, placed inside the OnCreate event for the form, ensures that both author name and it's email are displayed inside the drop down list. AuthorsTable.FieldByName('authorname').DisplayWidth:=15; AuthorsTable.FieldByName('email').DisplayWidth:=20;
Note 2 : If you drag AEmail field from a Field Editor to a form, Delphi will connect it with a DBLookupComboBox automatically. Of course, key lookup properties will look different since we don't need another data source for this link to work - lookup field is already defined "inside" the ApplicationsTable/Source.
Was this article helpful?