views:

638

answers:

2

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?

+1  A: 

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;
}
Ruslan
A: 

let me tell it easier, I need an example bypassing read only cells without making a new DataGridView