0

我有一行 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
            }
        }
    }
}

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

4

1 回答 1

0

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

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

您可以使用 For Each 循环 Ex 通过其常数评估相同的单元格。

For Each gr As GridViewRow In Me.GV.Rows

gr.Cells(GV_cell1).Text
于 2013-04-15T09:25:12.140 回答