C#使用Linq对DataGridView进行模糊查找

 针对DataGridView中已进行过数据绑定,即已向DataGridView中添加了一些数据,可以结合Linq查询,并让匹配查询的行高亮显示,如下图:

  

  具体实现如下:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Windows.Forms;  
  5.   
  6. namespace Maxes_PC_Client 
  7. {  
  8.     public partial class frmWelcome : Form 
  9.    {  
  10.         private int beforeMatchedRowIndex = 0;  
  11.   
  12.         public frmWelcome()  
  13.         {  
  14.             InitializeComponent();  
  15.         }  
  16.   
  17.         private void frmWelcome_Load(object sender, EventArgs e)
  18.        {  
  19.             this.dataGridViewInit();  
  20.         }  
  21.   
  22.         /// <summary>  
  23.         /// DataGridView添加数据、初始化  
  24.         /// </summary>  
  25.         private void dataGridViewInit()
  26.        {  
  27.             Dictionary<String, String> map = new Dictionary<String, String>();  
  28.             map.Add("Lily", "22");  
  29.             map.Add("Andy", "25");  
  30.             map.Add("Peter", "24");  
  31.   
  32.             // 在这里必须创建一个BindIngSource对象,用该对象接收Dictionary<T, K>泛型集合的对象  
  33.             BindingSource bindingSource = new BindingSource();  
  34.             // 将泛型集合对象的值赋给BindingSourc对象的数据源  
  35.             bindingSource.DataSource = map;  
  36.   
  37.             this.dataGridView.DataSource = bindingSource;  
  38.         }  
  39.   
  40.         private void SearchButton_Click(object sender, EventArgs e) 
  41.         {  
  42.             if (this.KeyWord.Text.Equals("")) 
  43.            {  
  44.                 return;  
  45.             }  
  46.   
  47.             // Linq模糊查询  
  48.             IEnumerable<DataGridViewRow> enumerableList = this.dataGridView.Rows.Cast<DataGridViewRow>();  
  49.             List<DataGridViewRow> list = (from item in enumerableList  
  50.                                           where item.Cells[0].Value.ToString().IndexOf(this.KeyWord.Text) >= 0  
  51.                                           select item).ToList();  
  52.   
  53.             // 恢复之前行的背景颜色为默认的白色背景  
  54.             this.dataGridView.Rows[beforeMatchedRowIndex].DefaultCellStyle.BackColor = System.Drawing.Color.White;  
  55.   
  56.             if (list.Count > 0)
  57.            {  
  58.                 // 查找匹配行高亮显示  
  59.                 int matchedRowIndex = list[0].Index;  
  60.                 this.dataGridView.Rows[matchedRowIndex].DefaultCellStyle.BackColor = System.Drawing.Color.Yellow;  
  61.                 this.beforeMatchedRowIndex = matchedRowIndex;  
  62.             }  
  63.         }  
  64.     }  
  65. }  
原文地址:https://www.cnblogs.com/lgx5/p/7544681.html