The DataGrid on a WinForm doesn't raise the standard keystroke events under all conditions.
If you need to handle key press events, you have to override the ProcessCmdKey method in your DataGrid
sub-class ... see this article for more information:
http://www.codeproject.com/cs/database/DatabaseAcessWithAdoNet1.asp#Keystrokes
Here's an excerpt from the article, along with the code:
9. How to trap keystrokes (Up, Down, Esc, NumLock...) in the DataGrid
Like many users, I
also looked for a method to catch the keystrokes in a DataGrid, and encountered
it first in MSDN Library. So I decided to include it in the code so that
users can make use of it. For most purposes, the standard KeyUp, KeyDown, and
KeyPress events can capture and handle keystrokes. However, not all controls
raise the standard KeyUp, KeyDown events for all keystrokes under all
conditions. The DataGrid control is one of them.
If no data was assigned
to the grid, the arrow keys (LEFT, RIGHT, UP, and DOWN) raise only the KeyUp
event. If the DataGrid displays data, none of the standard keyboard events are
raised for the navigation keys. The DataGrid is the control for which this
feature is most frequently requested. You also can intercept key combinations,
including CTRL and ALT. This technique does not capture the Print Screen key. In
order to trap keystrokes in a Windows Forms control, you can override the
ProcessCmdKey method ....
// Put this code in your Grid sub-class:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
const int WM_KEYDOWN = 0x100;
const int WM_SYSKEYDOWN = 0x104;
if ((msg.Msg == WM_KEYDOWN) || (msg.Msg == WM_SYSKEYDOWN))
{
switch(keyData)
{
case Keys.Enter:
MessageBox.Show("Enter");
break;
case Keys.Down:
MessageBox.Show("Down");
break;
case Keys.Up:
MessageBox.Show("Up");
break;
case Keys.NumLock:
MessageBox.Show("NumLock");
break;
case Keys.Escape:
MessageBox.Show("Escape");
break;
}
}
return base.ProcessCmdKey(ref msg,keyData);
}
from a solution provided by Bonnie Berent in Message #1055291
|