DataGridView使用List对象筛选BindingSource作为DataSource

我正在尝试使用BindingList作为数据源过滤BindingSource。 我尝试了BindingSource.Filter =’Text Condition’但它没有用,没有任何反应,屏幕上的数据保持不变。 但是如果我使用DataSet作为数据源它可以工作。 是否可以使用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 personas = new BindingList { 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。

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

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

BindingList似乎没有实现IBindingListView – 因为它是底层列表 ,所以您的集合不会被过滤。

BindingSource类虽然不是通用的,但确实实现了这个接口,所以尝试使用它作为你的角色集合。 我觉得简单地将一个新的BindingSource的数据源分配给BindingList是不够的,因为它不会改变底层列表。 尝试:

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

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

 BindingList personas = new BindingList { 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 filtered = new BindingList(personas.Where( p => p.Apellido.Contains("App1")).ToList()); grid.DataSource = filtered; 

我认为这是因为BindingSource不知道它正在过滤哪种类型的数据。 将数据转换为数据集到列和行后,就可以运行filter。 因为您的数据源是一个类,所以它无法进行自动过滤。