问题
When I enter some value in a cell in DataGridView and click on another cell the cellvalidating event handler code is executed. Even if validation fills, the cell on which I click gets highlighted. My requirement is that the cell should remain selected and cursor should blink in the cell for editing after removing the invalid value. Am using the below code if the validation fails:
DataGridView1.CancelEdit();
I have tried adding
DataGridView1.CurrentCell.Selected = true;
DataGridView1.BeginEdit(true);
回答1:
You need to use e.Cancel = true
like below.
private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
int i;
if (!int.TryParse(e.FormattedValue.ToString(), out i))
{
e.Cancel = true;
MessageBox.Show("Please input a integral number.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
回答2:
I changed my code with the above solution a bit and it worked:
private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
DataGridView1.CancelEdit();
e.Cancel = true;
DataGridView.BeginEdit(true);
}
来源:https://stackoverflow.com/questions/20822270/canceledit-does-not-keep-focus-on-edited-cell-in-datagridview-c-sharp