要使按下Enter鍵達到與按下Tab鍵一樣的效果,我們需要從DataGridView中派生出一個類,寫一個自訂的DataGridView控制項。這裡有兩個方面需要考慮。一方面,當DataGridView不處於編輯狀態:在這種情況下,我們需要重寫OnKeyDown事件來實現我們所需要的定位邏輯。另一方面,當DataGridView處於編輯的狀態下:在這種情況下,Enter鍵是在ProcessDialogKey事件中被處理,因此我們需要重寫該事件。詳見以下樣本:
代碼
class myDataGridView : DataGridView
{
protected override bool ProcessDialogKey(Keys keyData)
{
if (keyData == Keys.Enter)
{
int col = this.CurrentCell.ColumnIndex;
int row = this.CurrentCell.RowIndex;
if (row != this.NewRowIndex)
{
if (col == (this.Columns.Count - 1))
{
col = -1;
row++;
}
this.CurrentCell = this[col + 1, 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;
if (row != this.NewRowIndex)
{
if (col == (this.Columns.Count - 1))
{
col = -1;
row++;
}
this.CurrentCell = this[col + 1, row];
}
e.Handled = true;
}
base.OnKeyDown(e);
}
}
運用:
this.dataGridView1 = new myDataGridView();