Form to object and loop through objects in c#?

.net, c#, object, winforms

Solution

Each `Control` has a `Controls` collection that you can iterate through to get the full hierarchy, but unfortunately `ToolStrip` items use a different object model (they aren't all `Control`s); as such, you can iterate such a setup (to include the menu items too), but it isn't trivial; here's an example:

    IEnumerable RecurseObjects(object root) {
        Queue items = new Queue();
        items.Enqueue(root);
        while (items.Count > 0) {
            object obj = items.Dequeue();
            yield return obj;
            Control control = obj as Control;
            if (control != null) {
                // regular controls and sub-controls
                foreach (Control item in control.Controls) {
                    items.Enqueue(item);
                }
                // top-level menu items
                ToolStrip ts = control as ToolStrip;
                if (ts != null) {
                    foreach(ToolStripItem tsi in ts.Items) {
                        items.Enqueue(tsi);
                    }
                }
            }
            // child menus
            ToolStripDropDownItem tsddi = obj as ToolStripDropDownItem;
            if (tsddi != null && tsddi.HasDropDownItems) {
                foreach (ToolStripItem item in tsddi.DropDownItems) {
                    items.Enqueue(item);
                }
            }
        }            
    }

You might call this, for example, via something like:

    foreach (object obj in RecurseObjects(this)) {
        Console.WriteLine(obj);
    }

Of course, then the question is: what do you want to do with each item?

Problem

I have a main form `(frmMain)`, with some buttons `(button1, button2...)`. then I do this: ``` object objectsContainer = frmMain; // <--now the object contains form base, button1, button2... ``` how could I loop through all containing items in my object to access butto1, button2...??? I did this, but it's not what I want. ``` foreach (PropertyInfo pInfo in objectsContainer.GetType().GetProperties()) { } ``` I want to do something like this: ``` foreach (object objectFromForm in objectsContainer) // <--- how to do this looping an object (type of form) { //here is objectFromForm = base, button1, button2... foreach (PropertyInfo pInfo in objectFromForm .GetType().GetProperties()) { //here it's possible to access pInfo and its properties like size, name ... } } ``` When I'm debuggin and looking at the content of objectsContainer there are all "infos" that I want. Some suggestions?? Best regards. ** UPDATE: ** OK, I made a test project. There you could see what I want to do. In the project is an image with the objects... Here you can download it: http://www.mediafire.com/download.php?ik5j3ejnzm2 Best regards.

Original source