How to reset bindingsource filter to nothing

2020-04-28 21:02发布

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?

4条回答
放荡不羁爱自由
2楼-- · 2020-04-28 21:17

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.

查看更多
男人必须洒脱
3楼-- · 2020-04-28 21:28

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.

查看更多
贪生不怕死
4楼-- · 2020-04-28 21:30

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.

查看更多
别忘想泡老子
5楼-- · 2020-04-28 21:38

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;
    }
查看更多
登录 后发表回答