1

C# form has a datagridview. I need to trap an event when CTRL+UP Arrow or CTRL+Down Arrow is pressed in a cell in edit mode.

Not sure which event to handle and how it should be handled.

Rob
  • 13
  • 2
  • 1
    use DataGridView KeyPress event. Get the edited cell from DataGridView.CurrentCell. – Graffito Jul 17 '15 at 20:29
  • To test the key up in KeyPress event : if (((Control.ModifierKeys & Keys.Control) == Keys.Control) && e.KeyChar == Keys.Up) ... – Graffito Jul 17 '15 at 20:35
  • You got it Graffito. Thanks. I'd give you a +1, but don't yet have enough reputation to give to do so.. – Rob Jul 20 '15 at 15:19

1 Answers1

0

Handle the KeyUp event for your DataGridView like this :

private void dataGridView1_KeyUp(object sender, KeyEventArgs e)
{
    if (e.Control && e.KeyCode == Keys.Up)
        MessageBox.Show(string.Format("Ctrl+{0}",e.KeyCode.ToString()));
    else if (e.Control && e.KeyCode == Keys.Down)
        MessageBox.Show(string.Format("Ctrl+{0}", e.KeyCode.ToString()));
}

Adding the print screen i get when i actually run the code:

enter image description here

From MSDN:

The conditional-AND operator (&&) performs a logical-AND of its bool operands, but only evaluates its second operand if necessary.

https://msdn.microsoft.com/en-us/library/2a723cdk%28v=vs.140%29.aspx

The & operator can function as either a unary or a binary operator.

https://msdn.microsoft.com/en-us/library/sbf85k1c%28v=vs.140%29.aspx

Because both operands are bool in my code, && is the preferred option, although i tested with & and it worked as well. Also && is more efficient because it tests the second operand only if necessary.

jsanalytics
  • 13,058
  • 4
  • 22
  • 43