I need to traverse all controls and components inside a UserControl I’m developing.
I tried:
public void Traverse(Control cnt)
{
foreach (Control c in cnt.Controls)
{
if (c.HasChildren) Traverse(c);
Debug.Print(c.Name); // For debugging purpose only
// My code goes here
}
}
Problem raises when functions meets a ToolStrip: it has no children, but Items (ToolStripItemCollection: IList, ICollection, IEnumerable).
I don’t care of type: using Reflection I need to set some property, so I feel good having objects as result.
How can I get the name of every component that is inside my UserControl?
Thanks
I’ve written a version that goes through the control’s properties and looks for
IComponents that haveICollections on them:Method:
Called:
I’ve tested this and it seems to find every control on the form. I haven’t tested it for every kind of control and I can’t vouch for how efficient it is.