0
votes

On Windows forms, I have a gridview with 3 columns and few buttons to handle data processing. The Grid is editable and I am using the below code to move focus to the next cell of the current row whenever a user presses the "Enter" key in editing mode.

private void dataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
    {
        if (e.ColumnIndex != dataGridView.Columns.Count - 1)
        {
            this.BeginInvoke(new MethodInvoker(() =>
            {
                dataGridView.CurrentCell = dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex + 1];
            }));
        }
    }

The code works fine and is moving the focus to next cell as required. However, the problem arises when I click any of the button while grid's cell is in focus. Since the focus is on a certain cell, clicking the button fires the CellEndEdit event before the Click event of the button and as a result of my code, the focus moves to next cell and the button click is not fired at all. I want to ensure that the code written to move to next cell in CellEndEdit function is not fired when i click a button.

  1. Edit a cell in GridView, press Enter, focus moves to next cell - Correct
  2. Edit a call in GridView, click on any button, focus moves to next cell, button click event not fired - Problem

I have searched a lot on SO and Internet regarding this issue but couldn't find a permanent solution. Any help will be greatly appreciated.

2
I'm not sure i quite understand you, but what about, in the CellBeginEdit, store the previous value of the cell, and if in CellEndEdit is the same, don't move to the next cell?Pikoh
The problem is not in moving to next cell, the problem is when I click any button on the form, the gridview fires CellEndEdit and the code moves to next cell. The button click is not fired at all. I have added more details to my question now.Nitesh

2 Answers

2
votes

You can use instead the KeyDown event.

It could be like this:

private void dataGridView_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyData == Keys.Enter)
    {
        // the rest of your code

        e.Handled = true;
    }
}
1
votes

Override ProcessCmdKey of the form, check if CurrentCell is in edit mode and Enter was clicked:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    if (keyData == Keys.Enter && this.dataGridView.IsCurrentCellInEditMode)
    {
        if (this.dataGridView.CurrentCell.ColumnIndex != this.dataGridView.Columns.Count - 1)
        {
            //this.BeginInvoke(new MethodInvoker(() =>
            //{
                this.dataGridView.CurrentCell = this.dataGridView.CurrentRow.Cells[this.dataGridView.CurrentCell.ColumnIndex + 1];
            //}));
        }
        return true;
    }
    else return base.ProcessCmdKey(ref msg, keyData);
}