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

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

 

  

 

  具体实现以下: spa

 

[csharp] view plain copy orm

using System; 对象

using System.Collections.Generic; blog

using System.Linq; it

using System.Windows.Forms; io

 

namespace Maxes_PC_Client { ast

public partial class frmWelcome : Form { class

private int beforeMatchedRowIndex = 0; 泛型

 

public frmWelcome()

{

InitializeComponent();

}

 

private void frmWelcome_Load(object sender, EventArgs e) {

this.dataGridViewInit();

}

 

/// <summary>

/// DataGridView添加数据、初始化

/// </summary>

private void dataGridViewInit() {

Dictionary<String, String> map = new Dictionary<String, String>();

map.Add("Lily", "22");

map.Add("Andy", "25");

map.Add("Peter", "24");

 

// 在这里必须建立一个BindIngSource对象,用该对象接收Dictionary<T, K>泛型集合的对象

BindingSource bindingSource = new BindingSource();

// 将泛型集合对象的值赋给BindingSourc对象的数据源

bindingSource.DataSource = map;

 

this.dataGridView.DataSource = bindingSource;

}

 

private void SearchButton_Click(object sender, EventArgs e) {

if (this.KeyWord.Text.Equals("")) {

return;

}

 

// Linq模糊查询

IEnumerable<DataGridViewRow> enumerableList = this.dataGridView.Rows.Cast<DataGridViewRow>();

List<DataGridViewRow> list = (from item in enumerableList

where item.Cells[0].Value.ToString().IndexOf(this.KeyWord.Text) >= 0

select item).ToList();

 

// 恢复以前行的背景颜色为默认的白色背景

this.dataGridView.Rows[beforeMatchedRowIndex].DefaultCellStyle.BackColor = System.Drawing.Color.White;

 

if (list.Count > 0) {

// 查找匹配行高亮显示

int matchedRowIndex = list[0].Index;

this.dataGridView.Rows[matchedRowIndex].DefaultCellStyle.BackColor = System.Drawing.Color.Yellow;

this.beforeMatchedRowIndex = matchedRowIndex;

}

}

}

}

相关文章
相关标签/搜索