mardi 1 juillet 2014

Filter DataGridView out of the DbContext

Imagine you load data into a DataGridView.DataSource from a database.
Then you want to allow end user to filter the results, but without hitting database again.
So you use a TextBox to prompt a filter an, OnTextChanged
private void tbFilter_TextChanged(object sender, EventArgs e) {
    CurrencyManager cm = (CurrencyManager)BindingContext[dgvList.DataSource];
    cm.SuspendBinding();
    foreach (DataGridViewRow r in dgvList.Rows) {
        r.Visible = String.IsNullOrEmpty(tbFilter.Text) || r.Cells[1].Value.ToString().Contains(tbFilter.Text);
    }
    cm.ResumeBinding();
}
Here the difficulty is the use of a CurrencyManager.