Posted: 17 Nov 2020 14:32 EST Last activity: 20 Nov 2020 13:39 EST
RDA - WinForm - How to reliably iterate through all controls under parent WinForm (Or select controls of specific type)
I've run into an issue where attempting to loop recursively down the child controls from a top-level WinForm will miss certain controls, namely TreeViews. If I add a panel as the first child of the WinForm, then recursively loop through all the controls of the WinForm AND the first-child Panel, all controls are reached. @jeffbadger, is there a better way to do this?
I would write a recursive method that you can call that takes in a generic control. Every control has a property called Controls. This is an array of child controls. If your control has any children, they would be in this array. You might also have grandchildren and great grandchildren, so making a method that you can call recursively would be best. I don't have an example, but perhaps if you share your script, I could tweak it.
Here is a script we use for styling our UIs. As you can see it iterates through a Control's Controls property and checks to see if it HasChildren. If it does, it style the control and then calls this method again passing itself as the object this time. You can tweak this as needed.
I did not take out any of the dependencies so it won't build until you edit it a bit to remove methods you won't have, but it will get you started.
Posted: 1 month ago
Updated: 1 month ago
Posted: 20 Nov 2020 13:38 EST Updated: 20 Nov 2020 13:39 EST
If navigating through the controls collection doesn't work you can use the OpenSpan.Utils.HierarchyHelper to iterate through the children of any parent. Check out the included scripts. They take a parent and using the GetAllChildren method return an array of IComponents. These can then be cast to the appropriate base class - System.Windows.Forms.Control for a Win Form and OpenSpan.Adapters.IControl for a Windows Adapter. You can obviously cast to the actual type if you need specialized properties but the base class may suffice.