Reputation: 129
Is there a way to populate a TListbox
control with items from a database column?
I know the proper way to do this is to simply use a DBLookupListbox
control and set it up to access the column I want, but the problem with that is when I click on one of the items in the lookup control, it changes the current row in the dataset (expected behavior) but I do not want this to happen.
Instead, I would want the current row to be changed only on a double click event in the lookup control and since I do not think this behavior is possible to change, I thought it would be easier to simply use a normal TListBox
instead, but as I stated above, I am not sure how it's done.
So once again, I have come to the experts for some advise on how to populate a normal Tlistbox
control with items from a database column.
Upvotes: 1
Views: 4623
Reputation: 136391
You don't specify DB the components which you are using, so I wrote this sample using ADO and MySQL.
const
StrConnection='Driver={MySQL ODBC 5.1 Driver};Server=%s;Database=%s;User=%s; Password=%s;Option=3;';
procedure LoadColumn(Items:TStrings; const SqlStr :string);
Var
AdoDataSet : TADODataSet;
begin
AdoDataSet:=TADODataSet.Create(nil);
try
//you can share the connection too, in this case a new connection is made
AdoDataSet.ConnectionString:=Format(StrConnection,['server','mydatabase','user','pass']);;
AdoDataSet.CommandText:=SqlStr;
AdoDataSet.Open;
if not AdoDataSet.IsEmpty then
begin
Items.BeginUpdate;
try
Items.Clear;
while not AdoDataSet.Eof do
begin
Items.Add(AdoDataSet.Fields[0].AsString);
AdoDataSet.Next;
end;
finally
Items.EndUpdate;
end;
end;
finally
AdoDataSet.Free;
end;
end;
And use like so
LoadColumn(ListBox1.Items, 'Select MyColumn FROM Table');
Upvotes: 4
Reputation: 1570
There are a myriad of ways to solve your problem. You could create a hacked control of a TDbLookupListBox and override the Click method to do nothing. You could also create a second dataset to be used for your lookup. But as you wish, to populate a TListbox, you simply iterate the dataset and add the field value to the listbox as:
tLogin.first;
while not tLogin.eof do
begin
Listbox1.Items.Add(tLogin.fieldbyname('fullname').asstring);
tLogin.next;
end;
If you need a key value based on a selection, then this won't solve your problem entirely. You'd be better off hacking the TDbLookupListbox control, imo.
Upvotes: 2
Reputation: 43649
Use a TDBLookupListBox. Use the ListField property and ignore the DataField property.
Upvotes: 1