在datagridview中搜索C#winfom

我想在DataGridView一个搜索选项,即User在TextBox键入字符串或int,类似的记录应该突出显示DataGridView 。 我尝试使用KeyPress事件,但没有工作。

  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 ,而不仅仅是一列和一行。 那么最好的解决方案呢

如果DataGridView绑定到DataTable或DataView,则可以执行以下操作:

创建一个BindingSource并使BindingSource.DataSource成为您的DGV当前使用的Datatable或DataView。 然后将DataGridView.DataSource设置为BindingSource。 然后,您可以使用BindingSource.Filter属性通过将BindingSource.Filter设置为您的查询字符串来查询数据源,该查询字符串将自动过滤DGV。 您可以在此处找到语法 – 它与基本SQL查询非常相似,除了您只能在字符串的开头和结尾使用通配符。

使用DataView.RowFilter属性。

另请参阅DataTable.DefaultView

看一下这篇文章,我写了一些时间回过头来实时过滤数据。

  private void txtsearchgroup_KeyUp(object sender, KeyEventArgs e) { SqlConnection objconnection = new SqlConnection(servername and ...); DataView Dv = new DataView(); objcommand = new SqlCommand("select name from groupitems", objconnection); objdataadapter = new SqlDataAdapter(); objdataadapter.SelectCommand = new SqlCommand(); objdataadapter.SelectCommand = objcommand; objdataset = new DataSet(); objconnection.Open(); objdataadapter.Fill(objdataset); Dv.Table = objdataset.Tables[0]; Dv.RowFilter = " name LIKE '%" + txtsearchgroup.Text + "%'"; dataGridView1.DataSource = Dv; objconnection.Close(); } 
  • txtsearchgroup:datagridview1和中搜索词的文本框名称
  • txtsearchgroup_KeyUp:datagridview1和中的搜索和过滤词的keyup事件
  • 从groupitems中选择名称:name是groupitems表的字段和
  • Dv.Table = objdataset.Tables [0]:零(0)是数据集中的第一个表