Search code examples
.netwinformsuser-controlsbindingsource

WinForms: How to find all BindingSources in an UserControl


In the program we are working on, the user data is collected in UserControls which is data bound to a business entity using BindingSources.

I need to find all the BindingSources in a UserControl programatically.

Since a BindingSource source is not added to the UserControl's Controls collection, I cannot search in there.

Can this be done?


Solution

  • The biggest problem was to find a solution for my method to be available for all the UserControls and still be able to use the WinForms designer from Visual Studio.

    Because I don't know any way of using the designer on a class that does not derive from UserControl, I have made an interface without any methods, IBusinessEntityEditorView, and an extension method that takes such a view, uses reflection to find the components field in which I search for my BindingSources:

    public interface IBusinessEntityEditorViewBase
    {
    }
    
    ...
    
    public static void EndEditOnBindingSources(this IBusinessEntityEditorViewBase view)
    {
        UserControl userControl = view as UserControl;
        if (userControl == null) return;
    
        FieldInfo fi = userControl.GetType().GetField("components", BindingFlags.NonPublic | BindingFlags.Instance);
        if (fi != null)
        {
            object components = fi.GetValue(userControl);
            if (components != null)
            {
                IContainer container = components as IContainer;
                if (container != null)
                {
                    foreach (var bindingSource in container.Components.OfType<BindingSource>())
                    {
                        bindingSource.EndEdit();
                    }
                }
            }
        }
    }