2 回答
TA贡献1780条经验 获得超5个赞
在过去,我发现实现这种行为的最佳方法是创建一个继承自DataGridView并覆盖该ProcessCmdKey函数的自定义控件。
public class MyDataGridViewControl : DataGridView
{
protected override Boolean ProcessCmdKey(ref Message msg, Keys keyData)
{
Boolean handled = false;
if ((keyData == Keys.Enter || keyData == Keys.Return))
{
handled = NavigateToNextCell();
}
if (!handled)
{
handled = base.ProcessCmdKey(ref msg, keyData);
}
return handled;
}
private Boolean NavigateToNextCell()
{
Boolean retVal = false;
if (CurrentCell != null)
{
Int32 columnIndex = CurrentCell.ColumnIndex;
Int32 rowIndex = CurrentCell.RowIndex;
DataGridViewCell targetCell = null;
do
{
if (columnIndex >= Columns.Count - 1)
{
// Move to the start of the next row
columnIndex = 0;
rowIndex = rowIndex + 1;
}
else
{
// Move to the next cell on the right
columnIndex = columnIndex + 1;
}
if (rowIndex >= RowCount)
{
break;
}
else
{
targetCell = this[columnIndex, rowIndex];
}
} while (targetCell.Visible == false);
if (targetCell != null)
{
CurrentCell = targetCell;
}
retVal = true;
}
return retVal;
}
}
TA贡献1779条经验 获得超6个赞
我已经解决了这个问题。现在它工作正常......
private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Enter)
{
int row = dataGridView1.CurrentCell.RowIndex;
int colIndex = dataGridView1.CurrentCell.ColumnIndex;
if (colIndex < dataGridView1.Columns.Count - 1)
{
dataGridView1.CurrentCell = dataGridView1.Rows[row].Cells[colIndex + 1];
dataGridView1.Focus();
}
else if (colIndex == dataGridView1.Columns.Count - 1)
{
dataGridView1.Rows.Add(1);
dataGridView1.CurrentCell = dataGridView1.Rows[row].Cells[0];
dataGridView1.Focus();
}
}
- 2 回答
- 0 关注
- 388 浏览
添加回答
举报