Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cancel cell validation AND exit editing mode

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:

  • exit editing mode
  • revert the modification (i.e. recover the original value from the cell)
  • display an error message

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?

like image 902
KwentRell Avatar asked Feb 08 '23 20:02

KwentRell


1 Answers

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;
    }
like image 83
varocarbas Avatar answered Feb 15 '23 12:02

varocarbas