简体   繁体   English

在datagridview中按Enter键时如何执行一些编码?

[英]How to Execute some coding when the enter key press in datagridview?

I am using datagridview in winform. 我在winform中使用datagridview。

If I press the enter key the selection is moved on row wise. 如果按回车键,则选择将逐行移动。 But I want to execute some code which i write below: 但是我想执行一些我在下面编写的代码:

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();
}

How to do this? 这个怎么做?

I am trying key down event, but it affect all key, please help me. 我正在尝试按键事件,但它会影响所有按键,请帮助我。

Use datagridview.KeyPress Like: 使用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
     }
}
void TextBox1_KeyDown(object sender, KeyEventArgs e) 
{ 
    if (e.KeyCode == Keys.Enter) 
    { 
        e.Handled = true; 
    } 
}

void TextBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) 
{ 
    if (e.KeyCode == Keys.Return)
    {
        /* Your code here! */ 
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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