CancelEdit does not keep focus on edited cell in DataGridView c#

狂风中的少年 提交于 2020-01-03 04:55:29

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!