DataGridView Filter a BindingSource with a List of object as DataSource

后端 未结 3 1358
长发绾君心
长发绾君心 2020-12-14 03:23

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 s

相关标签:
3条回答
  • 2020-12-14 03:55

    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{ ... }, ... };
    
    0 讨论(0)
  • 2020-12-14 04:07

    I think it is because the BindingSource doesn't know what type of data it is filtering. Once a data is converted to dataset into columns and rows, filter can run. Because your datasource is a class, it can't do the automatic filtering.

    0 讨论(0)
  • 2020-12-14 04:08

    As an alternative to implementing IBindingListView which can be pretty involved you can try this type of filtering:

    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 讨论(0)
提交回复
热议问题