Delphi - How to remove all child components at runtime?

At design time, I create a TScrollBox that will be the parent of the TLayouts created at runtime. Layouts will also contain Tlabels and Tedits:

var
  Layout1: TLayout;
  Label1: TLabel;
  Edit1: TEdit;
begin
  Layout1 := TLayout.Create(self);
  Layout1.Parent := ScrollBox1;
  Label1 := TLabel.Create(self);
  Label1.Parent := Layout1;
  Label1.Text := 'abc';
end;

Now I want to delete everything, as this procedure was never called.

I tried the following, but the program just crashed.

var
  i : integer;
  Item : TControl;
begin
  for i := 0 to Scrollbox1.ControlCount - 1 do  
  begin  
    Item := Scrollbox1.controls[i];
    Item.Free;
  end;
end;

Can someone give me a hint?

+5
source share
2 answers

When you delete a control, the index of those behind it control listmoves down. Ie, you end up trying to access positions that don't exist.

You need to iterate the list down:

var
  i : integer;
  Item : TControl;
begin
  for i := (Scrollbox1.ControlCount - 1) downto 0 do  
  begin  
    Item := Scrollbox1.controls[i];
    Item.Free;
  end;
end;

- 0, , :

var
  i : integer;
  Item : TControl;
begin
  while Scrollbox1.ControlCount > 0 do  
  begin  
    Item := Scrollbox1.controls[0];
    Item.Free;
  end;
end;

UPDATE

@DavidHeffernan, . , . - .

. ( , , , ):

procedure freeChildControls(myControl : TControl; freeThisControl: boolean);
var
  i : integer;
  Item : TControl;
begin

  if Assigned(myControl) then
  begin
    for i := (myControl.ControlsCount - 1) downto 0 do
    begin
      Item := myControl.controls[i];
      if assigned(item) then
        freeChildControls(item, childShouldBeRemoved(item));
    end;

    if freeThisControl then
      FreeAndNil(myControl);
  end;
end;

function childShouldBeRemoved(child: TControl): boolean;
begin
  //consider whatever conditions you need
  //in my test I just checked for the child name to be layout1 or label1
  Result := ...; 
end;

scrollbox1 ( ), :

freeChildControls(scrollbox1, false);

, childShouldBeRemoved, , label layout, .

object list, , , .

+15

- . Label1 := TLabel.Create(Layout1); - . Layout1, Label1 .

+1

All Articles