DataGridView 使用对象列表作为数据源筛选绑定源

本文关键字:数据源 筛选 绑定 对象 列表 DataGridView | 更新日期: 2023-09-27 18:30:25

我正在尝试使用BindingList作为数据源来过滤BindingSource。我尝试了BindingSource.Filter ='文本条件'但它不起作用,没有任何反应,屏幕上的数据保持不变。但是,如果我使用数据集作为数据源,它可以工作。是否可以使用 BindingSource.Filter 属性筛选对象列表?

我有以下课程:

class Person
        {
            public String Nombre { get; set; }
            public String Apellido { get; set; }
            public int DNI { get; set; }
            public int Edad { get; set; }
            public Decimal Tamano { get; set; }
        }

这是我使用它的方式:

BindingList<Person> personas = new BindingList<Person> { 
                new Person{ Apellido = "App1", DNI = 3011, Edad = 20, Nombre ="Name1", Tamano = new decimal(1.7)}
                ,new Person{ Apellido = "App2", DNI = 1520, Edad = 30, Nombre ="Name2", Tamano = new decimal(1.5)}
                ,new Person{ Apellido = "App3", DNI = 5654, Edad = 21, Nombre ="Name3", Tamano = new decimal(1.6)}
                ,new Person{ Apellido = "App4", DNI = 778, Edad = 40, Nombre ="Name4", Tamano = new decimal(1.68)}
            };
            BindingSource bs = new BindingSource();
            bs.DataSource = personas;
            grid.DataSource = bs;
            bs.Filter = "Apellido like 'App1'";

这只是一个例子,这个想法是测试是否可以像这样过滤数据源。我将在新项目中使用这些知识。

pd:我们的想法是,如果可能的话,能够使用BindingSource.Filter。

DataGridView 使用对象列表作为数据源筛选绑定源

根据

http://msdn.microsoft.com/en-us/library/system.windows.forms.bindingsource.filter.aspx

只有实现IBindingListView接口的基础列表才支持筛选。

BindingList<T>似乎没有实现IBindingListView - 并且由于它是基础列表,因此您的集合不会筛选。

BindingSource 类虽然不是泛型的,但确实实现了此接口,因此请尝试将其用作角色集合。我感觉简单地将新的绑定源的数据源分配给绑定列表是不够的,因为它不会更改基础列表。尝试:

BindingSource personas = new BindingSource { new Person{ ... }, ... };

作为实现IBindingListView的替代方法,您可以尝试这种类型的过滤:

BindingList<Person> personas = new BindingList<Person> {  
new Person{ Apellido = "App1", DNI = 3011, Edad = 20, Nombre ="Name1", Tamano = new decimal(1.7)} 
,new Person{ Apellido = "App2", DNI = 1520, Edad = 30, Nombre ="Name2", Tamano = new decimal(1.5)} 
,new Person{ Apellido = "App3", DNI = 5654, Edad = 21, Nombre ="Name3", Tamano = new decimal(1.6)} 
,new Person{ Apellido = "App4", DNI = 778, Edad = 40, Nombre ="Name4", Tamano = new decimal(1.68)} 
};
BindingList<Person> filtered = new BindingList<Person>(personas.Where(
                                 p => p.Apellido.Contains("App1")).ToList());
grid.DataSource = filtered;
我认为

这是因为BindingSource不知道它正在过滤什么类型的数据。将数据转换为数据集为列和行后,可以运行筛选器。由于数据源是一个类,因此无法执行自动筛选。