Icon View Thread

The following is the text of the current message along with any replies.
Messages 1 to 2 of 2 total
Thread how to free dynamically created controls
Thu, May 29 2014 11:16 PMPermanent Link

Stephen Barker

I have a bunch of panels that represent data rows that have been dynamically created. Each contain other controls such as labels to display the data fields. These panels have no owner but they do own their child controls. I have set the panel tags to 99 to distinguish them from other static panels on the form.

When I want to shut this down (but not the whole app) I need to dispose of them all. I'm just freeing the parent (and owner) panels which should also free all the child components. I understand the Controls array may change, so I restart from the beginning each time I find and free one, like this:

procedure TfrmMain.pnlOtherProductsListHide(Sender: TObject);
var
 i : integer;
 any : boolean;
begin
 // destroy all the dynamically created data panels
 any := true;
 while any do begin
   any := false;
   for i := 0 to pnlProductContainer.ControlCount-1 do begin
     if (pnlProductContainer.Controls[i] is TPanel) and (TPanel(pnlProductContainer.Controls[i]).Tag = 99) then begin
       any := true;
       TPanel(pnlProductContainer.Controls[i]).Free;
       break;
     end;
   end;
 end;
end;

But I get the following error:
ReferenceError: invalid assignment left-hand side. Line: 1

Any ideas?


cheers,
Steve
Fri, May 30 2014 12:16 AMPermanent Link

Stephen Barker

Problem solved. I found I had to create an object instance before freeing it, rather than freeing directly from the controls array element.

var
 obj : TObject;
...
       obj := pnlProductContainer.Controls[i];
       obj.Free;
Image