Search code examples
c#wpffilterdatagrid

WPF filter datagrid through textbox


I have been searching everywhere and I cannot find a way to filter my datagrid based on my textBox's value. I have a simple DataGrid:

<DataGrid Name="myGrid" HorizontalAlignment="Left" Height="399" 
                  Margin="272,150,0,0" VerticalAlignment="Top" Width="735"/>

When my form loads. I have this function to fill datagrid :

public MainWindow()
{
    InitializeComponent();
    myGrid.ItemsSource = datatable;
}
 

I have a TextBox name "txtSearch" and my goal is to filter the datagrid and find all rows that contain txtSearch.Text (and hide the other rows)

Could someone provide an example ?


Solution

  • You could set the RowFilter property of the DataView to a filter expression. This is how you would filter a DataTable.

    Here is a basic example that should give you the idea:

    public partial class MainWindow : Window
    {
        DataTable _dataTable;
        public MainWindow()
        {
            InitializeComponent();
            _dataTable = new DataTable();
            _dataTable.Columns.Add(new DataColumn("Name"));
            _dataTable.Columns.Add(new DataColumn("Id"));
            _dataTable.Rows.Add("First", "1");
            _dataTable.Rows.Add("Second", "2");
            myGrid.ItemsSource = _dataTable.DefaultView;
        }
    
        private void txtSearch_TextChanged(object sender, TextChangedEventArgs e)
        {
            string filter = txtSearch.Text;
            if (string.IsNullOrEmpty(filter))
                _dataTable.DefaultView.RowFilter = null;
            else
                _dataTable.DefaultView.RowFilter = string.Format("Name Like '%{0}%' OR Id Like '%{0}%'", filter);
        }
    }