我有一个包含多列的dataGridView
。第一列是标识符,必须是唯一的 1 位或 2 位数字。我使用单元格验证来确保标识符满足这些条件。用户输入数据,根据需要输入任意数量的行,然后导出数据。导出数据后,程序通过调用 grid.Clear()
和 grid.Refresh()
来清除dataGridView
。
这在大多数情况下都很好用,但有时在删除行时,我会收到一个错误,指示第 1 列中的单元格编号不是唯一的。我无法始终如一地重现此错误;当我进入调试器时,如果我尝试在单元格验证步骤中断,我发现它没有像我预期的那样在清除期间被调用。然而,有时它确实在清除过程中会在那里破裂,这当然会导致问题。
有没有人对可能导致此问题的原因有任何想法?
编辑:这是我的单元格验证代码:
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
结果发现,我有时会清除 dataGridView,并选中标识符列中的单元格,从而获得焦点。通过在调用clear()之前关闭多选并将焦点更改为其他单元格,我能够解决问题。
在事件中使用布尔值并绕过它Grid_CellValidating清除数据网格视图后,您可以重置布尔值