I have a trouble.
I create a label object.
var lbl:Tlabel;
begin
lbl:=TLabel.Create(nil);
....
Ok, but after destroying it, it still remains on form.
There is my code:
lbl.free;
lbl := nil;
After executing it, controls stays on form.
There is a solution? I need to destroy this component, this should dissapear from form.
Thanks.
EDIT : RemoveControl(AControl: TControl); procedure isnt working.
EDIT2:
for I := 0 to 4 do begin
lbl:=TLabel.Create(nil);
lbl.Top := 100+z*i;
lbl.Left := 88;
Lbl.Width := 80;
Lbl.Height := 14;
lbl.Font.Size := 9;
lbl.Caption := nm[i];
Form1.InsertControl(lbl);
This control stays on form.
Destroying a control is no different from destroying any other object. Simply call Free on the object and you are done.
The only time that you run into problems is when you call Free on an object for whom an event handler is running. For example freeing a button in that button’s OnClick handler. In such a scenario you need to post a message to your form, and then free the button when that queued message is processed.
Your problem is that you are calling Free on the wrong object. You created 5 labels but only held on to a reference to one of them. You need to free all 5 labels. You’ll want an array or a list to hold the label references. Then you’ll be able to free them all.
In your form declare an array:
When you create them:
Destroy like this:
Some general advice for you. When you are faced with a problem, simplify it. Why try to debug object destruction with multiple controls? Create a blank app, and add a single control. Then try to delete that single control. Then move to multiple controls. Don’t troubleshoot the complex version, always try to simplify.