I need to filter database data based on filters available to the end user in the form of search term text box, select boxes etc.
I have put together this code and need feedback if this is a good way to do it or if there are any better solutions.
using Multi.Model;
using System;
using System.Linq;
using System.Windows.Controls;
namespace Multi.Pages
{
/// <summary>
/// Interaction logic for Page1.xaml
/// </summary>
public partial class Page1 : Page
{
public Page1()
{
InitializeComponent();
textBoxName.TextChanged += TextBoxName_TextChanged;
PopulateDataGrid();
}
private void PopulateDataGrid()
{
using (var db = new optisysEntities())
{
var items = db.clients.AsQueryable();
items = FilterClients(db, items);
dataGrid.ItemsSource = items.ToList();
}
}
private System.Linq.IQueryable<Multi.Model.clients> FilterClients(optisysEntities db, System.Linq.IQueryable<Multi.Model.clients> clients)
{
if (!String.IsNullOrWhiteSpace(textBoxName.Text)) clients = db.clients.Where(c => c.name.Contains(textBoxName.Text)
|| c.phone.Contains(textBoxName.Text));
// if (!String.IsNullOrWhiteSpace(search.Email)) clients = clients.Where(u => u.Email.Contains(search.Email));
// if (search.UsertypeId.HasValue) clients = clients.Where(u => u.UsertypeId == search.UsertypeId.Value);
return clients;
}
private void TextBoxName_TextChanged(object sender, TextChangedEventArgs e)
{
PopulateDataGrid();
}
}
}