c #datagridview交互式过滤

时间:2014-10-18 22:35:22

标签: c# winforms linq datagridview

我正在尝试为datagridview进行交互式过滤

我使用EF获取数据

           var query = from client in db.Clients
                        select new
                        {
                            client.Id,
                            client.Code,
                            client.Title
                        };

            clientsBs.DataSource = query.ToList();
            dataGridView1.DataSource = clientsBs;

在没有其他数据库查询的情况下过滤datagridview的最佳方法是什么? 我试过这种方式,但它没有给我任何结果/错误...

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        BindingSource bs = new BindingSource();
        bs.DataSource = dataGridView1.DataSource;
        bs.Filter = "Code like '%" + textBox1.Text + "%'";
        dataGridView1.DataSource = bs;
    }

任何想法?

1 个答案:

答案 0 :(得分:0)

请注明错误。我想在设置DataSource之前,您应该将其设置为null

dataGridView1.DataSource = null;

dataGridView1.DataSource = bs;

<强>更新

对于过滤DataGridView,您应该更改DataSource,然后再次绑定它:

var dataview = yourDataSet.Tables[tableIndex].DefaultView;
dataview.RowFilter = "Code like '%" + textBox1.Text + "%'";
var newDT = dataview.ToTable();
var newDS = new DataSet();    
newDS.Tables.Add(newDT);
dataGridView1.DataSource = null;
dataGridView1.DataSource = newDS;