DataGridView throwing “InvalidOperationException: Operation is not valid…” when adding a row

前端 未结 5 1623
失恋的感觉
失恋的感觉 2021-02-07 05:00

I want an OpenFileDialog to come up when a user clicks on a cell, then display the result in the cell.

It all works, except that the DataGridView displays an extra row,

5条回答
  •  梦谈多话
    2021-02-07 05:41

    This is old, but I am running VS2010 and just come across this issue. I have a DataGridView bound to a List using a BindingList. I have a drag n' drop event on my DataGridView and it would throw this exception after deleting all rows from the DGV (except for the last blank one which one cannot delete) and then adding new rows to the DGV in the DragDrop handler via the BindingList. This exception was not thrown if I simply added rows manually editing individual cells.

    One solution I read said to handle the BindingList.AddNew event, but I found that this event did not fire when calling BindingList.Add() within the DragDrop event handler (I'm not sure why). I solved the issue by adding

    if(bindingList.Count == 0)
        bindingList.RemoveAt(0)
    

    inside of the DragDrop event handler before adding new objects to bindingList. It seemed that adding an object to the bindingList failed when the only "object" in the bindingList was the one associated to the final blank row. The point of a BindingList is to allow the developer to work with it instead of the DGV directly, but it seems doing so can cause problems in border cases.

    The relationship between DGV rows and BindingList rows seems to be a bit of a gray area. I have not spent much time investigating this, but it is not clear to me what is the state of the "object" in the BindingList associated to the final (empty) row of the DGV. However, it does seem like the "object" at the end is only instantiated "correctly" when you interact with the final row directly (not via a DataSource).

提交回复
热议问题