Search code examples
delphi-7

How to assign a parent to an object using only the parent object name


Basically, I have 8 panels and I want to assign to all of them a picture by using a loop, to do that I used a TComponent variable and an image that I create during runtime. But I am unable to find a way to assign that image a parent using this string ('pnlDisplay' + inttostr(i)). So my code looks something like this:

var
  imgPanel : TImage;
  cPanel : TComponent;
begin
  for i := 1 to 8 do
    begin
      cPanel :=  FindComponent('pnlDisplay' + inttostr(i));
      imgPanel := TImage.Create(cPanel);

      imgPanel.Parent := cPanel; //Here is my problem

      imgPanel.Picture.LoadFromFile('Pic' + inttostr(i) + '.jpg');
      imgPanel.Visible := True;
    end;
end 

Any help or even another way to achieve this would be helpful.


Solution

  • FindComponent() returns a TComponent, whereas the Parent property expects a TWinControl instead. Assuming FindComponent() is returning the correct component, just type-cast it:

    imgPanel.Parent := TWinControl(cPanel);