Rahul Bajaj
Rahul Bajaj

Reputation: 135

Get all child elements of Tpagecontrols

I have a page control on my form. This page control has two or three tabs. Each tab has a few other controls like button, label panel etc. I am able to find all controls but if some control sits on top of the panel, then I am unable to find that control

My code:

for I := 0 to Pagecontrol.Pagecount -1 do
begin
  for J := 0 to pagecontrol.pages[i].controlcount - 1 do
    showmessage(pagecontrol.pages[i].controls[J].name) // not able to find button whose parent is panel
end

and when i do

for J := 0 to pagecontrol.pages[i].componentscount- 1 do  // it does not enter into loop

Upvotes: 3

Views: 5906

Answers (1)

David Heffernan
David Heffernan

Reputation: 612964

The Controls[] property lists the immediate children. You need to drill down to the children of the children and so on. Typically that is done recursively like this:

procedure WalkChildren(Parent: TWinControl; Visit: TProc<TControl>);
var
  i: Integer;    
  Child: TControl;
begin
  for i := 0 to Parent.ControlCount-1 do 
  begin
    Child := Parent.Controls[i];
    Visit(Child);
    if Child is TWinControl then 
      WalkChildren(TWinControl(Child), Visit);
  end;
end;

You might call this like so:

for i := 0 to PageControl1.PageCount-1 do
  WalkChildren(
    PageControl1.Pages[i], 
    procedure(Child: TControl) 
    begin 
      Memo1.Lines.Add(Child.Name); 
    end
  );

Or even:

WalkChildren(
  PageControl1, 
  procedure(Child: TControl) 
  begin 
    Memo1.Lines.Add(Child.Name); 
  end

Upvotes: 9

Related Questions