向DataGridView中添加了一些数据,可以结合Linq查询,并让匹配查询的行高亮显示
- 建立如下界面
- 代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WareHouse_WinForm
{
public partial class DataGridView_Query : Form
{
public DataGridView_Query()
{
InitializeComponent();
}
///
/// DataGridView添加数据、初始化
///
private void dataGridViewInit()
{
Dictionary map = new Dictionary();
map.Add("藏书室女尸之谜", " Body in the Library");
map.Add("寓所谜案", "Murder at the Vicarage");
map.Add("命案目睹记", "4:50 from Paddington");
map.Add("谋杀启事", "A Murder Is Announced");
map.Add("沉睡谋杀案", "Sleeping Murder");
map.Add("魔手", "Moving Finger");
map.Add("煦阳岭的疑云", "By The Pricking of My Thumbs");
map.Add("斯塔福特疑案", "The Sittaford Mystery");
map.Add("零时", "Towards Zero");
map.Add("复仇女神", "Nemesis");
map.Add("伯特伦旅馆之谜", "At Bertram's Hotel");
map.Add("奉命谋杀", "Ordeal By Innocence");
// 在这里必须创建一个BindIngSource对象,用该对象接收Dictionary泛型集合的对象
BindingSource bindingSource = new BindingSource();
// 将泛型集合对象的值赋给BindingSourc对象的数据源
bindingSource.DataSource = map;
this.dataGridView.DataSource = bindingSource;
}
private void button1_Click(object sender, EventArgs e)
{
if (this.KeyWord.Text.Equals(""))
{
return;
}
// Linq模糊查询
IEnumerable enumerableList = this.dataGridView.Rows.Cast();
List list = (from item in enumerableList
where item.Cells[0].Value.ToString().IndexOf(this.KeyWord.Text) >= 0
select item).ToList();
if (list.Count > 0)
{
// 查找匹配行高亮显示
int matchedRowIndex = list[0].Index;
this.dataGridView.Rows[matchedRowIndex].DefaultCellStyle.BackColor = System.Drawing.Color.Plum;
}
}
}
}



