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
You should call the KeyPress or KeyUp event in the EditingControlShowing event of the datagridview. 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 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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With