-
Define Your Class:
Ensure your class has properties that you want to map to the TStringGrid. Enable property change notifications if possible.
type
TMyObject = class
private
FName: string;
FAge: Integer;
procedure SetName(const Value: string);
procedure SetAge(const Value: Integer);
public
property Name: string read FName write SetName;
property Age: Integer read FAge write SetAge;
end;
-
Setting Up the TObjectList:
var
MyObjectList: TObjectList<TMyObject>;
-
Populate the TStringGrid:
procedure PopulateGrid(Grid: TStringGrid; List: TObjectList<TMyObject>);
var
I: Integer;
begin
Grid.RowCount := List.Count;
for I := 0 to List.Count - 1 do
begin
Grid.Cells[0, I] := List[I].Name;
Grid.Cells[1, I] := IntToStr(List[I].Age);
end;
end;
-
Respond to Changes in TStringGrid:
To handle changes made directly in the TStringGrid:
procedure TForm1.StringGrid1SetEditText(Sender: TObject; ACol, ARow: Integer; const Value: string);
var
Obj: TMyObject;
begin
Obj := MyObjectList[ARow];
case ACol of
0: Obj.Name := Value;
1: Obj.Age := StrToIntDef(Value, Obj.Age);
end;
end;
-
Track Changes in TObjectList Properties:
Implement property setters in your class that can notify changes. It’s often helpful to use custom events or observers that can signal when a property changes:
type
TMyObject = class
private
FName: string;
FAge: Integer;
FOnChange: TNotifyEvent;
procedure SetName(const Value: string);
procedure SetAge(const Value: Integer);
procedure Changed;
public
property Name: string read FName write SetName;
property Age: Integer read FAge write SetAge;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
end;
procedure TMyObject.SetName(const Value: string);
begin
if FName <> Value then
begin
FName := Value;
Changed;
end;
end;
procedure TMyObject.SetAge(const Value: Integer);
begin
if FAge <> Value then
begin
FAge := Value;
Changed;
end;
end;
procedure TMyObject.Changed;
begin
if Assigned(FOnChange) then
FOnChange(Self);
end;
-
Register for Change Notifications:
When you populate your list or form, register handlers that can respond to property changes and update the TStringGrid:
procedure SetupChangeNotification(List: TObjectList<TMyObject>; Grid: TStringGrid);
var
Obj: TMyObject;
I: Integer;
begin
for I := 0 to List.Count - 1 do
begin
Obj := List[I];
Obj.OnChange := procedure (Sender: TObject)
begin
var Index := List.IndexOf(TMyObject(Sender));
if Index >= 0 then
begin
Grid.Cells[0, Index] := TMyObject(Sender).Name;
Grid.Cells[1, Index] := IntToStr(TMyObject(Sender).Age);
end;
end;
end;
end;