欺骗 DataGridView






4.57/5 (13投票s)
DataGridView 修改,允许用户通过按下 Enter 键水平移动单元格。
引言
直接从数据源显示可读格式的数据是使用网格视图的诸多好处之一。 其快速实现和易于连接到数据源的特性使其成为初学者程序员的理想解决方案。 但当我尝试将其用于数据输入时,我对 DataGridView
的蜜月期结束了。
由于其外观和感觉非常适合数据输入,我尝试使用单元格来输入每个数据项。 那么,什么事件、何时以及哪个事件被触发? 所有这些问题让我感到困惑。 经过一段时间的摸索,我终于掌握了它,但其中一件我无法回避的事情是它的垂直焦点移动行为。
当用户在单元格中输入数据并按下“Enter”键时,焦点会移到同一列的下一个单元格,垂直方向上。 在我的情况下,在大多数情况下,我希望逐行输入数据,一次一个单元格。 因此,在寻找解决方案的动力下,我编写了一个非常小的代码来实现此任务。
使用代码
我尝试了大多数可能性来处理当前单元格的关键和焦点事件,以执行此任务,但最终却浪费了我的时间并让我感到沮丧。 最后,我决定重写处理 DataGridView
键的函数。 为了让我能够重写这些方法并随时使用此组件,我使用代码扩展了正常的 DataGridView
,以创建自定义控件。
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
namespace ZeeUIUtility
{
//the class defination that inherits from DataGridView
public class DataGridViewEx : DataGridView
{}
网格视图的另一个特点是,焦点会随着导航键(左、右、上、下)移动。 我所做的是重写此行为,使其在我想要的时候认为用户按下了导航键,这就是此解决方案的基础。 如代码所示,重写 "ProcessDialogKey
",每当用户按下 Enter 键时,调用将焦点移动到下一个单元格的方法。
protected override bool ProcessDialogKey(Keys keyData)
{
//if the key pressed is "return" then tell
//the datagridview to move to the next cell
if (keyData == Keys.Enter)
{
MoveToNextCell();
return true;
}
else
return base.ProcessDialogKey(keyData);
}
移动到下一个单元格的代码如下所示
public void MoveToNextCell()
{
int CurrentColumn, CurrentRow;
//get the current indicies of the cell
CurrentColumn = this.CurrentCell.ColumnIndex;
CurrentRow = this.CurrentCell.RowIndex;
//if cell is at the end move it to the first cell of the next row
//other with move it to the next cell
if (CurrentColumn == this.Columns.Count - 1 &&
CurrentRow != this.Rows.Count - 1)
{
base.ProcessDataGridViewKey(new KeyEventArgs(Keys.Home));
base.ProcessDataGridViewKey(new KeyEventArgs(Keys.Down));
}
else
base.ProcessDataGridViewKey(new KeyEventArgs(Keys.Right));
移动到下一个单元格意味着按下“右”键,所以这段代码就是让 DataGridView
认为用户按下了“右”键。 此外,我添加了代码,以便当用户到达网格的末尾时,焦点会移到下一行的第一个单元格,通过“Home”键和“Down”键模拟,因为如果你想移动到下一行中的单元格,你基本上就是这样做的。
实现
要使用此控件,只需从本文中下载程序集并引用它即可。 你会在工具箱中找到该控件。 由于此控件的其余属性与 DataGridView
相同,因此使用起来会更容易。