C#使用Linq对DataGridView进行模糊查找
针对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
- {
- 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;
- }
- }
- }
- }
分类:
C#
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 2 本地部署DeepSeek模型构建本地知识库+联网搜索详细步骤