C# 在datagridview中搜索并过滤它
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18253624/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
searching in datagridview and filtering it
提问by user2650781
i have a question regarding with this code, i use a bindingsource to show the data and this code only select the row when im searching in datagridview. i want to know how can i filter the data im searching.
我对此代码有疑问,我使用 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);
}
}
采纳答案by Sriram Sakthivel
if you want to display only the filtered rows use BindingSource.Filter
property.
Here is a good sample in MSDN
如果您只想显示过滤的行,请使用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
}
To remove filter use the following
要删除过滤器,请使用以下命令
bindingSource.RemoveFilter();
or
或者
bindingSource.Filter = null;
回答by NicoRiff
Without changing that much your code, you could set the row.Visible
property to false
instead of just changing row.Selected
. Anyway, the answer above is more performant and clean, you should try that.
在不更改那么多代码的情况下,您可以将row.Visible
属性设置为,false
而不仅仅是更改row.Selected
. 无论如何,上面的答案更高效,更干净,您应该尝试一下。