break

DataGridView Enter Key

I have a dataGridView with two columns and multiple rows.

The task: When I pressed the enter key, in any of my dataGridViewCell I want to handle the fact that the user pressed the enter key. I will also get the value they typed.

In order to do this I was trying to simulate an event that Processes the ENTER key. I read about a DataGridView.ProcessEnterKey Method but this didn’t work quite well for me, considering I need to know the index of the current column of my dataGridViewCell.

So how can you simulate this?. First of all the first event that is going to be called is CellEnter. This is the code I have when the user enters the cell

private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
// store the index of the column
columnIndex = e.ColumnIndex;
dataGridView1.BeginEdit(false);
}

Then the next event that is going to be called is EditingControlShowing. This occurs when a control for editing a cell is showing. This is the code I have for this event:

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
DataGridViewTextBoxEditingControl dText = (DataGridViewTextBoxEditingControl)e.Control;
dText.KeyUp -= new KeyEventHandler(dText_KeyUp);
dText.KeyUp += new KeyEventHandler(dText_KeyUp);
}

I create a DataGridViewTextBoxEditingControl (according to MSDN: “represents a text box control that can be hosted in a DataGridViewTextBoxCell” ) of the current cell, and remove and add to that control a KeyUp event, which is the next event that gets called.

The KeyUp event according to MSDN: “occurs when a key is released while the control has focus.”. The code for the KeyUp events looks like this:

void dText_KeyUp(object sender, KeyEventArgs e)
{
int rowIndex = ((System.Windows.Forms.DataGridViewTextBoxEditingControl)(sender)).
EditingControlRowIndex;
if (e.KeyCode == Keys.Enter)
{
object valueEntered = dataGridView1[columnIndex, rowIndex - 1].EditedFormattedValue;
MessageBox.Show("The Enter Key was detected. The value entered was: " + valueEntered.ToString());
}
}

At this point you can do something with the fact that the user pressed enter. I am displaying a Message Box with the value entered by the user.

If you know of another way, or a better way to do this , I’ll be very interested to know. At least this is the only way I found to solve this problem.

Here’s a copy of my files.

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.

CAPTCHA Image
Reload Image