Reputation: 974
I am trying to stop the enter key on winforms dataGridView
of changing the row when DataGridViewTextBoxColumn
cell is in edit-mode
and enter is pressed. Otherwise the functionality should stay normal.
My preferred approach is to create CustomDataGridView
and override the necessary methods. My approach seem to end edit-mode
but without firing CellValidating
event.
Currently this event is used to validate the user input.
public class CustomDataGridView : DataGridView
{
protected override bool ProcessDialogKey(Keys keyData)
{
if (keyData == Keys.Enter)
{
if (MyProcessDialogKey(keyData)) return true;
}
return base.ProcessDialogKey(keyData);
}
protected bool MyProcessDialogKey(Keys keyData)
{
EndEdit();
return true;
}
}
How can I raise the CellValidating
event? Or should I consider different approach?
Upvotes: 1
Views: 260
Reputation: 4809
You just need to override the OnKeyDown event as such:
protected override void OnKeyDown(KeyEventArgs e)
{
if ((e.KeyData & Keys.KeyCode) == Keys.Enter)
return;
else
base.OnKeyDown(e);
}
Upvotes: 0
Reputation:
You can simply use the KeyDown Event on the DataGridView like following:
private void MyDGV_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if(e.KeyCode == Keys.Enter)
{
//First process your stuff
//To stop Keypress from doing anything more:
e.Handled = true;
}
}
More Infos: MSDN
Notice: there are many Events where you can end processing with e.Handled = true
Have a nice day
Upvotes: 1