It is quite simple to enumerate Form components

         for (int i=0;i<ComponentCount;i++)
         {
            ShowMessage(Components[i]->Name);
            //.....
         }

but the same thing does not work if I want to enumerate only the components which are located on Panel.

         for (int i=0;i<Panel1->ComponentCount;i++)
         {
            ShowMessage(Panel1->Components[i]->Name);
            //.....
         }

because

            Panel1->ComponentCount;

is just zero while having several components on Panel. So, how can I enumerate the child components of Panel?

有帮助吗?

解决方案

The ComponentCount and Components[] properties access a component's list of owned components - components that have the component set as their Owner by having that component passed to their constructor. All components created at design-time have the parent TForm (or TFrame or TDataModule) set as their Owner. Your first loop is iterating through the TForm's owned components, that is why it works. Your TPanel does not own any components, that is why the second loop fails.

What you are looking for is the ControlCount and Controls[] properties instead. They access a visual control's list of child controls instead - controls that have the parent control set as their Parent for purposes of visual representation. Only TWinControl-derived controls (like TPanel) can have child controls:

for (int i = 0; i < Panel1->ControlCount; ++i)
{
    ShowMessage(Panel1->Controls[i]->Name);
    //.....
}

其他提示

Enumerate all controls AND sub-controls (child controls of that control) of a form, panel, group box, etc:

void ExtractAll_Structure(TWinControl *container, int &indent)
{
   // Enumarate its children
   for (int i = 0; i < container->ControlCount; i++)
      {
      // extract the control at index i
      TComponent *child2 = container->Controls[i];

      if (child2->InheritsFrom (__classid(TComponent)) )  // this check if optional
         {
         Memo->Lines->Add(child2->Name);

         // Is this a container for other controls
         TWinControl *winctrl = dynamic_cast<TWinControl *>(child2);
         if (winctrl)
            {
            indent++;
            ExtractAll_Structure(winctrl, indent);
            indent--;
            }
         }
      }
}

Also see: BCB : how to iterate over controls on a form?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top