Search code examples
c#wpfcollectionview

How can I use search in the grid using CollectionView with multiple conditions?


I have Textbox and Comboboxs and a GridView and I would like to filter some columns of the grid with all controls ( Comboboxs and the Textbox ) , I have this code that return a view filtered with one condition ( Textbox ) to a custom column .

Remark: I'm not using MVVM pattern.

    GridView.ItemsSource = MyList.ToList();
    ListCollectionView view = (ListCollectionView)CollectionViewSource.GetDefaultView(MyList);

    view.Filter = delegate (object item) { return (item as User).Name.Contains(Name_txt.Text); };
    GridView.ItemsSource = view;


    public class User 
     {
       public Id { get; set; }
       public Name { get; set; }
     } 

How can I filter the datagrid columns with more than one condition ( input ) ?


Solution

  • You should add all conditions to the Filter predicate, e.g.:

    view.Filter = delegate (object item)
    { 
        User user = item as User;
        if (user == null)
            return false;
    
        return user.Name.Contains(Name_txt.Text)
            && comboBox1.SelectedItem == ?
            && ...; 
    };