1

我有一个dataGridView包含多个列。第一列是标识符,它必须是唯一的 1 位或 2 位数字。我使用单元格验证来确保标识符满足这些标准。用户根据需要输入任意多行的数据,然后导出数据。dataGridView导出数据后,程序通过调用grid.Clear()和清除grid.Refresh()

这在大多数情况下都很好用,但有时当删除行时,我会收到一个错误,表明第 1 列中的单元格编号不是唯一的。我无法始终如一地重现此错误;当我通常进入调试器时,如果我尝试在单元格验证步骤中中断,我发现它在清除期间没有被调用,正如我所期望的那样。然而,有时它在清除期间确实会在那里中断,这当然会导致问题。

有没有人对可能导致此问题的原因有任何想法?

编辑:这是我的 cellValidate 代码:

private void Grid_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
    {
        string headerText = Grid.Columns[e.ColumnIndex].HeaderText;

        switch (headerText)
        {
            case "Number":

                if (!String.IsNullOrEmpty(e.FormattedValue.ToString()))
                {
                    if (!Regex.IsMatch(e.FormattedValue.ToString(), @"(^\d{1,2}$)"))
                    {
                        MessageBox.Show("Identifier number must be a 1 or 2 digit positive number");
                        e.Cancel = true;
                    }

                    else
                    {
                        foreach (DataGridViewRow r in Grid.Rows)
                        {
                            if (r.Cells[0].Value != null)
                            {
                                if (e.FormattedValue.ToString() == r.Cells[0].Value.ToString())
                                {
                                    //this message box pops up sometimes when I call Grid.Clear()
                                    MessageBox.Show("Identifier number must unique");
                                    e.Cancel = true;
                                }
                            }
                        }
                    }
                }
                break; //more cases for each column
4

2 回答 2

0

问题原来是我有时会在选定的标识符列中使用一个单元格清除 dataGridView,从而获得焦点。通过在调用 clear() 之前关闭多选并将焦点更改为不同的单元格,我能够解决问题。

于 2012-12-20T15:20:58.110 回答
0

在 Grid_CellValidating 事件中使用布尔值并绕过它,在清除 Datagridview 后,您可以重置布尔值

于 2016-11-22T10:47:43.267 回答