如何按名称查找bindingSource?

时间:2019-01-24 04:38:34

标签: c# winforms reflection

我的winform中有很多bindingsource,并且我想动态更改gridview的dataSource,所以我想用那里的名字获取bindingSource。 我找到以下代码,从我的winform中找到所有bindingSource,

名称均值的bindingSource名称属性 在图片中,它的名称是“ bsSL070101”

enter image description here

    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.ToString().Contains("Windows.Forms.BindingSource")
               select component;
    }

获得BindingSourceList之后,我想按名称过滤其中一个,但是我不知道该怎么做,请帮助我,谢谢〜

    IEnumerable<Component> BindingSourceList = EnumerateComponents();
    //I wonder find a bindingSource by name, but it doesn't work
    BindingSource bb = BindingSourceList.find(a=>a.name=="bsSL070101");

1 个答案:

答案 0 :(得分:1)

组件仅在设计时具有名称。如果在运行时需要使用它们的名称来查找它们,则需要依赖字段名称。

以下代码段以Dictionary<string, BindingSource>的形式返回表单的所有字段:

var bindingSources = this.GetType().GetFields(System.Reflection.BindingFlags.NonPublic |
    System.Reflection.BindingFlags.Public |
    System.Reflection.BindingFlags.Instance)
    .Where(x => typeof(BindingSource).IsAssignableFrom(x.FieldType))
    .ToDictionary(x => x.Name, x => (BindingSource)x.GetValue(this));

您可以在字典中按名称查找绑定源:

var bs = bindingSources["categoriesBindingSource"];

注意:

  • 如果名称不重要,而您只需要使用设计器添加的实例:

    var bindingSources = this.components.Components.OfType<BindingSource>();