H H H H - 15 days ago 12
C# Question

datagridview clear and cellvalidate issue

I have a

dataGridView
containing multiple columns. The first column is an identifier, which must be a unique 1 or 2 digit number. I use cell validating to ensure that the identifier satisfies these criteria. The user enters data, as many rows as needed, then exports the data. After exporting the data the program clears the
dataGridView
by calling
grid.Clear()
and
grid.Refresh()
.

This works well most of the time but sometimes when the rows are being deleted I get an error indicating the cell number in column 1 is not unique. I can't consistently reproduce this error; when I enter the debugger typically if I try and break at the cell validating step I find that it's not being called during the clear, as I expect. However sometimes it does break there during the clear and that of course causes problems.

Does anyone have any ideas as to what might be causing this problem?

Edit: Here's my cellValidate code:

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

H H H H
Answer

The problem turned out to be that I was sometimes clearing the dataGridView with a cell in the identifier column selected and thus in focus. By turning multi-select off and changing the focus to a different cell before calling clear() I was able to fix the problem.