簡體   English   中英

DataGridView 使用 object 列表過濾 BindingSource 作為數據源

[英]DataGridView Filter a BindingSource with a List of object as DataSource

我正在嘗試使用 BindingList 作為數據源來過濾 BindingSource。 我嘗試了 BindingSource.Filter = 'Text Condition' 但它沒有用,沒有任何反應,屏幕上的數據保持不變。 但是,如果我使用 DataSet 作為數據源,它就可以工作。 是否可以使用 BindingSource.Filter 屬性過濾對象列表?

我有以下 class:

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。

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

只有實現IBindingListView接口的底層列表才支持過濾。

BindingList<T>似乎沒有實現IBindingListView - 因為它是基礎列表,所以您的集合不會過濾。

BindingSource class 雖然不是通用的,但確實實現了此接口,因此請嘗試將其用作您的角色集合。 我感覺僅僅將新的 BindingSource 的數據源分配給 BindingList 是不夠的,因為它不會更改基礎列表。 嘗試:

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 不知道它正在過濾什么類型的數據。 一旦將數據轉換為數據集的列和行,過濾器就可以運行。 因為你的數據源是class,所以不能自動過濾。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM