How to filter a datagridview by a textbox after lo

2019-08-04 14:01发布

I am at the VERY beggining with C#. I am creating a program for making offers for clients. I got first form with offer and a subform with an excel file loaded into datagridview. When I double click the row it is copied to the datagridview in the first row. It works fine. But I want to add a TextBox with the TextChanged event so when user puts some text there a datagridview (in second form, that one with excel data) should show only rows that contain this text. If it is not possible to search all calumns at once it's fine. But I cannot make it work. I found some sollution and i copied it but i doesn't work. So here's the code:

private void button1_Click(object sender, EventArgs e)
{
  try
  {
    System.Data.OleDb.OleDbConnection PolaczenieBazyDanych = new System.Data.OleDb.OleDbConnection("provider=Microsoft.ACE.OLEDB.12.0;Data Source='C:\\Users\\user\\Desktop\\My Dropbox\\Cenniki\\Cennik.xlsx';Extended Properties=Excel 8.0;");
    System.Data.DataSet DtSet = new System.Data.DataSet();
    System.Data.OleDb.OleDbDataAdapter Adapter = new System.Data.OleDb.OleDbDataAdapter("select * from [Tabelle1$]", PolaczenieBazyDanych);
    //Adapter.TableMappings.Add("Tabela", "TabelaTestowa");
    Adapter.Fill(DtSet);     
    dataGridView1.DataSource = DtSet.Tables[0];
    PolaczenieBazyDanych.Close();

  }
  catch (Exception ex)
  {
    MessageBox.Show(ex.ToString());
  }
}

private void textBox1_TextChanged(object sender, EventArgs e)
{
  DataView dv = ((DataTable)dataGridView1.DataSource).DefaultView;
  dv.RowFilter = "FromColumn like '%" + textBox1.Text + "%'";
  dataGridView1.DataSource = dv;


}

1条回答
手持菜刀,她持情操
2楼-- · 2019-08-04 14:30

This did work:

  BindingSource bs = new BindingSource();
  bs.DataSource = dataGridView1.DataSource;
  bs.Filter = sColumnaDoPrzeszukania + " like '%" + textBox1.Text + "%'";
  dataGridView1.DataSource = bs;
查看更多
登录 后发表回答