Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LiveBindings - TList<TMyObject> bound to TStringGrid

I have the following example set of code, how can I bind the Data list elements to the TStringGrid using LiveBindings. I need bi-directional updates so that when the column in the grid is changed it can update the underlying TPerson.

I have seen example of how to do this with a TDataset Based binding but I need to do this without a TDataset.

unit Unit15;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Grids, System.Generics.Collections;

type
  TPerson = class(TObject)
  private
    FLastName: String;
    FFirstName: string;
  published
    property firstname : string read FFirstName write FFirstName;
    property Lastname : String read FLastName write FLastName;
  end;

  TForm15 = class(TForm)
    StringGrid1: TStringGrid;
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
    Data : TList<TPerson>;
  end;


var
  Form15: TForm15;



implementation

{$R *.dfm}

procedure TForm15.FormCreate(Sender: TObject);
var
 P : TPerson;
begin
  Data := TList<TPerson>.Create;
  P := TPerson.Create;
  P.firstname := 'John';
  P.Lastname := 'Doe';
  Data.Add(P);
  P := TPerson.Create;
  P.firstname := 'Jane';
  P.Lastname := 'Doe';
  Data.Add(P);
  // What can I add here or in the designer to link this to the TStringGrid.
end;

end.
like image 225
Robert Love Avatar asked Sep 21 '11 23:09

Robert Love


1 Answers

Part of the solution: From TList to TStringGrid is:

procedure TForm15.FormCreate(Sender: TObject); 
var 
 P : TPerson; 
 bgl: TBindGridList;
 bs: TBindScope;
 colexpr: TColumnFormatExpressionItem;
 cellexpr: TExpressionItem;
begin 
  Data := TList<TPerson>.Create; 
  P := TPerson.Create; 
  P.firstname := 'John'; 
  P.Lastname := 'Doe'; 
  Data.Add(P); 
  P := TPerson.Create; 
  P.firstname := 'Jane'; 
  P.Lastname := 'Doe'; 
  Data.Add(P); 
  // What can I add here or in the designer to link this to the TStringGrid. 

  while StringGrid1.ColumnCount<2 do
    StringGrid1.AddObject(TStringColumn.Create(self));

  bs := TBindScope.Create(self);

  bgl := TBindGridList.Create(self);
  bgl.ControlComponent := StringGrid1;
  bgl.SourceComponent := bs;

  colexpr := bgl.ColumnExpressions.AddExpression;
  cellexpr := colexpr.FormatCellExpressions.AddExpression;
  cellexpr.ControlExpression := 'cells[0]';
  cellexpr.SourceExpression := 'current.firstname';

  colexpr := bgl.ColumnExpressions.AddExpression;
  cellexpr := colexpr.FormatCellExpressions.AddExpression;
  cellexpr.ControlExpression := 'cells[1]';
  cellexpr.SourceExpression := 'current.lastname';

  bs.DataObject := Data;
end; 
like image 107
Arjen van der Spek Avatar answered Oct 24 '22 10:10

Arjen van der Spek