编辑模式下的单元格不会触发 C# 中的 OnKeyDown 事件
我已经制作了自己的 datagridview 控件,它 ovveride OnKeyDown 事件:
public partial class PMGrid : DataGridView
{
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
e.SuppressKeyPress = true; //suppress ENTER
//SendKeys.Send("{Tab}"); //Next column (or row)
base.OnKeyDown(e);
}
else if (e.KeyCode == Keys.Tab)
{
base.OnKeyDown(e);
this.BeginEdit(false);
}
else
{
base.OnKeyDown(e);
}
}
}
当我单击 datagridview 并按 Enter 键时,它工作得很好,因为行没有更改并且 KeyUp 事件被触发。但是当我按 Tab 时,下一个单元格被选中,并且它更改为编辑模式。当我在此单元格中按 Enter 时,KeyUp 事件不会被触发,KeyPress 也不会被触发。 我尝试这样做,用户可以从一个单元格移动到下一个单元格,然后用户可以在该单元格中写入一些内容,然后当用户按 Enter 时,该值将保存到数据库中。但是当单元格处于编辑模式时,我无法检测到用户按 Enter。
谢谢
I've made own datagridview control which ovveride OnKeyDown event:
public partial class PMGrid : DataGridView
{
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
e.SuppressKeyPress = true; //suppress ENTER
//SendKeys.Send("{Tab}"); //Next column (or row)
base.OnKeyDown(e);
}
else if (e.KeyCode == Keys.Tab)
{
base.OnKeyDown(e);
this.BeginEdit(false);
}
else
{
base.OnKeyDown(e);
}
}
}
When I click on datagridview and press Enter it works perfect because row isn't changed and KeyUp event is fired. But when I press Tab, next cell is selected and it is changed to EditMode. And when I press Enter in this cell KeyUp event isn't fired and KeyPress too.
I try to do that user can move from one cell to next cell and then user can write something in this cell and then when user press Enter this value is saved to the database. But when cell is in EditMode I cannot detect that user press Enter.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该在 中调用 KeyPress 或 KeyUp 事件datagridview 的 EditingControlShowing 事件。像这样的事情应该有效:
如果您在实现此代码时有任何疑问,请告诉我。
编辑
为了避免在输入时转到下一行,请检查此已解决的问题:如何防止在编辑 DataGridViewTextBoxColumn 并按 Enter 键后转到下一行?
You should call the KeyPress or KeyUp event in the EditingControlShowing event of the datagridview. Something like this should work:
Let me know if you have any doubts while implementing this code.
EDIT
To avoid going to the next row on enter, please check this resolved question: How to prevent going to next row after editing a DataGridViewTextBoxColumn and pressing EnterKey?