1. 程式人生 > >C#使用Linq對DataGridView進行模糊查詢

C#使用Linq對DataGridView進行模糊查詢

  針對DataGridView中已進行過資料繫結,即已向DataGridView中添加了一些資料,可以結合Linq查詢,並讓匹配查詢的行高亮顯示,如下圖:

  

  具體實現如下:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Windows.Forms;  
  5. namespace Maxes_PC_Client {  
  6.     public partial class frmWelcome : Form {  
  7.         privateint beforeMatchedRowIndex = 0;  
  8.         public frmWelcome()  
  9.         {  
  10.             InitializeComponent();  
  11.         }  
  12.         privatevoid frmWelcome_Load(object sender, EventArgs e) {  
  13.             this.dataGridViewInit();  
  14.         }  
  15.         /// <summary>
  16.         /// DataGridView新增資料、初始化
  17.         /// </summary>
  18.         private
    void dataGridViewInit() {  
  19.             Dictionary<String, String> map = new Dictionary<String, String>();  
  20.             map.Add("Lily""22");  
  21.             map.Add("Andy""25");  
  22.             map.Add("Peter""24");  
  23.             // 在這裡必須建立一個BindIngSource物件,用該物件接收Dictionary<T, K>泛型集合的物件
  24.             BindingSource bindingSource = new BindingSource();  
  25.             // 將泛型集合物件的值賦給BindingSourc物件的資料來源
  26.             bindingSource.DataSource = map;  
  27.             this.dataGridView.DataSource = bindingSource;  
  28.         }  
  29.         privatevoid SearchButton_Click(object sender, EventArgs e) {  
  30.             if (this.KeyWord.Text.Equals("")) {  
  31.                 return;  
  32.             }  
  33.             // Linq模糊查詢
  34.             IEnumerable<DataGridViewRow> enumerableList = this.dataGridView.Rows.Cast<DataGridViewRow>();  
  35.             List<DataGridViewRow> list = (from item in enumerableList  
  36.                                           where item.Cells[0].Value.ToString().IndexOf(this.KeyWord.Text) >= 0  
  37.                                           select item).ToList();  
  38.             // 恢復之前行的背景顏色為預設的白色背景
  39.             this.dataGridView.Rows[beforeMatchedRowIndex].DefaultCellStyle.BackColor = System.Drawing.Color.White;  
  40.             if (list.Count > 0) {  
  41.                 // 查詢匹配行高亮顯示
  42.                 int matchedRowIndex = list[0].Index;  
  43.                 this.dataGridView.Rows[matchedRowIndex].DefaultCellStyle.BackColor = System.Drawing.Color.Yellow;  
  44.                 this.beforeMatchedRowIndex = matchedRowIndex;  
  45.             }  
  46.         }  
  47.     }  
  48. }  
http://blog.csdn.net/xht555/article/details/38685845