栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

WinForm 在DataGridView中查询

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

WinForm 在DataGridView中查询

向DataGridView中添加了一些数据,可以结合Linq查询,并让匹配查询的行高亮显示

  1. 建立如下界面
  2. 代码如下:
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;              
            }
        }
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/906097.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号