2014-02-19 69 views
4

我有一個DataGridView填充DataTable,有10列。當我單擊Enter鍵時從一行移動到另一行時,我有一個場景,那麼我需要選擇該行並需要具有該行值。DataGridView「輸入」鍵事件處理

但在這裏,當我選擇ň個排那麼它會自動移動到N + 1行。

請幫我在這...

在頁面加載事件:

SqlConnection con = 
    new SqlConnection("Data Source=.;Initial Catalog=MHS;User ID=mhs_mt;[email protected]"); 

DataSet ds = new System.Data.DataSet(); 
SqlDataAdapter da = new SqlDataAdapter("select * from MT_INVENTORY_COUNT", con); 
da.Fill(ds); 
dataGridView1.DataSource = ds.Tables[0]; 

然後,

private void dataGridView1_KeyPress(object sender, KeyPressEventArgs e) 
{ 
    if (e.KeyChar == (Char)Keys.Enter) 
    { 
      int i = dataGridView1.CurrentRow.Index; 
      MessageBox.Show(i.ToString()); 
    }  
} 

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) 
{ 
    int i = dataGridView1.CurrentRow.Index; 
    MessageBox.Show(i.ToString()); 
} 
+0

做你想按回車鍵然後選擇移動到下一排啊? – Sathish

+0

不,我想當前行本身 – MSanika

回答

3

這是在DataGridView的默認行爲,和漂亮的標準在第三方供應商的其他數據網格中。

這裏是發生了什麼:

  1. 用戶點擊回車鍵
  2. 在DataGridView接收KeyPress事件和執行各種操作(如結束編輯等),然後向下移動單元格一個行。
  3. 然後DataGridView將檢查是否有任何事件處理程序與您連接並觸發它們。

因此,當按下回車鍵時,當前單元格已經改變。

如果您想在DataGridView更改行之前獲取用戶所在的行,則可以使用以下內容。這應該配合您現有的代碼(很明顯,你將需要添加的事件處理程序的話):

void dataGridView1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) 
{ 
    if (e.KeyCode == Keys.Enter) 
    { 
     int i = dataGridView1.CurrentRow.Index; 
     MessageBox.Show(i.ToString()); 
    }  
} 

我希望幫助你指出正確的方向。不知道你希望在這裏做什麼,但希望這可以解釋你所看到的事情。

+0

我錯了,因爲我預期,CurrentRow索引自動增加1,但不是這與GridView的最後一行相同。任何幫助? – MSanika

+0

如果連接PreviewKeyDown事件,它將在DataGridView將單元向下移動一行之前觸發。例如,我用我的建議運行你的代碼,並得到兩個消息框。其中一個表示「2」 - 因爲它在第三行,而下一個 - 來自KeyPress事件的表示「3」 - 在處理程序被調用之前,它向下移動到下一行。 這不是你所遇到的嗎? –

+0

我應該提到,如果您正在編輯單元格,按Enter鍵時不會觸發PreviewKeyDown事件,但KeyPress事件也不會發生。這是因爲用於編輯DataGridView中的數據的文本框處理鍵盤輸入。你也可以附加一個處理程序,但是這有點多。讓我知道你是否希望我告訴你如何。 –

2

添加班級用下面的代碼並修改你的GridView設計師頁即

this.dataGridView1 = New System.Windows.Forms.DataGridView();

this.dataGridView1 = new GridSample_WinForms.customDataGridView();

類文件是:

class customDataGridView : DataGridView 
{ 
    protected override bool ProcessDialogKey(Keys keyData) 
    { 
    if (keyData == Keys.Enter) 
    { 
     int col = this.CurrentCell.ColumnIndex; 
     int row = this.CurrentCell.RowIndex; 
     this.CurrentCell = this[col, row]; 
     return true; 
    } 
    return base.ProcessDialogKey(keyData); 
    } 

    protected override void OnKeyDown(KeyEventArgs e) 
    { 
    if (e.KeyData == Keys.Enter) 
    { 
     int col = this.CurrentCell.ColumnIndex; 
     int row = this.CurrentCell.RowIndex; 
     this.CurrentCell = this[col, row]; 
     e.Handled = true; 
    } 
    base.OnKeyDown(e); 
    } 
} 
+0

謝謝,我一直在尋找這個。 ProcessDialogKey是如何捕獲KeyDown的方式,如果我在單元格中 – rosta