I have dataGridView with one row, which may contain from 1 to 30 cells.
Now I need to check the input data while typing, and if the verification is passed, then give focus to the next cell... By the way, there is MaxInputLength for each cell set by 1.
The main idea, it's to check current cell while typing into it.
P.S. Cells are creating programmatically and each of them can contain only 1 letter.
Well, for checking I made next one and it works:
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (dataGridView1.CurrentCell.RowIndex == 0)
{
TextBox tb = (TextBox)e.Control;
tb.KeyPress += new KeyPressEventHandler(tb_KeyPress);
}
}
void tb_KeyPress(object sender, KeyPressEventArgs e)
{
List<string> detect = new List<string> { "№", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "`", "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "+", "=", "-", "/", "*", ".", "|", "]", "[", "}", "{", "'", ";", ":", "?", ">", "<", ",", "\"", "\\" };
var character = e.KeyChar.ToString();
if (dataGridView1.CurrentCell.RowIndex == 0)
{
foreach (string Item in detect)
{
if (character == Item)
{
e.Handled = true;
}
}
}
}
Now I only need move focus to the next cell if current cell has 1 letter.
I found this code and it looks suitable but actually I don't know what to do with it:
public static class GridExtension
{
public static void MoveNextCell(this DataGridView dgv)
{
DataGridViewCell currentCell = dgv.CurrentCell;
if (currentCell != null)
{
int nextRow = currentCell.RowIndex;
int nextCol = currentCell.ColumnIndex + 1;
if (nextCol >= dgv.ColumnCount)
{
nextCol = 0;
nextRow++;
}
if (nextRow >= dgv.RowCount)
{
nextRow = 0;
}
DataGridViewCell nextCell = dgv.Rows[nextRow].Cells[nextCol];
if (nextCell != null && nextCell.Visible)
{
if ((currentCell != null) && (currentCell.IsInEditMode))
dgv.EndEdit();
try
{
dgv.CurrentCell = nextCell;
}
catch (InvalidOperationException) { } //Fails if you have cell validation
}
}
}
}
Any help on how to use it?