2011-07-28 58 views
2

我在winform中使用datagridview。如何在enter鍵在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(); 
} 

如何做到這一點?

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

回答

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 
    } 
} 
+0

IT工作,但是......它選擇下一個記錄。 cursser的bzs移動到下一個記錄。那麼只有這個代碼被執行。如何解決此問題, – Sagotharan

+0

嘗試在'RunMyCustomCode()'之後或之前添加'e.Handled = true;' –

+0

謝謝。輸入關閉時,我使用一些代碼來停止行移動。 – Sagotharan

0
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! */ 
    } 
} 
相關問題