在datagridview中搜索并过滤它

我有一个关于这个代码的问题,我使用bindingsource来显示数据,这个代码只在我在datagridview中搜索时选择行。 我想知道如何过滤搜索数据。

private void button1_Click(object sender, EventArgs e) { string searchValue = textBox1.Text; dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; try { foreach (DataGridViewRow row in dataGridView1.Rows) { if (row.Cells[2].Value.ToString().Equals(searchValue)) { row.Selected = true; break; } } } catch (Exception exc) { MessageBox.Show(exc.Message); } } 

如果要仅显示已过滤的行,请使用BindingSource.Filter属性。 这是MSDN中的一个很好的示例

 bindingSource.Filter = "columnname = 'value'"; private void button1_Click(object sender, EventArgs e) { string searchValue = textBox1.Text; dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; bindingSource.Filter = string.Format("{0} = '{1}'","YourColumnName", searchValue ); //here you can do selection if you need } 

要删除filter,请使用以下内容

 bindingSource.RemoveFilter(); 

要么

 bindingSource.Filter = null; 

在不改变代码的情况下,可以将row.Visible属性设置为false而不是仅仅更改row.Selected 。 无论如何,上面的答案是更高效和干净,你应该尝试。