DataGridView - Make Enter按钮转到下一列而不是下一行 [英] DataGridView - Make Enter button go to next Column instead of next Row
问题描述
在 DataGridView
中,我将Enter按钮转到下一列,如Tab键。但是,如果有人编辑单元格,它会转到下一行。如何解决这个问题?
In DataGridView
, I set the Enter button to go to the next column like the Tab key. But if anyone edits the cell, it goes to the next row instead. How to resolve this?
这是我的代码:
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键转到下一行而不是下一列。此外,没有任何财产可以直接更改。
This is a little tricky because the DataGridView
control automatically handles the Enter key to go to the next row instead of the next column. Also, there isn't any property to change this directly.
但是,当用户编辑单元格时,您可以使用一种解决方法手动更改为下一列并按Enter。
However, there is a workaround you can use to manually change to the next column whenever a user edits a cell and presses Enter.
您可以执行此操作的一种方法是处理 CellEndEdit
和
事件。在 DataGridView
控件中的SelectionChanged CellEndEdit
事件中,您可以设置一个单元格刚刚编辑的自定义标志。然后在 SelectionChanged
事件中,您可以检测此标志,并将当前单元格更改为下一列而不是下一列。
One way you can do this is to handle the CellEndEdit
and SelectionChanged
events on the DataGridView
control. In the CellEndEdit
event, you can set a custom flag that a cell has just been edited. And then in the SelectionChanged
event, you can detect this flag and change the current cell to the next column instead of the next row.
这是一个如何做到这一点的工作示例:
Here's a working example of how you can do this:
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;
}
}
这篇关于DataGridView - Make Enter按钮转到下一列而不是下一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!