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


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

 

  

 

  具體實現如下:

 

[csharp] view plain copy

using System;

using System.Collections.Generic;

using System.Linq;

using System.Windows.Forms;

 

namespace Maxes_PC_Client {

public partial class frmWelcome : Form {

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;

}

}

}

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM