DataGridView cell validation

In my datagridview I want to add validation to ensure entered values are between a certain numeric range. I'm doing my checking in the CellValidating event. This works out fine:

 private void gvTraining_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) { switch (gvTraining.Columns[e.ColumnIndex].HeaderText) { case "NextTrainingLevel": { int newInteger; if (!int.TryParse(e.FormattedValue.ToString(), out newInteger) || newInteger <= 0 || newInteger >= 21) { gvTraining.Rows[e.RowIndex].ErrorText = "Please enter a numeric value between 0 and 21. Press Esc to clear."; e.Cancel = true; } } break; case "TrainingScore": { int newInteger; if (!int.TryParse(e.FormattedValue.ToString(), out newInteger) || newInteger <= 0 || newInteger >= 2046820351) { gvTraining.Rows[e.RowIndex].ErrorText = "Please enter a numeric value between 0 and 2046820351. Press Esc to clear."; e.Cancel = true; } } break; case "TrainingLevelComp": { int newInteger; if (!int.TryParse(e.FormattedValue.ToString(), out newInteger) || newInteger <= 0 || newInteger >= 20) { gvTraining.Rows[e.RowIndex].ErrorText = "Please enter a numeric value between 0 and 20. Press Esc to clear."; e.Cancel = true; } } break; } 

According to what I'm reading online, I also need to use the CellEndEdit event to clear the row error text if the user presses Esc. So I added this and it works fine as well:

 private void gvTraining_CellEndEdit(object sender, DataGridViewCellEventArgs e) { gvTraining.Rows[e.RowIndex].ErrorText = String.Empty; } 

However, it seems that once the cell has entered the error state, the only way to clear that error is to hit Esc. This seems strange. If I see the error and correct it without hitting Esc, it still stays in the error state. I must hit Esc to continue.

Is there a way to do this without needing to hit Esc after failing validation?

by LordDrakken via /r/csharp

Leave a Reply