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

烂漫一生 提交于 2019-12-22 08:27:05

问题


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


回答1:


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?



来源:https://stackoverflow.com/questions/8538120/cell-in-editmode-doesnt-fire-onkeydown-event-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!