如何在数据网格视图中按回车键时执行一些编码?

Sag*_*ran 2 c# datagridview winforms

我在winform中使用datagridview.

如果我按下回车键,则选择将按行方式移动.但我想执行一些代码,我在下面写:

try
{
    int dispin = dataGridView1.CurrentCell.OwningColumn.DisplayIndex;
    if (dispin == 0)
    {
        string cellval = dataGridView1.CurrentCell.Value.ToString();
        returnParam = cellval;
        this.Close();
    }
    else
    {
        int rowIndex = dataGridView1.CurrentCell.RowIndex;
        int colIndex = dataGridView1.CurrentCell.ColumnIndex;
        colIndex = colIndex - 1;
        string cellval = dataGridView1[colIndex, rowIndex].Value.ToString();

        // MessageBox.Show(cellval1+cellval2+cellval3);
        returnParam = cellval;
        this.Close();
        //textBox1.Text = cellval;
    }
}
catch
{
    MessageBox.Show("Select a Record", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    //this.Close();
}
Run Code Online (Sandbox Code Playgroud)

这该怎么做?

我正在尝试按键事件,但它会影响所有键,请帮助我.

Jal*_*aid 5

使用datagridview.KeyPress喜欢:

//at form load:
dataGirdView1.KeyPress += OnDataGirdView1_KeyPress;

private void OnDataGirdView1_KeyPress(object sender, KeyPressEventArgs e)
{
     if (e.KeyChar == (char)Keys.Enter)
     { 
         RunMyCustomCode(); 
         //e.Handled = true; if you don't want the datagrid from hearing the enter pressed
     }
}
Run Code Online (Sandbox Code Playgroud)