Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find components on a windows form c# (not controls)

I know how to find and collect a list of all the controls used in a Windows Form. Something like this:

static public void FillControls(Control control, List<Control> AllControls)
{
    String controlName = "";
    controlName = control.Name;

    foreach (Control c in control.Controls)
    {
        controlName = c.Name;
        if ((control.Controls.Count > 0))
        {
            AllControls.Add(c);
            FillControls(c, AllControls);
        }
    }
}

However this function does not retrieve the non-visual components on the bottom of the form like the HelpProvider, ImageList, TableAdapters, DataSets, etc.

Is there a way to get the list of these components as well?

Edit:

Thanks @HighCore for pointing me to use System.ComponentModel.Component instead in a similar function does get me a list with components such the ImageList, the Help Provider and the BindingSource. However, I still miss from this list the TableAdapters and the DataSets. I suppose because those inherit directly from Object.

Please. Don't refer me to older posts which shows a similar function to mine and that only gets the list of the controls.

Edit: Why the negative votes? This question has never been answered before!

like image 842
Craig Stevensson Avatar asked Jun 18 '13 14:06

Craig Stevensson


People also ask

Where do I find labels in Windows form?

On the tab "Properties" just click on the arrow to show all controls and click on the label you want, this will automatically select the label on your form..

Does Microsoft still support WinForms?

The latest version of Windows Forms is for . NET 6 using Visual Studio 2022 version 17.0. The . NET Framework 4 implementation that's supported by Visual Studio 2022, Visual Studio 2019, and Visual Studio 2017.

How do I add a component to Windows form?

Add a component to a Windows FormOpen the form in Visual Studio. For details, see How to: Display Windows Forms in the Designer. In the Toolbox, click a component and drag it to your form. Your component appears in the component tray.


1 Answers

Surprisingly, it seems the only way to do this is via reflection.

private IEnumerable<Component> EnumerateComponents()
{
    return from field in GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
           where typeof (Component).IsAssignableFrom(field.FieldType)
           let component = (Component) field.GetValue(this)
           where component != null
           select component;
}
like image 106
Michael Gunter Avatar answered Oct 18 '22 23:10

Michael Gunter