Search code examples
delphiruntimevcl

Delete TLabel created in run-time


How to delete created labels. I tried FindComponent but failed , what I have to do? should I set there parent to other component like TPanel or what?

procedure TForm1.Button1Click(Sender: TObject);
var
  lblLink: TLabel;
begin
   for i := 0 to stringtList.Count-1 do
   begin 
     lblLink := TLabel.create(self);

     with lblLink do
     begin
       name:='lblLink'+inttostr(i);
       caption:inttostr(i);
       Parent := self;
       font.style := [fsUnderline];
       cursor := crHandPoint;
       color := clBlue;
       font.Color := clBlue;
     end;
   end;
end;

Solution

  • You can iterate over the Components property, then check for the name of the component and finally free the component.

    Var
      LIndex : Integer;
      LComponent : TComponent;
    begin
      for LIndex := ComponentCount-1 downto 0 do
        if StartsText('lblLink',Components[LIndex].Name) then
        begin
         LComponent:=Components[LIndex];
         FreeAndNil(LComponent);
        end;
    end;