Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 460
Аймен Ахмед Avatar asked Dec 03 '22 01:12

Аймен Ахмед


2 Answers

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;
like image 57
RRUZ Avatar answered Dec 28 '22 15:12

RRUZ


You don't have to free it. You gave the responsibility to free it to the form with lblLink := TLabel.create(self);. The form will free the label when the form is freed.

However, with that being said, you can free it by looping through the form's Components array:

procedure TForm1.DeleteLabel(const LabelName: string);
var
  i: Integer;
begin
  for i := ComponentCount - 1 downto 0 do
  begin
    if Components[i] is TLabel then
      if Components[i].Name = LabelName then
      begin
        Components[i].Free;
        Break;
      end;
  end;
end;
like image 23
Ken White Avatar answered Dec 28 '22 15:12

Ken White