C# 在datagridview C winfom中搜索

C# 在datagridview C winfom中搜索,c#,winforms,search,datagridview,C#,Winforms,Search,Datagridview,我想在DataGridView中设置一个搜索选项,即用户在文本框中键入字符串或int,DataGridView应该突出显示的类似记录。我尝试使用按键事件,但没有成功 if (Char.IsLetter(e.KeyChar)) { for (int i = 0; i < (dgemployee.Rows.Count); i++) { if (dgemployee.Rows[i].Cells["Employee"].Value.ToString()

我想在DataGridView中设置一个搜索选项,即用户在文本框中键入字符串或int,DataGridView应该突出显示的类似记录。我尝试使用按键事件,但没有成功

  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.DataSource成为DGV当前使用的数据表或数据视图。然后将DataGridView.DataSource设置为BindingSource。然后,可以使用BindingSource.Filter属性通过将BindingSource.Filter设置为查询字符串来查询数据源,该查询字符串将自动过滤DGV。您可以找到语法-它与基本SQL查询非常相似,只是您只能在字符串的开头和结尾使用通配符

        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中选择名称:名称是groupitems表和 Dv.Table=objdataset.Tables[0]:0是数据集中的第一个表
感谢您的评论,现在我可以有效地过滤我的dgview:干得好