在datagridview中搜索C#winfom [英] search in datagridview C# winfom
问题描述
我想在 DataGridView
中添加一个搜索选项,即用户键入 TextBox
中的字符串或int,类似的记录应该突出显示 DataGridView
。我尝试使用 KeyPress
事件,但没有工作。
I want to put a search option in DataGridView
, i.e., User types the string or int in TextBox
and similar records the DataGridView
should be highlighted. I tried it using KeyPress
event but didn't work.
if (Char.IsLetter(e.KeyChar))
{
for (int i = 0; i < (dgemployee.Rows.Count); i++)
{
if (dgemployee.Rows[i].Cells["Employee"].Value.ToString().
StartsWith(e.KeyChar.ToString(), true,
CultureInfo.InvariantCulture))
{
dgemployee.Rows[i].Cells[0].Selected = true;
return;
}
}
实际上,我需要搜索整个 DataGridView
,不仅一列和一行。那么任何最好的解决方案?
Actually, I need to search the whole DataGridView
, not only one column and row. So any best solution?
推荐答案
如果您的DataGridView绑定到DataTable或DataView,您可以这样做:
If your DataGridView is bound to a DataTable or a DataView, you can do this:
创建 BindingSource 并使您的DGV当前正在使用的Datatable或DataView的 BindingSource.DataSource
。然后将您的 DataGridView.DataSource
设置到BindingSource。然后您可以使用 BindingSource.Filter
属性来查询您的数据源,方法是将 BindingSource.Filter
设置为查询字符串将自动过滤DGV。您可以在这里找到语法非常类似于基本SQL查询,除了您只能在字符串的开头和结尾使用通配符。
Create a BindingSource and make BindingSource.DataSource
the Datatable or DataView that your DGV is currently using. Then set your DataGridView.DataSource
to the BindingSource. Then you can use the BindingSource.Filter
property to query your datasource by setting the BindingSource.Filter
to your query string which will automatically filter the DGV. You can find the syntax here - it is very similar to basic SQL queries, except you can only use wild cards on the beginning and end of the string.
这篇关于在datagridview中搜索C#winfom的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!