繁体   English   中英

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

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

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

暂无
暂无

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

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