I have a gridview that takes in values from a sortedlist. I want to filter those values before putting them in the gridview without taking values out of the list.
Is there an easy way to do this? Or do I have to redirect the data through another list and point the gridview to it?
There are probably a number of ways to do this, but none are magic. All involve some work.
If the list is in memory, yes, you’ll have to wash the list through a filtering process before binding to the grid.
If the list comes from a database, then you should be doing the filtering at the database level. The way I prefer to do this is by binding the grid to an ObjectDataSource. You can also bind other controls in the UI as select parameters in the ObjectDataSource. (You can also do sorting and paging through the ObjectDataSource, so that everything can be built in to your database query, and the grid binds only to the data you want to display.)
Here’s an ObjectDataSource fully configured:
Note that it is binding to a dropdown list for selection in the database query.
Here’s the grid, with binding:
Here’s the method the ObjectDataSource binds to for selection:
The Load method builds the query and runs it, then returns the data. It can be either an IEnumerable or List, as you see here, or a DataSet or DataTable. That should get you started.
One nice thing is that the code-behind is almost empty now. It only needs to handle events that don’t relate to binding, sorting, or paging.