简体   繁体   中英

execute block of code on enter key press in datagridviewcell

我们正在尝试在datagridviewcell editing modeenter key press执行代码块。但是在editing mode我们无法在datagridviewcell上找到Enter键。

KeyDown will not work for a cell in editing mode, subclass DataGridView and override ProcessDialogKey like this.

protected override bool ProcessDialogKey(Keys keyData)
{
    if (keyData == Keys.Enter)
    {
        // Your code here
        return true;
    }
    return base.ProcessDialogKey(keyData);
}

You will have to use dataGridView1_KeyDown event as follows:

private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {                
                e.SuppressKeyPress=true;
                //block of code
            }
         }

Do following if you want to check which cell is being clicked. This is in VB.net. Extended what Gary has already suggested you.

Public Class Custom_DataGridView Inherits System.Windows.Forms.DataGridView

Public Event DataGridView_CustomEnterKeyPressed(ByVal keyData As Keys, ByVal CurrentCell As DataGridViewCell)

Protected Overrides Function ProcessDialogKey(ByVal keyData As Keys) As Boolean If keyData = Keys.Enter Then RaiseEvent DataGridView_CustomEnterKeyPressed(keyData, CType(Me, DataGridView).CurrentCell) 'Return true 'Open this if you don't want to move to next cell, if you open this the cursor will not move to next cell in the column. End If Return MyBase.ProcessDialogKey(keyData) End Function

End Class

Use this Custom_DataGridView instead of out of the box DataGridView Control and then you have to handle the DataGridView_CustomEnterKeyPressed event as shown below in your form in which you have added this custom control.

Private Sub DataGridNameYouHaveUsed_DataGridView_CustomEnterKeyPressed(ByVal keyData As System.Windows.Forms.Keys, ByVal CurrentCell As DataGridViewCell) Handles DataGridNameYouHaveUsed.DataGridView_CustomEnterKeyPressed MsgBox("In DataGridView_CustomEnterKeyPressed Event Handler for cell( : " + CurrentCell.ColumnIndex.ToString + "," + CurrentCell.RowIndex.ToString + ")") End Sub

You might have already solved your problem, just posting so that if somebody else (like me) is searching for a solution this might be useful to them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM