But how do I fill the ComboBox? And once filled, how do I know which record the user has selected?
First the Query. I am assuming that, like me, you create a field in every table that is filled with a unique ID. I can use this ID in other tables to create a join. For example, I may have a Customer table ...
Name: String (e.g. VarChar)
Lets say I want a ComboBox of all my customers for the user to select. The query would look something like this ...
SELECT CustomerID, Name
ORDER BY Name
I am always sure to ask for the ID first and then the text that the user will want to see. Now lets fill the ComboBox with that detail. Because I may wish to do this with many comboboxes in my application and with many different queries on other tables, I have built a procedure to fill the ComboBox using AddObject.
Procedure FillCombo(cb: TComboBox; Q: TQuery);
while not Q.Eof do
Now I want to use that procedure to fill my ComboBox.
So how then can we tell which record the user has selected? Simple, I have created a function that will return the ID of the selected record, in this case the selected Customer. If none has been selected, it will return -1.
function GetSelected(cb : TComboBox) : integer;
if cb.ItemIndex = -1 then
result := -1
result := Integer(cb.Items.Objects[cb.ItemIndex]);
So all we need to do is call it.
CustomerID := GetSelected(cbCustomer);
if CustomerID = -1 then
// none selected