Need help with DataGrid Navigation / Cancelling Keystroke in PreviewKeyDown Event

J

Joseph Geretz

I'm noticing that when my DataGrid has focus, it handles the Enter key by
advancing to the next row in the grid. This neutralizes Forms's current
defined AcceptButton.

My primary question: is there any quick way to configure the Grid not to
handle the Enter key? I do not see any property control which might
configure this behavior.

My secondary question: If there's no quick solution via Grid configuration,
then how do I get the following workaround to work? I've implemented the
PreviewKeyDown event to trap for the Enter key. This is working, but only
partially. Using this approach, the AcceptButton is triggered, however I
need to then suppress the Enter key so that the Grid doesn't handle it.
However, I don't see anything in the PreviewKeyDownEventArgs object to allow
me to cancel the keystroke.

private void gridResults_PreviewKeyDown(object sender,
PreviewKeyDownEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
this.AcceptButton.PerformClick();
}
}

Thanks for any help which you can provide.

- Joseph Geretz -
 
J

Joseph Geretz

OK, I was able to implement this successfully using the KeyDown event,
rather than the PreviewKeyDown event.

private void gridResults_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
this.AcceptButton.PerformClick();
e.Handled = true;
}
}

Kind of leaves me wondering though, what's the point in the PreviewKeyDown
event if you can't cancel the key? What would be a scenario where you'd need
to implement KeyDownPreview as opposed to KeyDown?

Thanks,

- Joe Geretz -
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top