Using BindingSource
on LINQ to SQL, and having implemented a BindingList
in my project, I have to use a Textbox
to filter rows in a DataGridView
, so when I delete the textbox content, Filter should be reset to nothing.
My code is as follows:
if (textBox1.Text.Length == 0)
{
productBindingSource.Filter = null;
}
else
{
productBindingSource.Filter = "ProductName = '" + textBox1.Text +"'";
//productBindingSource.RemoveFilter();
}
productDataGridView.DataSource = productBindingSource;
But this does nothing, any idea, please?
Try it like this:
if (textBox1.Text.Length == 0) {
productBindingSource.RemoveFilter();
} else {
productBindingSource.Filter = "ProductName = '" + textBox1.Text +"'";
}
// productDataGridView.DataSource = productBindingSource;
The DataGridView shouldn't need to be DataSourced again if it's already using productBindingSource.
http://msdn.microsoft.com/en-us/library/system.windows.forms.bindingsource.filter.aspx
as shown there the bindingsource.Filter
is a string value. And default is null, so just do this:
productBindingSource.Filter = null;
its possible though that you have to do something to update your UI but usually the bindingSource takes care of that itself.
I found that "Find" method cannot be used directly with BindingList, but fortunately there is an alternative, using IEnumerable. After Implementing a BindingList in the project, I can filter a bound datagridview using the next code:
private void button1_Click(object sender, EventArgs e)
{
var qry = (from p in dc.Products
select p).ToList();
BindingList<Product> list = new BindingList<Product>(qry);
IEnumerable<Product> selection = list.Where(m => m.ProductName.Contains(textBox1.Text) == true);
productBindingSource.DataSource = selection;
}
I assume you test if textbox is empty in TextChanged event.
Maybe your method is not being called when Text length = 0.
I don't remember exactly why but i experienced this case before.
If you are using a BindingList you wrote, provide code.
RemoveFilter, setting Filter to null or empty string has always worked for me.