Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Relational Databases
Expertise: Beginner
Dec 5, 1997

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 Recordset Dim MyDB as Database Set 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 i End Sub But 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.
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date