0

I have a winform DataGridView binded to a typed BindingSource, itself binded to a DTO whose fields are read/write strings.

In my controller, I do View.ItemDtoBindingSource.DataSource = FoundResults where FoundResults is a List<ItemDto>, and the data grid displays the expected values.

I want to allow the user to make changes and expect that the BindingSource will update as the user changes cell values. Then an Update button will fetch the contents of View.ItemDtoBindingSource and make the desired changes in the back end.

I am not sure if I misunderstand the subtleties of data binding, but when I click on a cell on the data grid I am able to edit the value, but if I click away or press enter, the cursor leaves the cell and the value returns back to what it was before I tried to edit it (a behaviour expected if for example I had pressed Escape). Any reasons for this to happen?

I read that ReadOnly collections as a binding source may prevent from editing the datagrid, so I made sure I passed an IList<T> instead of an IEnumerable<T>, but this did not resolve the problem. I have also seen this and made sure VirtualMode = False.

Ama
  • 1,373
  • 10
  • 24
  • If you are using a `BindingSource` as a `DataSource` to the grid… then what construct are you using as a `DataSource` to the `BindingSource`? What is a `View`? How is the `ItemDto` object defined? – JohnG Jun 13 '22 at 21:04
  • The BindingSource uses a List . View is a winform which contains the DataGridView and the ItemDtoBindingSource. ItemDto is a POCO with 3 properties. – Ama Jun 13 '22 at 21:46
  • Post your `ItemDto` and whatever returns `FoundResults`. – Jimi Jun 13 '22 at 22:23
  • I believe I have found the problem: `ItemDto` is a structure. Turning it into a class seems to work. I will run final tests and post an answer. – Ama Jun 13 '22 at 22:28
  • There's not much to test. Turn the struct into a class; use Properties, not Fields. – Jimi Jun 13 '22 at 22:51

1 Answers1

0

When one of the rows in a DataGridView changes, the control updates the BindingSource by updating the item provided by the DataSource. The control updates the property of the existing item, it does not replace the existing item (to update) by a new one (updated).

Hence it is necessary to use classes instead of structure types as the generic type of the collection backing the DataSource. If not, then the control gets a copy (instead of a reference) of the item to update, updates the copy, then fetches the DataSource again but since it has not changed (only the copy has changed) the change is not reflected and is lost.

Ama
  • 1,373
  • 10
  • 24