捕获键盘事件控制DataGridView选中行改变

认知尚浅,如有错误,愿闻其详!

概述

  工作中需求上有这样一个功能,就是在文本框上输入内容,然后根据内容去查询相关的数据,然后用户键盘选择、Enter选中或者是鼠标双击选中。简单效果如下:


捕获键盘事件控制DataGridView选中行改变_第1张图片
键盘DataGridView选中.gif

  功能看着很简单,不过在实现过程中存在了一些问题。说一下踩坑记录!

DataGridView选中行改变的坑

   在如图中,添加的DataGridView是无法获取到键盘按键的按下,无法实现按键控制选中行的选中光标上下移动。尽管将DataGridView设为焦点控件,也不行。而且在后来,通过捕获键盘来直接改变选中行来实现功能,也遇到了问题,网上方法选中行dataGridView1.Rows[index].Selected = true;也无法实现。

问题剖析

  我个人感觉应该是被某些控件或者窗体不捕获了,以至于DataGridView无法实现享用功能。

解决方法

  思路:我们利用重写ProcessCmdKey(ref Message msg, Keys keyData)捕获键盘重写键盘事件方法,然后判断按键,进行处理响应的功能。
代码如下:

  protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            
            if (keyData == Keys.Up)//上键
            {
                int index = dataGridView1.CurrentCell.RowIndex;

                if (index > 0)
                {
                    dataGridView1.CurrentCell = dataGridView1.Rows[index--].Cells[0];
                    dataGridView1.Rows[index].Cells[0].Selected = true;
                }
                return true;
            }
            if (keyData == Keys.Down)//下键
            {
                int index = dataGridView1.CurrentCell.RowIndex;
                if (index < dataGridView1.RowCount -1)
                {
                    dataGridView1.CurrentCell = dataGridView1.Rows[index++].Cells[0];
                    dataGridView1.Rows[index].Cells[0].Selected = true;
                }
                return true;
            }
            if (keyData == Keys.Enter)//Enter键
            {
                DataGridView1_CellDoubleClick(null , null);
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

首先,我们的DataGridView需要先设置MultiSelect = false 和 SelectionMode = FullRowSelect,我再判断按下键是键盘上或下键,获取当前选中行的行号:int index = dataGridView1.CurrentCell.RowIndex;,然后进行当前选中行是否超出数据边界,否则开始选中index --index ++行的第一个CelldataGridView1.CurrentCell = dataGridView1.Rows[index++].Cells[0];,再将当前行状态设置为选中,dataGridView1.Rows[index].Cells[0].Selected = true;,坑就在这,网上教程都是说dataGridView1.Rows[index].Selected = true;这样可以实现,但是最后index始终没改变,原因就在于下一行始终没有被选中,导致index始终不变。最后,要指定到某个单元格dataGridView1.Rows[index].Cells[0].Selected = true;才实现了相应功能。

你可能感兴趣的:(捕获键盘事件控制DataGridView选中行改变)