在datagridview&中键入时如何检查输入数据将光标移动到下一个单元格?

时间:2013-04-15 09:17:48

标签: c# datagridview verification

我有一行dataGridView,可能包含1到30个单元格。 现在我需要在输入时检查输入数据,如果验证通过,则将焦点放在下一个单元格......顺便说一下,每个单元格的MaxInputLength设置为1.

主要想法是在输入时检查当前单元格。

P.S。单元格以编程方式创建,每个单元格只能包含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
            }
        }
    }
}

有关如何使用它的任何帮助?

1 个答案:

答案 0 :(得分:0)

首先,您需要分配常量值,以便在运行时检查相同的值 例如:

Private Const GV_Cell1 As Integer = 0
Private Const GV_Cell2 As Integer = 1

您可以使用For Each循环按常量评估相同的单元格  实施例

For Each gr As GridViewRow In Me.GV.Rows

gr.Cells(GV_cell1).Text