Search code examples
c#wpfdatagridwpfdatagrid

How to perform text search on datagrid?


May I know, how can I perform search on this default DataGrid? While added the value on it.

<DataGrid Name="table" AutoGenerateColumns="False" CanUserAddRows="False" CanUserDeleteRows="False" IsTextSearchEnabled="True" Background="White">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Timestamp" Binding="{Binding StartDate}" SortDirection="Descending" SortMemberPath="StartDate" IsReadOnly="True" />
        <DataGridTextColumn Header="Title" Binding="{Binding Title}" IsReadOnly="True" />
        <DataGridTextColumn Header="Description" Binding="{Binding Description}" IsReadOnly="True" />
        <DataGridTextColumn Header="Type" Binding="{Binding Tag}" IsReadOnly="True" />
    </DataGrid.Columns>
</DataGrid>

Solution

  • How to Create and Use a CollectionView

    The following example shows you how to create a collection view and bind it to a ListBox In the same way you can use it with datagrid

    <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
        <ListBox ItemsSource={Binding Customers} />
    </Window>
    
    public class CustomerView
    {
       public CustomerView()
       {
            DataContext = new CustomerViewModel();
       }
    }
    
    
    public class CustomerViewModel
    {
        private ICollectionView _customerView;
    
        public ICollectionView Customers
        {
            get { return _customerView; }
        }
    
        public CustomerViewModel()
        {
            IList<Customer> customers = GetCustomers();
            _customerView = CollectionViewSource.GetDefaultView(customers);
        }
    }
    

    Filtering

    To filter a collection view you can define a callback method that determines if the item should be part of the view or not. That method should have the following signature: bool Filter(object item). Now set the delegate of that method to the Filter property of the CollectionView and you're done.

    ICollectionView _customerView = CollectionViewSource.GetDefaultView(customers);
    _customerView.Filter = CustomerFilter
    
    private bool CustomerFilter(object item)
    {
        Customer customer = item as Customer;
        return customer.Name.Contains( _filterString );
    }
    

    Refresh the filter

    If you change the filter criteria and you want to refresh the view, you have to call Refresh() on the collection view

    public string FilterString
    {
      get { return _filterString; }
      set 
      { 
          _filterString = value; 
          NotifyPropertyChanged("FilterString");
          _customerView.Refresh();
      }
    }