devxlogo

Populating a ComboBox

Populating a ComboBox

Question:
I am trying to populate a comboxbox from a table (or query). If I use dataware is only receive the first record, I however want all records in the field I select. I have done this in the following VB code;Private Sub Form_Load()Dim RecEmployees as RecordsetDim MyDB as DatabaseSet MyDB = OpenDatabase _ (“D:database.mdb”)Set Recemployees = MyDB.OpenRecordset(“Employees”)Dim i as integer For i = 0 to RecEmployees.RecordCount – 1 Combo1.AddItem (RecEmployees(1)) RecEmployee.MoveNext Next iEnd SubBut have been unable to duplicate in Object Pascal.Any assistance would be greatly appreciated.Thanks,James

Answer:
In Delphi, it’s basically the same principle. Here are a couple of function that I’ve written that will seamlessly do the job:

procedure DBLoadListBox( dbSource,             {database name}                         tblSource,            {table name}                         fldName   : String;   {field name to load from}                         const LBox: TStrings);{List Box on Form}var   SourceTbl : TTable;begin  SourceTbl := TTable.Create(Application); {Create an instance of sourceTbl}  with SourceTbl do  begin    Active       := False;    DatabaseName := dbSource;    TableName    := tblSource;    try      Open;      First;      while NOT EOF do begin         LBox.Add(SourceTbl.FieldByName(fldName).AsString);         Next;      end;    finally      Free;    end;  end;end;procedure DBLoadList(tblSource,             {table name}                     fldName    : String;   {field name to load from}                     const List : TStrings); {Any TStrings}var  qry : TQuery;begin  qry := TQuery.Create(nil);  with qry do begin    Active := False;    DatabaseName := ExtractFilePath(tblSource);    SQL.Add('SELECT DISTINCT d."' + fldName + '" ');    SQL.Add('FROM "' + tblSource + '" d');    try      Open;      while NOT EOF do begin        List.Add(FieldByName(fldName).AsString);        Next;      end;    finally      Free;    end;  end;end;

The first function accesses a table directly, while the second uses a query – very useful for when you only want the DISTINCT values from a particular field.

See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist