2014-09-29 78 views
1

我知道這個問題(或它的變體)已經拿出了幾次。但到目前爲止,我還沒有找到適合我的解決方案。阻止Windows窗體DataGridView移動到下一行上按ENTER鍵

我正在寫一個Windows使用包含一個DataGridView呈現僱員數據的只讀集合作爲一種榮耀選擇列表中的C#用戶控件形式。網格是隻讀的(在control_load上填充)並將FullRowSelect設置爲選擇方法。我希望用戶能夠通過雙擊鼠標或使用當前行上的Enter鍵來選擇一個由訂戶在其他地方處理的行的Id值。

在分配我選擇員工價值後處理KeyDown事件,我試圖阻止選擇移動到下一行。這個工作正常,除了當CurrentCell.RowIndex爲零。 有誰知道我可以如何得到這個工作CurrentCell.Rowindex = 0?

private void dgvEmployees_KeyDown(object sender, KeyEventArgs e) 
{ 
    if (e.KeyCode == Keys.Enter) 
    { 
     if (dgvEmployees.CurrentRow.Cells[0].Value != null) 
     { 
      this.SelectedEmployeeId = (int) dgvEmployees.CurrentRow.Cells[0].Value; 
      this.OnEmployeeSelected(new TestEmployeeGridListEventArgs() { 
      SelectedEmployeeId = this.SelectedEmployeeId, 
      SelectedEmployeeIdentifier = dgvEmployees.CurrentRow.Cells["Identifier"].Value.ToString() 
      }); 
     } 

     // Prevent pressing <enter key> moving onto the next row. 
     if (dgvEmployees.CurrentCell.RowIndex > 0) 
     { 
      dgvEmployees.CurrentCell = dgvEmployees[1, dgvEmployees.CurrentCell.RowIndex - 1]; 
      dgvEmployees.CurrentRow.Selected = true; 
     } 
     else 
     { 
      dgvEmployees.CurrentCell = dgvEmployees[1, 0]; 
      dgvEmployees.Rows[0].Cells[1].Selected = true; 
     }   
    } 
} 
+2

你試過了'e.Handled = true;'還是'e.SuppressKeyPress'? – Reniuz 2014-09-29 09:52:40

+0

我沒有想到這一點。在else塊中將e.Handled或SuppressKeyPress設置爲true可以讓我確切地找到我正在尋找的行爲。非常感謝。 – 2014-09-29 10:04:31

+0

你可以用它來代替所有'if'語句的代碼塊 – Reniuz 2014-09-29 10:07:05

回答

2

感謝Reniuz的擡頭。我所需要的只是設置e.Handled = truee.SuppressKeyPress = true替換整個if (dgvEmployees.CurrentCell.RowIndex > 0)聲明。

if (e.KeyCode == Keys.Enter) 
{ 
    if (dgvEmployees.CurrentRow.Cells[0].Value != null) 
    { 
     this.SelectedEmployeeId = (int) dgvEmployees.CurrentRow.Cells[0].Value; 
     this.OnEmployeeSelected(new TestEmployeeGridListEventArgs() { 
      SelectedEmployeeId = this.SelectedEmployeeId, 
      SelectedEmployeeIdentifier = dgvEmployees.CurrentRow.Cells["Identifier"].Value.ToString() 
     }); 
    } 

    e.SuppressKeyPress = true; 
} 
相關問題