通过文本框更改过滤datagridview

时间:2012-07-26 15:00:50

标签: c# winforms linq-to-sql filtering

在WinForms中通过绑定源控件使用Linq来实现sql,我无法解决这个问题:

private void textBox1_TextChanged(object sender, EventArgs e)
{
            productBindingSource.Filter = string.Format("ProductName LIKE '*{0}*'", textBox1.Text);
            MessageBox.Show("Changed");
}
        NorthwindDataContext dc;
        private void FrmFilter_Load(object sender, EventArgs e)
    {
        // create new data context
        dc = new NorthwindDataContext();

        // set the binding source data source to the full order table
        var qry = (from p in dc.Products select p).ToList();
        this.productBindingSource.DataSource = dc.GetTable<Product>();
    }

当我在文本框中键入一些字母时,datagridview中没有任何内容。 谢谢你的建议...

2 个答案:

答案 0 :(得分:3)

尝试将代码更改为:

NorthwindDataContext dc;

private void FrmFilter_Load(object sender, EventArgs e)
{
  dc = new NorthwindDataContext();
  this.productBindingSource.DataSource = dc.GetTable<Product>();
  productDataGridView.DataSource = productBindingSource;
}

private void textBox1_TextChanged(object sender, EventArgs e)
{
  this.productBindingSource.Filter = string.Format("ProductName LIKE '*{0}*'",
                                     textBox1.Text);
}

确保您的TextChanged事件已连线并且实际正在运行。此外,由于您未在发布的代码中的任何位置使用它,因此我将qry从示例中删除。


旧编辑:

您不必在网格上重置DataSource。

尝试将其更改为:

private void textBox1_TextChanged(object sender, EventArgs e) {
  if (textBox1.Text == string.Empty) {
    productBindingSource.RemoveFilter();
  } else {
    productBindingSource.Filter = string.Format("ProductName LIKE '*{0}*'", _
                                  textBox1.Text);
  }
}

我会避免担心此刻替换这些特殊字符。首先使过滤器工作。


这是一个工作示例,在表单上只有一个DataGridView和一个TextBox:

private DataTable dt = new DataTable("Test");
private BindingSource bs;

public Form1() {
  InitializeComponent();

  dt.Columns.Add("ProductName", typeof(string));

  DataRow dr1 = dt.NewRow();
  dr1["ProductName"] = "One A";
  dt.Rows.Add(dr1);

  DataRow dr2 = dt.NewRow();
  dr2["ProductName"] = "One B";
  dt.Rows.Add(dr2);

  DataRow dr3 = dt.NewRow();
  dr3["ProductName"] = "Two A";
  dt.Rows.Add(dr3);

  DataRow dr4 = dt.NewRow();
  dr4["ProductName"] = "Two B";
  dt.Rows.Add(dr4);

  bs = new BindingSource(dt, null);
  dataGridView1.DataSource = bs;
}

private void textBox1_TextChanged(object sender, EventArgs e) {
  if (textBox1.Text == string.Empty) {
    bs.RemoveFilter();
  } else {
    bs.Filter = string.Format("ProductName LIKE '*{0}*'", textBox1.Text);
  }
}

答案 1 :(得分:1)

这项工作对我来说很好!

this.productBindingSource.Filter = null;