Filtering Linq queries with a LinqDataSource control is easy, you can set a where clause and use a property of a control as an input parameter. If however you want to bind a Linq query as the data source for a GridView (or some other binable control) that’s filtered by a set of controls in code, it gets a little more tricky.
This tutorial gives a simplistic way of doing it that’s always worked for me.
What we need to do:
1. Setup the data
2. Setup your controls
3. Write your dynamic Linq query
4. Bind it to your GridView
Setup the data:
For our example, let’s suppose we have a ‘Customers’ table and an ‘Orders’ table. They are linked by a primary key where customers have multiple orders.
Setup your controls:
Add your controls to the form by dragging them on to the design surface. You can bind them to datasource controls or build the datasource dynamically with Linq and bind the control to that.
For our example we’ll have two controls a ‘Surname’ textbox control and an ‘Order type’ dropdown control. The Linq query will be filtered by what the user either enters or selects in the dropdown control.
Write your dynamic Linq query:
The Linq query utilises simple logic to filter the result based on whether the user has entered a surname or selected an option in the dropdown list.
var filteredClients = from c in db.Clients where (c.Surname == txtName.Text || txtName.Text.Length == 0) && (c.Orders.OrderType.ID == ddlOrderType.SelectedValue || ddlOrderType.SelectedIndex == 0) orderby c.DateOfOrder descending select o
If the user does not select an option in the dropdown or does not enter a surname then the query does not apply the corresponding filter. Essentially, the filter is only applied if the user has chosen to enter/select something on the control.