my goal is to have a friendly validation flow on my DataGridView.
When the user enters an incorrect value for a certain cell, I want to:
I am currently using the CellValidating event to prevent the cell from updating its value but I'm not able to exit the editing mode. The cell is then waiting for a correct value and won't let the user to simply cancel&revert his action...
Here is what the validation method looks like :
private void dataGridViewMsg_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
[...] // Here, treatment determines is the new cell value isValid or not
if (!isValid)
{
MessageBox.Show("The value entered is incorrect.", "Modification aborted");
e.Cancel = true;
dataGridViewMsg[e.ColumnIndex, e.RowIndex].IsInEditMode = false; // Someway, what I would like to do
return;
}
}
How can I proceed to make the cell recover its original value without requiring me to keep track of this value?
You can use EndEdit()
to get what you want.
In any case, note that it is better to make sure that the cancellation happens only under the expected conditions; otherwise, the code might get stuck in this event because it is automatically called at many different points. For example, to validate the inputs written by the user via cell edition, you can rely on an approach on the lines of the following one:
bool cancelIt = false;
private void dataGridViewMsg_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
[...] // Here, treatment determines is the new cell value isValid or not
if (cancelIt && !isValid)
{
MessageBox.Show("The value entered is incorrect.", "Modification aborted");
e.Cancel = true;
dataGridViewMsg.EndEdit();
cancelIt = false;
}
}
//CellBeginEdit event -> the user has edited the cell and the cancellation part
//can be executed without any problem
private void dataGridViewMsg_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
cancelIt = true;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With