简体   繁体   English

DataGridView-使“输入”按钮转到下一个列而不是下一行

[英]DataGridView - Make Enter button go to next Column instead of next Row

In DataGridView , I set the Enter button to go to the next column like the Tab key. DataGridView ,我将Enter按钮设置为跳至下一页,例如Tab键。 But if anyone edits the cell, it goes to the next row instead. 但是,如果有人编辑该单元格,它将转到下一行。 How to resolve this? 如何解决呢?

Here's my code: 这是我的代码:

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;

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. 这有点棘手,因为DataGridView控件会自动处理Enter键以转到下一行而不是下一行。 Also, there isn't any property to change this directly. 此外,没有任何属性可以直接更改此设置。

However, there is a workaround you can use to manually change to the next column whenever a user edits a cell and presses Enter. 但是,有一种解决方法,您可以在用户编辑单元格并按Enter时手动将其更改为下一列。

One way you can do this is to handle the CellEndEdit and SelectionChanged events on the DataGridView control. 一种实现方法是处理DataGridView控件上的CellEndEditSelectionChanged事件。 In the CellEndEdit event, you can set a custom flag that a cell has just been edited. CellEndEdit事件中,您可以设置一个自定义标志,表示单元格刚刚被编辑。 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. 然后在SelectionChanged事件中,您可以检测到此标志并将当前单元格更改为下一列而不是下一行。

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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM