C#使用Linq對DataGridView進行模糊查詢
阿新 • • 發佈:2019-01-06
針對DataGridView中已進行過資料繫結,即已向DataGridView中添加了一些資料,可以結合Linq查詢,並讓匹配查詢的行高亮顯示,如下圖:
具體實現如下:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Windows.Forms;
- namespace Maxes_PC_Client {
- public partial class frmWelcome : Form {
-
privateint beforeMatchedRowIndex = 0;
- public frmWelcome()
- {
- InitializeComponent();
- }
- privatevoid frmWelcome_Load(object sender, EventArgs e) {
- this.dataGridViewInit();
- }
- /// <summary>
- /// DataGridView新增資料、初始化
- /// </summary>
-
private
- 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;
- }
- privatevoid 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;
- }
- }
- }
- }