delphicomponents

Using FindComponent to find a control recursively


I created Layout1 dynamically.

object Layout1: TLayout
  Align = Client
  object Rect1: TRectangle
    Align = Client    
    object Button1: TButton
      Text = 'Test'
    end
  end
end

Why is it when I use Layout1.FindComponent('Button1'), it returns nil? (caps exactly)

I had thought that FindComponent is recursive?

Then I tried

if Layout1.FindComponent('Rect1') <> nil then;  // this find Rect1

but only when I set

Rect := Layout1.FindComponent('Rect1')

and then use

if Rect.FindComponent('Button1') <> nil then  // only then it works

any advice? confused by this FindComponent stuff. What is supposed to be recursive isn't recursive.

Or is it only .FindComponent that is recursive, and other components FindComponent is not recursive?


Solution

  • I had thought that FindComponent is recursive?

    No, it is not. It searches only for components that are directly owned by the component which you call FindComponent() on.

    Components that are created at design-time are owned by the top-level Form/Frame/DataModule, so you can call FindComponent() on that object to find design-time components.

    But, if you create components manually in code with different owners, then you will have to write the recursive logic yourself to search for nested components.