Question

I'm creating nested components at run time. How can I assign the Parent property of a child component inside a with?

with Tspanel.Create(categorypanel) do
begin
  parent:=categorypanel;  // categorypanel, is a declared variable
  height:=30;
  visible:=true;

  button1 := tsbutton.Create();
  // Here is my problem! I want the parent to be the
  // panel I've created with the "with tspanel.create(...)"
  button1.Parent := ...
end;

My goal is to not declare variables for every component.

Was it helpful?

Solution

You cannot do what you want with a with statement. There is no way to name the object that is the subject of a with statement.

Use a local variable instead. For example:

var
  Panel1: TPanel
  Button1: TButton;
....
Panel1 := TPanel.Create(Form1);
Panel1.Parent := Form1;
Button1 := TButton.Create(Panel1);
Button1.Parent := Panel1;

As an added benefit you get to remove these with statements that are a scoping blight on any code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top