2012-04-09 41 views
12

我試圖篩選的BindingSource用的BindingList作爲數據源。我試過BindingSource.Filter ='Text Condition'但它沒有工作,沒有任何反應,屏幕上的數據保持不變。但是,如果我使用DataSet作爲它的數據源的作品。是否可以使用BindingSource.Filter屬性過濾對象列表?的DataGridView過濾一個BindingSource的與對象的列表作爲數據源

我有以下類:

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如果可能的話。

回答

7

按照實現該IBindingListView接口支持過濾http://msdn.microsoft.com/en-us/library/system.windows.forms.bindingsource.filter.aspx

只有基礎列表。

BindingList<T>似乎並沒有實現IBindingListView - 而且因爲它是基礎列表,你的收藏將不會進行篩選。

BindingSource類,而不是通用的,確實實現了這個接口,所以儘量使用這個作爲你的角色的集合。我覺得簡單地將一個新的BindingSource的數據源分配給一個BindingList是不夠的,因爲它不會改變基礎列表。嘗試:

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

謝謝!有了你的信息,我發現IBindingListView的實現,它的工作原理。這裏是鏈接:http://blogs.msdn.com/b/winformsue/archive/2008/05/19/implementing-filtering-on-the-ibindinglistview.aspx – 2012-04-09 14:20:48

+1

我碰到這個前幾年,該溶液來爲我工作得很好。今天我使用相同的代碼只是有點不同:需要兩個datagridviews顯示相同的FilteredBindingList具有不同的過濾/排序選項。 有關如何實現這一目標的任何想法? – Afshin 2015-07-29 00:38:06

1

我想這是因爲BindingSource的不知道它是過濾什麼類型的數據。將數據轉換爲數據集後,可以運行過濾器。因爲你的數據源是一個類,所以它不能進行自動過濾。

+0

感謝您的時間和信息。 – 2012-04-09 14:21:11

2

作爲替代實施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; 
+0

謝謝!這是一個替代方案。但想法是能夠使用BindingSource.Filter屬性。謝謝你的時間 – 2012-04-09 14:22:13

相關問題