Reputation: 5623
I have a DataGridView
in C# and need to disable the arrow keys (so they cannot navigate the list via keys). I have tried this:
void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyData & Keys.KeyCode)
{
case Keys.Up:
case Keys.Right:
case Keys.Down:
case Keys.Left:
e.Handled = true;
e.SuppressKeyPress = true;
break;
}
}
But it did not disable the arrow keys. Any thoughts?
I tried this handler, but got a compile error:
this.dataGridView1.KeyDown += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_KeyDown);
Error 1 No overload for 'dataGridView1_KeyDown' matches delegate 'System.Windows.Forms.DataGridViewCellEventHandler' Form1.Designer.cs 78 43 FaxMonitorCSharp
Upvotes: 0
Views: 2983
Reputation: 81
Binding the KeyDown event works great so long as the current cell isn't in EditMode, but if it is you'll need to get a bit more creative. I created an inherited DataGridView class, overrode ProcessCmdKey as follows.
class NewDataGridView : System.Windows.Forms.DataGridView
{
protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, System.Windows.Forms.Keys keyData)
{
(FindForm() as Form1).DataGridViewKeyDown((DataGridView)this, keyData);
//return base.ProcessCmdKey(ref msg, keyData);
return true;
}
}
This absorbs all keypresses for the datagridview and redirects them to a method that lives in the container form.
Upvotes: 2