Click here to Skip to main content
Click here to Skip to main content

Filtering Records in Silverlight DataGrid using PagedCollectionView

, 7 Dec 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
In this article, we will see how this PagedCollectionView will help us to filter out the records based on the search keyword. Not much code but the trick done with the same class will do everything for us in some easy way. We will learn about this here in this article.

Introduction

In my last article, we discussed about “Grouping Records in Silverlight DataGrid using PagedCollectionView” where we grouped our data records by column name using the PagedCollectionView. In this article, we will see how this PagedCollectionView will help us to filter out the records based on the search keyword. Not much code but the trick done with the same class will do everything for us in some easy way. We will learn about this here in this article. Not only this, we will also see the filtering on top of the grouped records too. Read the complete article to see it in action.

Background

If you didn't read my previous article, I will ask you to read that article (“Grouping Records in Silverlight DataGrid using PagedCollectionView”) first and then come to read this one. It will help you in many cases to understand the basic requirement and the code. Now come to the actual article. In some cases, we need to filter the DataGrid records based on the search key. A DataGrid may contain a huge collection of data and in that case, finding a particular record is very difficult. At such a time, you need to filter the records.

image

In this article, we will implement the same filtering feature in some quick easy steps.

XAML Design

First of all, we need to redesign our existing XAML page with a Search TextBox as shown below:

image To do this, we need a TextBlock (which is optional) to label the TextBox. The TextBox is a mandatory field where you will be able to insert the search query. Whenever the end user types something here, the DataGrid will filter the records. Here is the complete XAML for your reference:
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:viewModels="clr-namespace:DataGridDemo1.ViewModels"
xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk" 
x:Class="DataGridDemo1.Views.MainView">
<UserControl.Resources>
<viewModels:MainViewModel x:Key="MainViewModel"/>
</UserControl.Resources>
<StackPanel x:Name="LayoutRoot" Background="White"
DataContext="{StaticResource MainViewModel}">
<StackPanel Orientation="Horizontal">
<ComboBox Width="200" Height="20" Margin="10"
HorizontalAlignment="Left" 
SelectionChanged="ComboBox_SelectionChanged">
<ComboBoxItem Content="City"/>
<ComboBoxItem Content="State"/>
<ComboBoxItem Content="Department"/>
</ComboBox>
<TextBlock Text="Filter Records by: " Height="20"/>
<TextBox Width="150" Height="25" TextChanged="TextBox_TextChanged"/>
</StackPanel>
<sdk:DataGrid 
IsReadOnly="True" Margin="10" Height="300" ItemsSource="{Binding Employees}"/>
</StackPanel>
</UserControl>

You will see that, not a big change there. We used one extra StackPanel to make our application UI layout clean and proper.

Playing with the Code

It’s time for us to write the code inside the ViewModel to do the filtering. Make sure that we will use the class named “PagedCollectionView” which we used earlier. Hence, we are familiar with the collection too. Add a private string variable called “searchKey” which we will use internally for our feature implementation. Now, write a new method “FilterDataBySearchKey()” passing the search key to it to store in the member variable. You will notice that, the PagedCollectionView has a property called “Filter” which takes Predicate. This Filter predicate will do the tricks for our requirement. Here, our PagedCollectionView is our collection named “Employees”. First of all, set the Filter of this collection to null to remove the previous filtering. Then, set a new Predicate function call to it. Inside the predicate action, do your filtering mechanism. Have a look into the below ViewModel code to understand the same:

private string searchKey;
 
/// <summary>
/// Filters the data by search key.
/// </summary>
/// <param name="searchKey">The search key.</param>
public void FilterDataBySearchKey(string searchKey)
{
this.searchKey = searchKey;
Employees.Filter = null;
Employees.Filter = new Predicate<object>(FilterRecords);
}
 
/// <summary>
/// Filters the records.
/// </summary>
/// <param name="obj">The obj.</param>
/// <returns></returns>
private bool FilterRecords(object obj)
{
var employee = obj as Employee;
 
return employee != null &&
(employee.Firstname.ToLower().IndexOf(searchKey) >= 0 ||
employee.Lastname.ToLower().IndexOf(searchKey) >= 0 ||
employee.City.ToLower().IndexOf(searchKey) >= 0 ||
employee.State.ToLower().IndexOf(searchKey) >= 0);
}

You will see that the FilterRecords() is the actual predicate to the PagedCollectionsView’s Filter key. Here we searched whether the “searchKey” is present in the Firstname, Lastname, City or State by using the IndexOf(). This will search anywhere in the value for the matching key. If you want to implement it for the first characters of string, you can use StartsWith() too. We are searching for only Firstname, Lastname, City and State. You can include more or reduce some too from the actual logic. As our actual code is ready, we need to integrate that with the TextChanged event. To do this, go to the code behind file and inside the TextBox_TextChanged event, get the search Key from the TextBox’s Text and pass it to the viewmodel’s method. Here is the same code:

private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
string searchKey = (sender as TextBox).Text.Trim().ToLower();
(Resources["MainViewModel"] as MainViewModel).FilterDataBySearchKey(searchKey);
}

Up to this, our full code has been implemented. No more code is required for our sample. Let's start running the application to see it in action, so that, we will be able to understand whether our code is working properly or not.

Playing with the Application

