如何在搜索文本框中输入字符时突出显示datagridview行

问题描述:

使用文本框搜索给定datagridview列中的值时,下面的代码将选定行放置在包含输入文本的列上。如何在搜索文本框中输入字符时突出显示datagridview行

private void textBox1_TextChanged(object sender, EventArgs e) 
    { 
     //if (Char.IsLetter(e.KeyChar)) 
     //{ 
      for (int i = 0; i < (productDataGridView.Rows.Count); i++) 
      { 

       if (productDataGridView.Rows[i].Cells[1].Value.ToString().StartsWith(textBox1.Text, true, CultureInfo.InvariantCulture)) 
       { 
        productDataGridView.FirstDisplayedCell = productDataGridView[1, i]; 
        productDataGridView.CurrentRow.DefaultCellStyle.BackColor = System.Drawing.Color.Red; 
        return; // stop looping 
       } 
      } 
    } 

的问题是,我不能突出或更改所需行的背景色,而在文本框中输入任何帮助吗?

+0

不要相信FirstDisplayedCell该行设置为当前。尝试设置productDataGridView [1,i] .DefaultCellStyle.BackColor ...比CurrentRow更好吗? – 2012-07-29 16:46:05

+0

这是真的FirstDisplayedCell不会将行设置为当前,有没有办法将其设置为当前? – 2012-07-29 17:32:10

+0

productDataGridView.CurrentRow = ... – 2012-07-29 19:29:01

尝试这样的解决方案,这个最终的作品就像一个魅力:

  try 
     { 
      productDataGridView.ClearSelection(); //or restore rows backcolor to default 
      for (int i = 0; i < (productDataGridView.Rows.Count); i++) 
      { 
       if (productDataGridView.Rows[i].Cells[1].Value.ToString().StartsWith(textBox1.Text, true, CultureInfo.InvariantCulture)) 
       { 
        productDataGridView.FirstDisplayedScrollingRowIndex = i; 
        productDataGridView.Rows[i].Selected = true; //It is also possible to color the row backgroud 
        return; 
       } 
      } 
     } 
     catch (Exception) 
     { 
     } 

试试这个

 //restore backcolor of rows to default e.g. loop through grid and set backcolor to white 
     foreach(DataGridViewRow row in productDataGridView.Rows) 
     { 
      if (row.Cells[1].Value.ToString().StartsWith(textBox1.Text, true,  CultureInfo.InvariantCulture)) 
      { 
       //productDataGridView.FirstDisplayedCell = productDataGridView[1, i]; 
       row.DefaultCellStyle.BackColor = System.Drawing.Color.Red; 
       return; // stop looping 
      } 
      else 
       //Set backcolor to default 
     } 

     //return; //move return here 
+0

试过这种方法,只有当文本框内容被发现只有一行不多。尽管有文本框内容,行仍然被着色的第二个问题已被更改。 – 2012-07-29 17:36:33

+0

第一个问题是因为你把'return'。第二个问题是在运行此代码之前,必须将背景颜色恢复为默认状态。检查更新的答案 – codingbiz 2012-07-29 17:49:08

+0

不可能删除退货,我收到异常。试过:productDataGridView.DefaultCellStyle.BackColor = System.Drawing.Color.White;不会将颜色恢复到默认状态。 – 2012-07-29 18:04:45