How to reset bindingsource filter to nothing

ぃ、小莉子 提交于 2019-12-20 04:13:16

问题


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?


回答1:


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.




回答2:


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.




回答3:


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;
    }



回答4:


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.



来源:https://stackoverflow.com/questions/11764574/how-to-reset-bindingsource-filter-to-nothing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!