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

3 篇文章 0 订阅

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

  

  具体实现如下:

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

http://blog.csdn.net/xht555/article/details/38685845
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值