DataGridView – 使Enter按钮转到下一列而不是下一行

DataGridView ,我将Enter按钮设置为像Tab键一样转到下一列。 但如果有人编辑单元格,它会转到下一行。 怎么解决这个?

这是我的代码:

 int col = dataGridView2.CurrentCell.ColumnIndex; int row = dataGridView2.CurrentCell.RowIndex; if(col<dataGridView1.ColumnCount-1) { col++; } else { col = 0; row++; } if(row==dataGridView2.RowCount) dataGridView1.Rows.Add(); dataGridView2.CurrentCell=dataGridView2[col,row]; //e.Handled = true; 

这有点棘手,因为DataGridView控件自动处理Enter键以转到下一行而不是下一列。 此外,没有任何财产可以直接更改此信息。

但是,只要用户编辑单元格并按Enter,就可以使用手动更改为下一列的变通方法。

一种方法是在DataGridView控件上处理CellEndEditSelectionChanged事件。 在CellEndEdit事件中,您可以设置刚刚编辑过单元格的自定义标志。 然后在SelectionChanged事件中,您可以检测到此标志并将当前单元格更改为下一列而不是下一行。

以下是如何执行此操作的工作示例:

 bool hasCellBeenEdited = false; private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e) { // Set flag that cell has been edited hasCellBeenEdited = true; } private void dataGridView1_SelectionChanged(object sender, EventArgs e) { // If edit flag is set and it's not already the last column, move to the next column if (hasCellBeenEdited && dataGridView1.CurrentCell.ColumnIndex != dataGridView1.ColumnCount - 1) { int desiredColumn = dataGridView1.CurrentCell.ColumnIndex + 1; int desiredRow = dataGridView1.CurrentCell.RowIndex - 1; dataGridView1.CurrentCell = dataGridView1[desiredColumn, desiredRow]; hasCellBeenEdited = false; } // If edit flag is set and it is the last column, go to the first column of the next row else if (hasCellBeenEdited && dataGridView1.CurrentCell.ColumnIndex == dataGridView1.ColumnCount - 1) { int desiredColumn = 0; int desiredRow = dataGridView1.CurrentCell.RowIndex; dataGridView1.CurrentCell = dataGridView1[desiredColumn, desiredRow]; hasCellBeenEdited = false; } }