Tim Schmelter
Tim Schmelter

Reputation: 460058

Cannot edit DataGridView-cell, Validating-event sets e.Cancel = true

The DatagridView drives me crazy again. So i have a form with a DatagridView which works until now. But now there's an invalid value in the database which causes the Validating event to block the program flow.

This is it:

private void GrdChargeAssignment_Validating(Object sender, DataGridViewCellValidatingEventArgs e)
{
    e.Cancel = false;
    var grid = (DataGridView)sender;
    ErpService.ArrivalChargeAssignment ass = grid.Rows[e.RowIndex].DataBoundItem as ErpService.ArrivalChargeAssignment;

    string countValue = grid.Rows[e.RowIndex].Cells[AssignedCol.Name].EditedFormattedValue.ToString();
    if (string.IsNullOrWhiteSpace(countValue))
    {
        grid.Rows[e.RowIndex].Cells[AssignedCol.Name].Value = "0";
        countValue = "0";
    }

    int count;
    if (!int.TryParse(countValue, out count))
    {
        grid.Rows[e.RowIndex].ErrorText = "Insert a valid integer for count!";
        e.Cancel = true;
    }
    else if (count > ass.Count_Actual)
    {
        grid.Rows[e.RowIndex].ErrorText = string.Format("Please insert a count between 0 and arrival-count({0})!", ass.Count_Actual);
        e.Cancel = true;  // !!!! HERE !!!!
    }

    if (e.Cancel == false)
        grid.Rows[e.RowIndex].ErrorText = "";
}

The line that i've commented with !!!! HERE !!!! causes the event to be canceled which blocks the gui. The user cannot edit this invalid value.

During databinding i have already unsubscribed from this event to disable it. But now it is still triggered if the user clicks into the cell to edit the invalid value. The call-stack window shows that it's triggered internally from the CellMouseDown-event. How can i prevent this? I want it to be validated only if the user has edited a cell and leaves it.

Upvotes: 3

Views: 919

Answers (1)

Gary Wright
Gary Wright

Reputation: 2469

If you only want to validate when the user changes the value, could you check for modifications before applying the validation? Something like:

else if (count > ass.Count_Actual)
{
    if( count == ass.Count )
    {
        // The data has not changed, do not validate
    }
    else
    {
        grid.Rows[e.RowIndex].ErrorText = string.Format("Please insert a count between 0 and arrival-count({0})!", ass.Count_Actual);
        e.Cancel = true;  // !!!! HERE !!!!
    }
}

If the user edits the value to another invalid value, the validation will kick in, otherwise, the bad data is ignored.

Upvotes: 1

Related Questions