Filtering data in a datagrid can be achieved by attaching the data source of the datagrid with a ListCollectionView object and then set the Filter property with a private method that has the logic to filter the data in the ListCollectionView object based on the object passed.
In this sample I will show how to filter data in the Grid based on Employees FirstName
I have added the event handler for the window loaded event to set the ItemsSource property of the Grid as
private void OnWindowLoaded(object sender, RoutedEventArgs e)
{
ListCollectionView dgcv = new ListCollectionView(new List<UIEmployee>(_employeeDataGrid.ItemsSource as ObservableEmployee));
dgcv.Filter = SearchFilter;
_employeeDataGrid.ItemsSource = dgcv;
}
The search filter method is implemented as
private bool SearchFilter(object sender)
{
if (_searchTextBox == null)
return true;
string search = _searchTextBox.Text;
UIEmployee item = (UIEmployee)sender;
if (!string.IsNullOrEmpty(search))
{
if (item.FirstName.ToLower().Contains(search.ToLower()))
return true;
return false;
}
return true;
}
For entering the search text for searching, we need to add a text box and an event handler to the TextChanged event of the textbox as
<TextBox Name="_searchTextBox" TextChanged="OnSearchChanged" Width="150" Margin="8 0 0 0" Height="25">TextBox>
The event handler code is given as
private void OnSearchChanged(object sender, TextChangedEventArgs e)
{
((ListCollectionView)_employeeDataGrid.ItemsSource).Refresh();
}
Output
The next part of the series I'll show how to display data with Master- Detail relationship on the WPF DataGrid.