简体   繁体   中英

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. 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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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