我已经编写了以下代码“当用户按 Enter 时转到下一个单元格”,但代码不起作用,我无法找到错误。
private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Enter)
{
int col = dataGridView1.CurrentCell.ColumnIndex;
int row = dataGridView1.CurrentCell.RowIndex;
if (col < dataGridView1.ColumnCount - 1)
{
col++;
}
else
{
col = 1;
row++;
}
if (row == dataGridView1.RowCount)
{
dataGridView1.Rows.Add();
dataGridView1.CurrentCell = dataGridView1[col, row];
e.Handled = true;
}
}
}
过去我发现实现这种行为的最佳方法是创建一个继承自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;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)