How to dynamically create controls aligned to the top but after other aligned controls?

Once again, DisableAlign and EnableAlign to the rescue:

procedure TForm1.FormCreate(Sender: TObject);
var
  I: Integer;
  P: TPanel;
begin
  DisableAlign;
  try
    for I := 0 to 4 do
    begin
      P := TPanel.Create(Self);
      P.Caption := IntToStr(I);
      P.Align := alTop;
      P.Parent := Self;
    end;
  finally
    EnableAlign;
  end;
end;

Explanation:

When alignment is enabled, every single addition of a control to a container (the form itself in this specific case) will re-evaluate all alignment (and anchor) settings of all other controls within that container. In case that control has no specific Top property set, then Top will be 0. When there is already another control aligned to the top, then there are two controls with Top = 0, and the one which is about to inserted wins. I (currently) have no in-depth explanation for that, but it just is, and the position order indeed gets reversed from the creation order.

Now, when alignment of the container is disabled, then consecutive added controls are simply just inserted with all their positioning properties unaltered. When alignment is enabled again, then all those controls are re-evaluated in the same manner, with the difference that this takes place in one single loop in the order of the index in the Controls array; i.e. the order in which they were created.

Leave a Comment