如何更改DataGridView中的Tab键顺序?

时间:2009-04-10 12:47:34

标签: c# winforms datagridview

我的客户希望在通过DataGridView单元格选项卡时,下一个当前单元格不是默认单元格。实现这一目标的最佳方法是什么?

2 个答案:

答案 0 :(得分:2)

创建自己的DataGridView,重写ProcessTabKey方法。你在那里逻辑,使用SetCurrentCellAddressCore来设置下一个活动单元格。

请注意,该方法的默认实现会考虑许多不同的条件,例如选择模式,编辑模式,行状态,边界等。

修改

或者,您可以处理KeyUp / KeyDown事件。虽然,它有一些奇怪的行为,我没有花太多时间,这应该做:

将网格的StandardTab属性设置为True,并添加以下代码:

private void Form1_Load(object sender, EventArgs e)
{
    // TODO: Load Data

    dataGridView1.CurrentCell = dataGridView1.Rows[0].Cells[0];

    if (dataGridView1.CurrentCell.ReadOnly)
        dataGridView1.CurrentCell = GetNextCell(dataGridView1.CurrentCell);
}

private void dataGridView1_KeyUp(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Tab)
    {
        dataGridView1.CurrentCell = GetNextCell(dataGridView1.CurrentCell);
        e.Handled = true;
    }
}

private DataGridViewCell GetNextCell(DataGridViewCell currentCell)
{
    int i = 0;
    DataGridViewCell nextCell = currentCell;

    do
    {
        int nextCellIndex = (nextCell.ColumnIndex + 1) % dataGridView1.ColumnCount;
        int nextRowIndex = nextCellIndex == 0 ? (nextCell.RowIndex + 1) % dataGridView1.RowCount : nextCell.RowIndex;
        nextCell = dataGridView1.Rows[nextRowIndex].Cells[nextCellIndex];
        i++;
    } while (i < dataGridView1.RowCount * dataGridView1.ColumnCount && nextCell.ReadOnly);

    return nextCell;
}

答案 1 :(得分:0)

先生。 Ruslan代码对我没用。通过提取他的想法,我在代码中做了一些改变。

private void dataGridView1_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Tab)
        {
            if(dataGridView1.CurrentCell.ReadOnly)
                dataGridView1.CurrentCell = GetNextCell(dataGridView1.CurrentCell);
            e.Handled = true;
        }
    }

    private DataGridViewCell GetNextCell(DataGridViewCell currentCell)
    {
        int i = 0;
        DataGridViewCell nextCell = currentCell;

        do
        {
            int nextCellIndex = (nextCell.ColumnIndex + 1) % dataGridView1.ColumnCount;
            int nextRowIndex = nextCellIndex == 0 ? (nextCell.RowIndex + 1) % dataGridView1.RowCount : nextCell.RowIndex;
            nextCell = dataGridView1.Rows[nextRowIndex].Cells[nextCellIndex];
            i++;
        } while (i < dataGridView1.RowCount * dataGridView1.ColumnCount && nextCell.ReadOnly);

        return nextCell;
    }