簡體   English   中英

在datagridview中按Enter鍵時如何執行一些編碼?

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

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

這個怎么做?

我正在嘗試按鍵事件,但它會影響所有按鍵,請幫助我。

使用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