Skip to main content
 首页 » 编程设计

c#之通过文本框更改过滤数据 GridView

2024年02月20日10mate10pro

在 WinForms 中通过绑定(bind)源控件使用 Linq to 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 中没有任何反应。 感谢您的建议...

请您参考如下方法:

尝试将您的代码更改为如下所示:

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,因为您没有在发布的代码中的任何地方使用它。


较早的编辑:

您不必在网格上重置数据源。

尝试将其更改为:

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