Search code examples
delphidelphi-7

How do I refer to components created at runtime rather than in the form designer?


i have a little problem. I'm trying to create in Delphi7 a list of components at run-time and to resize them with form's .OnResize event but no use... i can't figure out how to do it.

Here's my code:

procedure TForm1.Button1Click(Sender: TObject);
var
  //ExtCtrls
  panel: TPanel;
  memo: TMemo;
  splitter: TSplitter;
  list: TListBox;
begin
  panel := TPanel.Create(Self);
  list := TListBox.Create(Self);
  splitter := TSplitter.Create(Self);
  memo := TMemo.Create(Self);

  with panel do
  begin
    Parent := Form1;
    BevelOuter := bvNone;
    Top := 12;
    Left := 12;
    Height := Form1.Clientheight - 24;
    Width := Form1.Clientwidth - 24;
  end;

  with list do
  begin
    Parent := panel;
    Align := alClient;
    Top := 0;
    Height := panel.Height;
  end;

  with splitter do
  begin
    Parent := panel;
    Top := 0;
    Width := 12;
    Align := alLeft;
  end;

  with memo do
  begin
    Parent := panel;
    Top := 0;
    Left := 0;
    Width := round(panel.Width / 4) * 3;
    Height := panel.Height;
    Align := alLeft;
  end;
end;

Do i have to somehow register their names in order to use them in form's event? Or maybe, to create a class and include them?

Any kind of help is really appreciated! Thank you in advance.


Solution

  • Your variables are local to the procedure where they are created so you can't refer to them using those variables when outside that procedure. The solution is to make them fields of the form class.

    type
      TForm1 = class(TForm)
        procedure FormResize(Sender: TObject);
        procedure Button1Click(Sender: TObject);
      private
        FPanel: TPanel;
        FMemo: TMemo;
        FSplitter: TSplitter;
        FList: TListBox;
      end;
    

    Then your FormResize event handler can refer to them.

    procedure TForm1.FormResize(Sender: TObject);
    begin
      if Assigned(FPanel) then
      begin
        ...
      end;
    end;
    

    Don't forget to remove the local variables from Button1Click and use the fields instead.

    procedure TForm1.Button1Click(Sender: TObject);
    begin
      FPanel := TPanel.Create(Self);
      ...
    end;