【问题标题】:How to reset bindingsource filter to nothing如何将绑定源过滤器重置为空
【发布时间】:2012-08-01 17:36:52
【问题描述】:

在 LINQ to SQL 上使用BindingSource,并在我的项目中实现了BindingList,我必须使用Textbox 过滤DataGridView 中的行,所以当我删除文本框内容时,过滤器应该重置为空。

我的代码如下:

if (textBox1.Text.Length == 0)
{
    productBindingSource.Filter = null;
}
else
{
    productBindingSource.Filter = "ProductName = '" + textBox1.Text +"'";
    //productBindingSource.RemoveFilter();
}
productDataGridView.DataSource = productBindingSource;

但这没有任何作用,请问有什么想法吗?

【问题讨论】:

    标签: .net winforms c#-4.0 bindingsource bindinglist


    【解决方案1】:

    试试这样:

    if (textBox1.Text.Length == 0) {
      productBindingSource.RemoveFilter();
    } else {
      productBindingSource.Filter = "ProductName = '" + textBox1.Text +"'";
    }
    
    // productDataGridView.DataSource = productBindingSource;
    

    如果 DataGridView 已经在使用 productBindingSource,则不需要再次进行 DataSourced。

    【讨论】:

    • 这个也不行,我已经测试过了。请在我的问题中查看评论中的代码行
    • @AlphaBird 不确定“请参阅我的问题中的注释代码行”是什么意思?您的 productBindingSource 是否来自 BindingList?
    • 在我的问题中你可以找到这个://productBindingSource.RemoveFilter();表示我已经尝试过 RemoveFilter。是的,我已经将一个 BindingList 传递给我的 productBindingSource,它已经在为“Find”方法工作了。
    • @AlphaBird 嗯,不知道过滤器是否适用于 BindingList。我发布的代码适用于 DataTable。
    • 也试过this,但 FindAll 无法识别。
    【解决方案2】:

    http://msdn.microsoft.com/en-us/library/system.windows.forms.bindingsource.filter.aspx

    如图所示,bindingsource.Filter 是一个字符串值。并且默认为 null,所以只需这样做:

    productBindingSource.Filter = null;
    

    虽然您可能需要做一些事情来更新您的 UI,但通常 bindingSource 会自行处理。

    【讨论】:

    • 这不起作用,您的链接提供了数据集类型数据源的代码。请看一下我最初的问题更新。
    • 如果这样做会发生什么productBindingSource.Filter = "";
    • 没什么,因为Filter不能直接作用于bindingSource控件,所以需要在项目中实现一个BindingList并使用IEnumerable来达到这个目的,请look at this知道如何实现项目中的 BindingList。
    【解决方案3】:

    我发现“Find”方法不能直接与 BindingList 一起使用,但幸运的是有一个替代方法,使用 IEnumerable。在项目中实现 BindingList 后,我​​可以使用下面的代码过滤绑定的 datagridview:

        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】:

      我假设您在 TextChanged 事件中测试文本框是否为空。 当文本长度 = 0 时,可能没有调用您的方法。 我不记得确切原因,但我以前经历过这种情况。

      如果您使用的是自己编写的 BindingList,请提供代码。 RemoveFilter,将Filter设置为null或空字符串一直对我有用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-01
        • 2013-09-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多