Skip to content

LiveBindings: Code to create TBindLink and fill a Listbox

The previous post described how to configure TBindList in the designer.  This post describes how to use TBindList in code.

Here is a method to fill a listbox using a TBindList component:

procedure FillList(AControl: TComponent; const AControlExpression: string;
  ASource: TBaseBindScopeComponent; const ASourceExpression: string; const ASourceMemberName: string = '');
var
  LBindList: TBindList;
begin
  LBindList := TBindList.Create(nil);
  try
    // Turn off auto properties.
    LBindList.AutoFill := False;
    LBindList.AutoActivate := False;
    LBindList.ControlComponent := AControl;
    LBindList.SourceComponent := ASource;
    LBindList.SourceMemberName := ASourceMemberName;
    with LBindList.FormatExpressions.AddExpression do
    begin
      SourceExpression := ASourceExpression;
      ControlExpression := AControlExpression;
    end;
    LBindList.FillList;
  finally
    LBindList.Free;
  end;
end;

You will need a TBindScopeDB component which is connected to a TDataSource. Call FillList as follows to populate a listbox with the value of the Category field:

  FillList(ListBox1, 'Text', BindScopeDB1, 'AsString', 'Category');

When using this code in a FireMonkey project, you will need to use FMX.Bind.Editors. For VCL projects, use VCL.Bind.Editors.

These units register editors which TBindList uses to add items to a TListBox. These units also register editors for a TComboBox.  Use the following line of code to populate a combo box.

  FillList(ComboBox1, 'Text', BindScopeDB1, 'AsString', 'Category');

VCL.Bind.Editors also registers an editor for TListView.  Use the following line of code to populate a list view:

  FillList(ListView1, 'Caption', BindScopeDB1, 'AsString', 'Category');

The last parameter to the FillList method is optional. When excluded, TBindList will evaluate against TDataSet instead of TField.  The following code fills a listbox with values from two different fields:

  FillList(ListBox1, 'Text', BindScopeDB1, 'Category.AsString + " - " +  Common_Name.AsString');

A sample project showing how to implemet and use the FillList method is available on sourceforge:

The project name is BindListUtilsSampleProject.dpr.
This project includes other versions of FillList besides the one shown in this post.   More about this in the next post.

{ 1 } Trackback

  1. El misterio de los 200… | Delphi Básico | January 26, 2012 at 1:37 am | Permalink

    [...] LiveBindings: Code to create TBindLink and fill a Listbox [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

Bad Behavior has blocked 26 access attempts in the last 7 days.

Close