Filter a DataGr > Ask Question
I load a lists of objects in a datagrid with this:
The model become data from a database. It has a Id(int) , Name(string) and Text(string)
In my datagrid I show only the Name of the model . How can I filter the datagrid now, when I enter something in a textbox?
I was at this page: http://msdn.microsoft.com/en-us/library/vstudio/ff407126(v=vs.100).aspx but I don’t understand the code from there and I can not explain how I should transpose that for my problem.
5 Answers 5
there are multiple way’s to filter Collection
let’s suggesting this is your Item Class
and your collection looks like
Way 1 (Predicate):
Way 2 (FilterEventHandler):
extended Information to Way 1
if need multiple conditions or some complex Filter you can add a method to your Predicat
This is a simple implementation of using the Filter property of ICollectionView. Suppose your XAML contains this:
Then in the constructor you can get the default view for your data where you can set the filter predicate which will be executed for every item of your collection. The CollectionView won’t know when it should update the collection, so you have to call Refresh when the user clicks the search button.
At this url you can find a more detailed description of CollectionViews: http://wpftutorial.net/DataViews.html
@WiiMaxx, can’t comment as not enough rep. I would be a bit more careful about the direct casts there. They can be slow for one thing and for another, if the same filter was applied to a grid holding different complex type data you would have an InvalidCastException.
This will not break you datagrid and will not filter the results if the cast fails. Less impact to your users if you get the code wrong. On top of that the filter will be faster due to the “as” operator not doing any explicit type coercion as the direct cast operation will.
take at look at DataBinding –> in your case dont add items to your grid, but set the itemssource
and if you want some kind of filtering,sorting, grouping look at CollectionView
You can use dataview filter in order to filter the datagrid rows.
Where the “datatable” is datasource given to your datagrid and using string builder you build the filter query where “Filter String” is the text you want to search in your datagrid and set it to dataview and finally set the dataview as itemsource to your datagrid and refresh it.
Not the answer you’re looking for? Browse other questions tagged c# wpf datagrid filter or ask your own question.
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2019 Stack Exchange Inc; user contributions licensed under cc by-sa 4.0 with attribution required. rev 2019.10.7.35126