Ivan-Mark Debono
Ivan-Mark Debono

Reputation: 16280

How to get all bindingsources on a form

I have a base form with one BindingSource on it. I have a second form that inherits from the the base form, and this second form has an additional 5 binding sources.

I want to get the list of binding sources that I have in the second form (ie. 6).

So, in the OnLoad of the base form, I first tried:

var list = this.Controls.OfType<BindingSource>();

But I only got the base form's bindingsource. Then I tried:

var List = (from Component bs in this.components.Components
            where bs is BindingSource
            select bs);

Which also returns the same bindingsource.

Doing the above in the OnLoad of the base form should work because I can get all controls of the second form.

However, I cannot seem to get the binding sources of the second form.

So what is the correct way to list them?

Upvotes: 3

Views: 959

Answers (1)

LarsTech
LarsTech

Reputation: 81610

Using the answer from Find components on a windows form c# (not controls), the accepted answer was returning some controls, so I added a check for the Name property (which components don't have at runtime):

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
         where component.GetType().GetProperty("Name") == null
         select component;
}

Upvotes: 3

Related Questions