Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
985 views
in Technique[技术] by (71.8m points)

c# - DataGridView Filter a BindingSource with a List of object as DataSource

I'm trying to filter a BindingSource with a BindingList as Datasource. I tried BindingSource.Filter = 'Text Condition' But it didn't work, nothing happens, the data on screen remains the same. But if i use a DataSet as the datasource it works. Is It possible to filter a list of objects with the BindingSource.Filter property?

I have the following 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; }
        }

This is how i use it:

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'";

This is just an example the idea is to test if a can filter a data source like that. I will use the knowledge inside a new project.

pd: The idea is to be able to use BindingSource.Filter if it is possible.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Only underlying lists that implement the IBindingListView interface support filtering.

BindingList<T> does not appear to implement IBindingListView - and since it is the underlying list, your collection will not filter.

BindingSource class, while not generic, does implement this Interface, so try using this as your personas collection. I get the feeling that simply assigning a new BindingSource's datasource to a BindingList won't suffice, since it doesn't change the underlying list. Try:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...