LiveBindings: Code to create TBindLink and fill a Listbox

Posted by on in Blogs
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 = '');
LBindList: TBindList;
LBindList := TBindList.Create(nil);
// Turn off auto properties.
LBindList.AutoFill := False;
LBindList.AutoActivate := False;
LBindList.ControlComponent := AControl;
LBindList.SourceComponent := ASource;
LBindList.SourceMemberName := ASourceMemberName;
with LBindList.FormatExpressions.AddExpression do
SourceExpression := ASourceExpression;
ControlExpression := AControlExpression;

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.


  • Page :
  • 1

Check out more tips and tricks in this development video: