InvalidOperationException - When ending editing a cell & moving to another cell

北战南征 提交于 2019-11-29 15:00:57

There's an answer by Bruce.Zhou at MSDN forums. I posted here a snippet from it. Here also is the link to the original post.

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    ...................................................;
    if (toUpdate)
    {
        foreach(DataRow row in dt.Rows)
        {
            if ( (int)row["ID"] == id)
            {
                row[columnName] = value;
            }
        }

        this.BeginInvoke(new MethodInvoker(Refresh_dataGridView1));
    }
}

...

When using this fix, whenever the new cell is selected, all the cells between it and the first cell (including) are selected. I am looking for a way to select only the new cell.

i knocked my head against the keyboard for the last hour to solve this issue. here is my workaround: looking at the problem: when selecting another cell (or any control within the gridview) EndEdit is triggered.

apply the following check before applying your edit:

public void myGrid_EndEdit(object sender, DataGridViewCellEventArgs e) 
{
  if (!myGrid.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected)
                return;
  //...rest of your code to apply edit below...
}

This should apply to any cell being edited.(thus edit is not applied when losing focus; Typing Enter would suffice to apply the edit)

My work around was to capture the CellMouseDown event, and if the action was on a cell other than that being edited, then it issues the DataGridView.EndEdit(). Everything else works as expected.

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