I have a datagridview with CellValidating and RowValidating events handled. My problem is that when I click into it and then I change my mind and want to cancel edit of the current row these validating methods won't let me do that if it's the first row, it seems to work when there is already some valid rows, but when it's the first it won't let me change the focus to something else.
So my question is how can I have both validation and the ability to cancel edit of the datagridview row? I don't mind if the current row in the datagridview is lost when edit is canceled.
EDIT: here is my validating methods:
private void Neighbours_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (e.ColumnIndex == 2)
{
int i = 0;
if (!int.TryParse(e.FormattedValue.ToString(), out i) || i <= 0)
{
e.Cancel = true;
Neighbours.Rows[e.RowIndex].ErrorText = "error";
}
}
}
private void Neighbours_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
{
DataGridViewRow r = ((DataGridView)sender).Rows[e.RowIndex];
int dist = 0;
if (r.Cells["NeighboursStop1"].Value == null || r.Cells["NeighboursStop1"].Value.ToString() == "" || r.Cells["NeighboursStop2"].Value == null || r.Cells["NeighboursStop2"].Value.ToString() == "")
{
e.Cancel = true;
r.ErrorText = "error";
}
else if (r.Cells["NeighboursStop1"].Value.ToString() == r.Cells["NeighboursStop2"].Value.ToString())
{
e.Cancel = true;
r.ErrorText = "error";
}
else if(!int.TryParse(r.Cells["NeighboursDistance"].Value.ToString(), out dist))
{
e.Cancel = true;
r.ErrorText = "error";
}
else if (dist <= 0)
{
e.Cancel = true;
r.ErrorText = "error";
}
else
{
r.ErrorText = "";
}
}
Here is how it looks when it happens, if I hit Escape key, the error message disappears, but when I try to click something else, RowValidation happens again and I back to this state:

EDIT2: I use datatable as datasource for this datagridview.