Search code examples
delphidelphi-7

Dynamically creating a new component without predeclared variable limitation?


I am working on a school project. I need the user to click a button and each time the button is pressed a new component with a new name is created. The idea I had looked something like this

procedure TForm1.btnClick (Sender: TObject);
Var
    pnlTest1, pnlTest2 : TPanel;
Begin
 If iCount = 1
 then
   Begin
     pnlTest1 := TPanel.Create(Self);
     pnlTest1.Parent := Self;
     pnlTest.Top := 0;
     Etc...
   End
Else if iCount = 2
 Then
  Begin
   PnlTest2 := TPanel.Create(Self);
   PnlTest2.Parent := Self;
   PnlTest2.Top := 0;
   Etc...
End;

The problem is i can only create as many components as I have created varaibles and I need the user to craete basically an infinite amount of new components. I tried other methods as well but the same problem occurs, I also tried creating dynamic variables with pointers and so on but the data types of those varaibles worked only (in my efforts) with the basic data types (Integer, String etc) and so i could not create a variable in run time to create a component (in the example pnlTest : TPanel was declared, this did not work with the dynamic variables)

Please advise on how i can create a new component everytime the button is clicked without bieng limited by the preexisting variables or please advise on how i can have a ''ínfinite'' amount of variables to use for creating a new component each time.


Solution

  • You only need to declare 1 pointer variable to receive the new component instance, eg:

    private
      iCount: Integer;
    
    ... 
    
    procedure TForm1.btnClick (Sender: TObject);
    Var
      pnlTest : TPanel;
    Begin
      pnlTest := TPanel.Create(Self);
      pnlTest.Parent := Self;
      pnlTest.Name := 'pnlTest' + IntToStr(iCount);
      pnlTest.Top := 0;
      //...
      Inc(iCount);
    End;
    

    The component instance is stored in the Form's Components and Controls properties, since you are assigning the Form as the component's Owner and Parent, respectively.