Как программно перейти из одной ячейки в сетке данных в другую?
Мне нужно разрешить ввод только одного символа в редактируемые ячейки таблицы данных (все остальные столбцы, нечетные, редактируются); если пользователь добавляет второй символ, находясь в одной из этих ячеек, курсор должен переместиться на следующую ячейку вниз и поместить туда второе значение (повторное нажатие на эту клавишу снова перемещается вниз и т. д.). Если в нижней части сетки (12-й ряд), он должен переместиться в строку 0, а также переместить два столбца вправо.
Я пытался сделать это:
private void dataGridViewPlatypus_KeyDown(object sender, KeyEventArgs e) {
var currentCell = dataGridViewPlatypus.CurrentCell;
int currentCol = currentCell.ColumnIndex;
int currentRow = currentCell.RowIndex;
if (currentCell.Value.ToString().Length > 0) {
if (currentRow < 11) {
dataGridViewPlatypus.CurrentCell.RowIndex = currentRow+1;
} else if (currentRow == 11) {
currentCell.RowIndex = 0;
currentCell.ColumnIndex = currentCell.ColumnIndex + 2;
dataGridViewPlatypus.CurrentCell = currentCell;
}
}
}
... но я получаю сообщения об ошибках, которые нельзя назначить RowIndex и ColumnIndex, так как они доступны только для чтения.
Так как я могу это сделать?
Предостережение: я знаю, что мне также нужно будет добавить логику, чтобы перейти к столбцу 1, если в данный момент он находится внизу последнего редактируемого столбца.
UPDATEИз ответа tergiver'а это то, что я до сих пор получил, но я не знаю, как перейти к следующей ячейке.
protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
if (this.ActiveControl == dataGridViewPlatypus)
{
var currentCell = dataGridViewPlatypus.CurrentCell;
if (currentCell.Value.ToString().Length == 1)
{
;//Now what?
}
}
return base.ProcessCmdKey(ref msg, keyData);
}
UPDATE 2
Спасибо всем; это то, что я использую, чтобы заставить его работать в значительной степени (я все еще хочу иметь возможность позволить пользователю просто удерживать клавишу, и чтобы это значение непрерывно вводилось в последующих ячейках):
private void dataGridViewPlatypus_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) {
int columnIndex = (((DataGridView)(sender)).CurrentCell.ColumnIndex);
if (columnIndex % 2 == 1) {
e.Control.KeyDown -= TextboxNumeric_KeyDown;
e.Control.KeyDown += TextboxNumeric_KeyDown;
e.Control.KeyUp -= TextboxNumeric_KeyUp;
e.Control.KeyUp += TextboxNumeric_KeyUp;
}
}
private void TextboxNumeric_KeyDown(object sender, KeyEventArgs e) {
var tb = sender as TextBox;
if (tb != null) {
tb.MaxLength = 1;
}
}
// TODO: Now need to find a way to be able to just press down once
private void TextboxNumeric_KeyUp(object sender, KeyEventArgs e) {
var tb = sender as TextBox;
if (tb != null && tb.TextLength >= 1) {
if (dataGridViewPlatypus.CurrentCell.RowIndex != dataGridViewPlatypus.Rows.Count - 1) {
dataGridViewPlatypus.CurrentCell = dataGridViewPlatypus[
dataGridViewPlatypus.CurrentCell.ColumnIndex,
dataGridViewPlatypus.CurrentCell.RowIndex + 1];
} else { // on last row
this.dataGridViewPlatypus.CurrentCell = this.dataGridViewPlatypus.CurrentCell.ColumnIndex != dataGridViewPlatypus.Columns.Count - 1 ? this.dataGridViewPlatypus[this.dataGridViewPlatypus.CurrentCell.ColumnIndex + 2, 0] : this.dataGridViewPlatypus[1, 0];
}
}
}