Cornel
Cornel

Reputation:

How do I change the tab order in a DataGridView?

My client wants that when tabbing through DataGridView cells the next current cell to be other than the default one. What's the best way to accomplish this?

Upvotes: 2

Views: 8123

Answers (2)

vinrav
vinrav

Reputation: 370

Mr. Ruslan code did not worked for me. By fetching his idea, i made some change in code.

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

Upvotes: 0

Ruslan
Ruslan

Reputation: 1761

Create your own DataGridView, override ProcessTabKey method. Do you logic there, use SetCurrentCellAddressCore to set next active cell.

Note that the default implementation of that method accounts for many different conditions, such as selection mode, editing mode, row states, bounds etc.

Edit

Alternatively, you could handle KeyUp/KeyDown events. Although, there is some weird behavior with it and I didn't spend much time, this should do:

Set StandardTab property of the grid to True, and add following code:

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

Upvotes: 2

Related Questions