Let's build the source and run the application. You will see the same UI as we demoed in the previous article. Only change here is a TextBox which asks to enter the search key to filter the records.

image

Start typing something in the Filter box. You will notice that the records are automatically filtering out as per the entered term. This filtering is happening for both Firstname, Lastname, City and State as we implemented the logic for that only.

image

Nice, right? Wondering whether it will work for the grouped data? Let's have a try. Group the records by department and then type something in the search box.

image

You will see that the records are now filtered based on the key but in a grouped manner, i.e., department wise.

image

Modify to a different search term. You will notice the change in a fraction of second as and when you type something there in the search box.

image

We noticed that all the filtering is working with the value starting with the searched key. Let us check how it works for the searched key which is in the middle of the value.

image

Enter ‘w’ in the TextBox and you will see that the records which have ‘w’ inside any value, have been filtered properly.

Further Reading

End Note

Hope this article was also interesting & helpful for you like the previous one. Wish this will help you in future to filter out the DataGrid records. Many more things are there with DataGrid. I will post another article on the same soon and that will also help you with another importance of the same PagedCollectionView. Explore more to do lots of magic with DataGrid. Don’t forget to provide your feedback/suggestion. If you have any issue, drop a line here. I will try to answer you as soon as possible. Cheers!

History

  • 7th December, 2010: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Kunal Chowdhury (@kunal2383)
Team Leader
India India
Kunal Chowdhury is a Microsoft "Windows Platform Development" MVP (Most Valuable Professional), a Codeproject Mentor, Telerik MVP, Nokia Developer Champion, Speaker in various Microsoft events, Author, passionate Blogger and a Software Engineer by profession.
 
He is currently working in an MNC located in India. He has a very good skill over XAML, C#, Silverlight, Windows Phone, WPF and Windows Store (WinRT) app development. He posts his findings, articles, tutorials in his technical blog and CodeProject.
 
Technical Blog: http://www.kunal-chowdhury.com
Facebook: http://facebook.com/blog.kunal
Twitter : http://twitter.com/kunal2383
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
QuestionHelp filtering datagrid view from SQL through a service reference. PinmemberMember 1046328012-Dec-13 12:30 
QuestionGridview doesn't filtering data Pinmembermojamcpds00712-Jan-13 0:37 
QuestionNoob question Pinmemberkissarat18-Nov-12 8:39 
AnswerRe: Noob question Pinmvp_ Kunal Chowdhury _18-Nov-12 17:32 
SuggestionOne extra line in your code Pinmemberkissarat18-Nov-12 8:21 
AnswerRe: One extra line in your code Pinmvp_ Kunal Chowdhury _18-Nov-12 8:23 
QuestionSearch/filtering datagrid in silverlight PinmemberRicardo Araoz27-Jul-12 15:28 
AnswerRe: Search/filtering datagrid in silverlight Pinmvp_ Kunal Chowdhury _27-Jul-12 16:39 
Hi Ricardo,
 
The sample project was demonstrated in MVVM pattern and you are seeing ViewModel folder there. If you are not comfortable in MVVM, either you can use normal coding pattern or do a search to learn about MVVM.
 
ViewModels folder that is available in the project is not part of Silverlight project. I created this to separate the ViewModel namespace there. All the folders were created separately to give proper separation between the code files, so that one can easily navigate to all the files.
 
As I am not using any real database for this sample, I don't need any service. So, I used a class to return sample data. You can replace it by using the WCF Service call. This is just a sample to guide you the actual implementation of what the article title says and was not needed to make it complex by introducing additional services.
 
Let me know, if you still have doubts.
Regards - Kunal Chowdhury
Microsoft MVP (Silverlight) | Codeproject MVP & Mentor | Telerik MVP & Insider

 
Follow me on: My Technical Blog | Silverlight-Zone | Twitter | Facebook | Google+

GeneralRe: Search/filtering datagrid in silverlight PinmemberRicardo Araoz28-Jul-12 17:21 
SuggestionFound Some bugs Pinmemberparmarj23-Jul-12 5:07 
AnswerRe: Found Some bugs Pinmvp_ Kunal Chowdhury _23-Jul-12 5:19 
GeneralMy vote of 5 PinmemberDurgaprasadtb12-Jan-11 2:30 
GeneralRe: My vote of 5 PinmvpKunal_Chowdhury12-Jan-11 16:16 
GeneralMy vote of 5 Pinmemberprasad0222-Dec-10 5:36 
GeneralRe: My vote of 5 PinmentorKunal_Chowdhury31-Dec-10 17:18 
Generalyou are the hero PinmemberPranay Rana20-Dec-10 2:24 
GeneralRe: you are the hero PinmentorKunal_Chowdhury31-Dec-10 17:14 
GeneralMy vote of 5 PinmemberHiren Solanki9-Dec-10 21:40 
GeneralRe: My vote of 5 PinmentorKunal_Chowdhury10-Dec-10 6:44 
GeneralMy vote of 5 PinmvpAbhijit Jana7-Dec-10 6:12 
GeneralRe: My vote of 5 PinmentorKunal_Chowdhury7-Dec-10 7:25 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.141220.1 | Last Updated 7 Dec 2010
Article Copyright 2010 by Kunal Chowdhury (@kunal2383)
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid