[英]Datagridview enter key selects next cell from next row
The code works only when i'm adding a value at first time. 该代码仅在我第一次添加值时有效。 The problem is that when i'm going back in a previous value which i added and i'm hitting enter it selects next cell from next row, not the next right cell.
问题是,当我返回添加的上一个值并按Enter键时,它将选择下一行中的下一个单元格,而不是下一个右单元格。
Here is my code: 这是我的代码:
private void dataGridView1_CellEndEdit(object sender, KeyEventArgs e)
{
int col = dataGridView1.CurrentCell.ColumnIndex;
int row = dataGridView1.CurrentCell.RowIndex;
if (col < dataGridView1.ColumnCount - 1)
{
col++;
}
else
{
col = 0;
row++;
}
if (row == dataGridView1.RowCount)
dataGridView1.Rows.Add();
dataGridView1.CurrentCell = dataGridView1[col, row];
}
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.AllowUserToAddRows = false;
dataGridView1.Rows.Add();
}
Just changed the approach completely. 只是完全改变了方法。 Created a new class, extended it with DataGridView and overrode two functions.
创建了一个新类,使用DataGridView对其进行了扩展 ,并覆盖了两个功能。 OnKeyDown and ProcessDialogKey
OnKeyDown和ProcessDialogKey
Here is the code: 这是代码:
class CustomDataGridview : DataGridView
{
protected override bool ProcessDialogKey(Keys keyData) // Fired when key is press in edit mode
{
if (keyData == Keys.Enter)
{
MoveToRightCell();
return true;
}
return base.ProcessDialogKey(keyData);
}
protected override void OnKeyDown(KeyEventArgs e) // Fired when key is press in non-edit mode
{
if (e.KeyData == Keys.Enter)
{
MoveToRightCell();
e.Handled = true;
return;
}
base.OnKeyDown(e);
}
private void MoveToRightCell()
{
int col = this.CurrentCell.ColumnIndex;
int row = this.CurrentCell.RowIndex;
if (col < this.ColumnCount - 1)
{
col++;
}
else
{
col = 0;
row++;
}
if (row == this.RowCount)
{
this.Rows.Add();
}
this.CurrentCell = this[col, row];
}
}
After adding this class build you project and then you can simply chose this new control from Toolbox>DgvDemoComponents>CustomDataGridview Or if you want to convert the old DataGridView into a new one just change to following line: 添加此类构建后,您可以进行项目开发,然后只需从Toolbox> DgvDemoComponents> CustomDataGridview中选择此新控件,或者如果要将旧的DataGridView转换为新控件,只需更改为以下行:
this.dataGridView1 = new System.Windows.Forms.DataGridView();
to 至
this.dataGridView1 = new DgvDemo.CustomDataGridview();
The Second approach will cause some issues in designer just select ignore and proceed. 第二种方法会在设计器中引起一些问题,只是选择忽略并继续。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.