Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cell in editmode doesn't fire OnKeyDown event in C#

I've made own datagridview control which ovveride OnKeyDown event:

public partial class PMGrid : DataGridView
{
    protected override void OnKeyDown(KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            e.SuppressKeyPress = true; //suppress ENTER
            //SendKeys.Send("{Tab}"); //Next column (or row)
            base.OnKeyDown(e);
        }
        else if (e.KeyCode == Keys.Tab)
        {
            base.OnKeyDown(e);
            this.BeginEdit(false);
        }
        else
        {
            base.OnKeyDown(e);
        }
    }
}

When I click on datagridview and press Enter it works perfect because row isn't changed and KeyUp event is fired. But when I press Tab, next cell is selected and it is changed to EditMode. And when I press Enter in this cell KeyUp event isn't fired and KeyPress too. I try to do that user can move from one cell to next cell and then user can write something in this cell and then when user press Enter this value is saved to the database. But when cell is in EditMode I cannot detect that user press Enter.

Thanks

like image 835
Robert Avatar asked Dec 16 '11 17:12

Robert


1 Answers

You should call the KeyPress or KeyUp event in the EditingControlShowing event of the datagridview. Something like this should work:

private void dtgrd1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    var txtEdit = (TextBox)e.Control;
    txtEdit.KeyPress += EditKeyPress; //where EditKeyPress is your keypress event
}


private void EditKeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
            {
                e.SuppressKeyPress = true; //suppress ENTER
                //SendKeys.Send("{Tab}"); //Next column (or row)
                base.OnKeyDown(e);
            }
            else if (e.KeyCode == Keys.Tab)
            {
                base.OnKeyDown(e);
                this.BeginEdit(false);
            }
            else
            {
                base.OnKeyDown(e);
            }

}

Let me know if you have any doubts while implementing this code.

EDIT

To avoid going to the next row on enter, please check this resolved question: How to prevent going to next row after editing a DataGridViewTextBoxColumn and pressing EnterKey?

like image 136
reggie Avatar answered Oct 20 '22 01:10

reggie