C# DataGridView-使Enter按钮转到下一列而不是下一行

C# DataGridView-使Enter按钮转到下一列而不是下一行,c#,datagridview,C#,Datagridview,在DataGridView中,我将Enter按钮设置为转到下一列,就像Tab键一样。但如果有人编辑单元格,它将转到下一行。如何解决这个问题 这是我的密码: int col = dataGridView2.CurrentCell.ColumnIndex; int row = dataGridView2.CurrentCell.RowIndex; if(col<dataGridView1.ColumnCount-1) { col++; } else { col = 0;

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;
int col=dataGridView2.CurrentCell.ColumnIndex;
int row=dataGridView2.CurrentCell.RowIndex;

if(col这有点棘手,因为
DataGridView
控件会自动处理Enter键以转到下一行而不是下一列。此外,没有任何属性可以直接更改此属性

但是,当用户编辑单元格并按Enter键时,可以使用一种变通方法手动更改到下一列

一种方法是在
DataGridView
控件上处理
CellEndEdit
SelectionChanged
事件。在
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;
    }
}