Wizzard
Wizzard

Reputation: 12712

Programmatically create and remove a label from a form

I got some code here, which creates a label just fine, but when I free the label it STILL shows on the form. Even though it's been removed and no longer 'assigned'.

Here is the code below. It creates the label fine, but wont remove. No exceptions, and the assigned says false.

I can reproduce this with a TRectangle as well.

type
  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
      Lab : TLabel;
  end;

var
  Form1: TForm1;

implementation

{$R *.fmx}

procedure TForm1.Button1Click(Sender: TObject);
begin
  Lab := TLabel.Create(Self);
  Lab.Parent := Form1;
  Lab.Text := 'Hello!';
  Lab.Position.X := 30;
  Lab.Position.Y := 40;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  FreeAndNil(Lab);
  ShowMessage(BoolToStr(Assigned(Lab), true));
end;

Upvotes: 3

Views: 8796

Answers (2)

Frank Schmitt
Frank Schmitt

Reputation: 30835

FWIW, using Delphi XE (not XE2), your code works as expected (after making some small modifications, e.g. replacing Position.X with Left etc).

A few things to check/try:

  • is your Parent really Form1 (since you are using Lab.Parent := Form1 instead of using self) ?
  • have you tried adding Self.Repaint after free'ing Lab?

Upvotes: 0

punker76
punker76

Reputation: 14621

i think

Lab.Parent:= NIL;
FreeAndNil(Lab);

could help.

Upvotes: 5

Related Questions