A cell in editmode does not fire an OnKeyDown event in C #

I created my own datagridview control that includes the 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 the datagridview and press Enter, it works fine because the row does not change and the KeyUp event is fired. But when I press Tab, the next cell is selected, and it changes to EditMode. And when I press Enter in this cell, the KeyUp event does not fire, nor does KeyPress either. I'm trying to make sure that the user can move from one cell to the next cell, and then the user can write something in this cell, and then when the user presses Enter, this value is stored in the database. But when the cell is in the EditMode, I cannot find that the user presses Enter.

thanks

+4
source share
1 answer

You must raise a KeyPress or KeyUp event in the EditingControlShowing datagridview event. Something like this should work:

 private void dtgrd1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) { var txtEdit = (TextBox)e.Control; txtEdit.KeyPress += EditKeyPress; //where EditKeyPress is your keypress event } private void EditKeyPress(object sender, KeyPressEventArgs 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); } } 

Let me know if you have any doubts about implementing this code.

EDIT

In order not to go to the next line as you type, check this resolved question: How to prevent the next line after editing the DataGridViewTextBoxColumn and pressing EnterKey?

+4
source

Source: https://habr.com/ru/post/1386746/


All Articles