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.
DSZoo is connected to a DBGrid and to a DBNavigator.

TableAnimals is connected to a DataSource component, named DSAnimals.
DSAnimals is connected to a DBLookUpListBox.
At design time, the properties of the DBLookUpListBox are set as follows:

   DataSource: DSZoo
   DataField: Animal
   ListSource: DSAnimals
   ListField: Animal
   KeyField: Animal

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).
Note that the event-handler is connected to the event "OnStateChange" of the datasource.

procedure TFormMain.DSZooStateChange(Sender: TObject);
begin
  DBLookupListBox1.Enabled := DSZoo.State in [dsInsert, dsEdit];
end;

Related articles

Turbo Delphi Explorer
Download and install the free Delphi version, suitable for database programming!
     

DelphiLand Discussion Forum