如何按名称查找bindingSource?

Mia Huang

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

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

在此处输入图片说明

    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");
雷扎·阿盖伊

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

以下代码段以形式返回表单的所有字段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>();
    

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章