2011-07-28 8 views
2

私はwinformでdatagridviewを使用しています。DataGridviewでEnterキーを押すとコードを実行する方法は?

Enterキーを押すと、選択肢が行単位で移動します。しかし、私は以下のコードを実行したい:

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! */ 
    } 
}