Tlistbox items from database column

南笙酒味 提交于 2019-12-06 15:01:40

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.

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');

Use a TDBLookupListBox. Use the ListField property and ignore the DataField property.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!