开发者

Can't Delete a row from a DataGridView

I'm simply trying to delete a row from a DataGridView. Basically, the first column is a combo box, and when the user selects "[Remove]" from the combo box, the entire row should be removed. So I have this OnCellEndEdit event code:

if (grid.CurrentCell.ColumnIndex == 0 && grid.CurrentRow.Cells[0].Value.ToString()=="[Remove]") {
  grid.EndEdit();
  grid.Rows.RemoveAt(grid.CurrentRow.Index);
}

Rather than delete the row, this throws an exception:

Operation is not valid because it results in a reentrant call to the SetCurrentCellAddressCore function.

I've tried moving the CurrentRow to a different co开发者_如何学Clumn before I delete, like this:

DataGridViewRow deleteRow = grid.CurrentRow;
grid.CurrentRow.Selected = false;
grid.Rows[deleteRow+1].Selected = true;
grid.Rows.RemoveAt(deleteRow);

Same problem. The grid's AllowUserToDeleteRows attribute is true. I'm not binding data to this control.

I believe the problem lies in my tying to the CellEndEdit event, as if I delete the row from a button control's OnClick event, I'm okay.

Could I programatically trigger the button's OnClick event? How?


It looks like you are already in the OnCellEndEdit call, so I dont think you need to call grid.EndEdit() again. Try removing that call and see if the row gets removed. I believe that error is caused because you could end up in an infinite loop.


use 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 work with any cell being edited.(the edit-code is not applied when losing focus; Typing Enter would suffice to apply the edit)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