要使按下Enter键达到与按下Tab键一样的效果,我们需要从DataGridView中派生出一个类,写一个自定义的DataGridView控件。这里有两个方面需要考虑。一方面,当DataGridView不处于编辑状态:在这种情况下,我们需要重写OnKeyDown事件来实现我们所需要的定位逻辑。另一方面,当DataGridView处于编辑的状态下:在这种情况下,Enter键是在ProcessDialogKey事件中被处理,因此我们需要重写该事件。详见以下示例:

class myDataGridView : DataGridView
{
protected override bool ProcessDialogKey(Keys keyData)
{
if (keyData == Keys.Enter)
{
int col = this.CurrentCell.ColumnIndex;
int row = this.CurrentCell.RowIndex;
if (row != this.NewRowIndex)
{
if (col == (this.Columns.Count - 1))
{
col = -1;
row++;
}
this.CurrentCell = this[col + 1, row];
}
return true;
}
return base.ProcessDialogKey(keyData);
}
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.KeyData == Keys.Enter)
{
int col = this.CurrentCell.ColumnIndex;
int row = this.CurrentCell.RowIndex;
if (row != this.NewRowIndex)
{
if (col == (this.Columns.Count - 1))
{
col = -1;
row++;
}
this.CurrentCell = this[col + 1, row];
}
e.Handled = true;
}
base.OnKeyDown(e);
}
}
{
protected override bool ProcessDialogKey(Keys keyData)
{
if (keyData == Keys.Enter)
{
int col = this.CurrentCell.ColumnIndex;
int row = this.CurrentCell.RowIndex;
if (row != this.NewRowIndex)
{
if (col == (this.Columns.Count - 1))
{
col = -1;
row++;
}
this.CurrentCell = this[col + 1, row];
}
return true;
}
return base.ProcessDialogKey(keyData);
}
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.KeyData == Keys.Enter)
{
int col = this.CurrentCell.ColumnIndex;
int row = this.CurrentCell.RowIndex;
if (row != this.NewRowIndex)
{
if (col == (this.Columns.Count - 1))
{
col = -1;
row++;
}
this.CurrentCell = this[col + 1, row];
}
e.Handled = true;
}
base.OnKeyDown(e);
}
}
运用:
this.dataGridView1 = new myDataGridView();
分类:
C#
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
2008-12-11 C# 2.0 :仿MSN提示框or仿迅雷提示框(.Net2.0).rar
2007-12-11 ASP.NET(C#)实现一次性上传多张图片(多个文件)