Reputation: 1526
I'm trying to validate the value of a cell to ensure that it's numeric. If it isn't I want to display an error, wipe the cell, and set them back into the cell to correct.
private void gridData_CellEndEdit(object sender, DataGridViewCellEventArgs e) {
// If Cell Edited is in the Add'l Qty Column
if (gridData.Columns[e.ColumnIndex].Name == "AddlQty") {
int intVal;
// Validate Entry for Numeric Only
if (int.TryParse(gridData.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString(), out intVal)) {
CalcFinalQty(e.RowIndex);
} else {
// Clear and Send User Back to Try Again
gridData.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "";
gridData.CurrentCell = gridData.Rows[e.RowIndex].Cells[e.ColumnIndex];
MessageBox.Show("Entry Not Valid, Only Numeric Values Accepted");
gridData.BeginEdit(true);
}
}
} // End gridData_CellEndEdit
It catches if it's numeric or not, wipes the cell, but displays the MessageBox twice. After the first time, the selected cell moves to the next cell down, it pops up another MessageBox, and THEN moves back to the cell and set to edit.
If you hit Enter without entering anything into the cell, it gives a Null exception error.
Upvotes: 0
Views: 46
Reputation: 418
I have a suspicion here. I think beginEdit is triggering somehow the event the second time. If that's the case can you double check in your else statement that the value is not empty and if it's not, then show message box? it'd be something like :
private void gridData_CellEndEdit(object sender, DataGridViewCellEventArgs e) {
// If Cell Edited is in the Add'l Qty Column
if (gridData.Columns[e.ColumnIndex].Name == "AddlQty") {
int intVal;
// Validate Entry for Numeric Only
if (int.TryParse(gridData.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString(), out intVal)) {
CalcFinalQty(e.RowIndex);
} else {
if(!String.IsNullOrEmpty(gridData.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()))
// Clear and Send User Back to Try Again
gridData.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "";
gridData.CurrentCell = gridData.Rows[e.RowIndex].Cells[e.ColumnIndex];
MessageBox.Show("Entry Not Valid, Only Numeric Values Accepted");
gridData.BeginEdit(true);
}
}
}
Let me know if it helps, cheers.
Upvotes: 1
Reputation: 1909
Try assigning a "0" value instead of clearing.
gridData.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "0";
When execute gridData.BeginEdit(true);
it goes back to the edit event and will goes to each cell and Try.Parse
part is called again.
Try.Parse
is getting false because it can't parse ""
value to int
.
This ensures that your application will force to put zero value when user didn't put anything.
Upvotes: 1