Example of DBLookupListBox
Posted by webmaster Guido on October 25, 2002:
In Reply to: Re: Populating a listbox from a database table posted by webmaster Guido on October 24, 2002:
: : IS it possible to populate a listbox from a database table and if so, then can someone please tell me how to go about it. I have a listbox control, which I have manually added the entries to. The highlighted entry in the list box can be added to a gridbox, which also appends the record to the table. I now wish to have the listbox so that is it is used in the same manner, but populated from another table.
Yesterday, I wrote that you can use a TDBLookupListBox. It provides a list of "lookup" items for filling in fields with data from another table.
Here is the example that I promised.
The idea is to add/change records in TableZoo, whereby the field "Animal" is filled with the aid of a visual list that contains names of animals from table TableAnimals ("elephant", "lion", "tiger",...)
The two tables have one common field, a field with the same name, type and size; this is the alpha-numeric field "Animal".
TableZoo is connected to a DataSource component, named DSZoo.
TableAnimals is connected to a DataSource component, named DSAnimals.
At program start, the DBLookUpListBox must be disabled. Later on, it will be enabled only when we make a change to TableZoo (append a record or edit a record). Afterwards, when the changes are posted or canceled, DBLookUpListBox is disabled again. The actual code is surprisingly small, I'm just using two event handlers:
1. When the form is created, we disable the DBLookupListBox and we open the tables.
procedure TFormMain.FormCreate(Sender: TObject); begin DBLookupListBox1.Enabled := False; TableZoo.Open; TableAnimals.Open; end;
2. When the state of TableZoo changes to "edit" or "append", we enable the DBLookupListBox. We disable it again after the record is posted, or after the changes are discarded (canceled).
procedure TFormMain.DSZooStateChange(Sender: TObject); begin DBLookupListBox1.Enabled := DSZoo.State in [dsInsert, dsEdit]; end;