我有一行 dataGridView,其中可能包含 1 到 30 个单元格。现在我需要在输入时检查输入数据,如果验证通过,则将焦点放在下一个单元格上……顺便说一下,每个单元格的 MaxInputLength 设置为 1。
主要思想是在输入时检查当前单元格。
PS 单元以编程方式创建,每个单元只能包含 1 个字母。
好吧,为了检查我做了下一个,它可以工作:
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;
}
}
}
}
现在,如果当前单元格有 1 个字母,我只需要将焦点移动到下一个单元格。
我找到了这段代码,它看起来很合适,但实际上我不知道如何处理它:
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
}
}
}
}
关于如何使用它的任何帮助?