Setup
- C# WinForms Application.
Summary
- Binding a dictionary to a datagridview.
- Updating the dictionary automatically updates the datagrid.
- The datagrid does not lose focus when the update happens.
- The binding works both ways (editing values in the grid updates the dictionary.
Scenario
- I have a class that calculates values
based on data from a database. - The data in this database constantly changes so hence, the calculated values change too.
- These calculated values are added to the properties of a custom object "MyCustomObject".
- Each "MyCustomObject" is then added to a dictionary (or the custom object is updated if it already exists).
- The Dictionary is bound to a datagrid.
The idea
- The idea is that the calculated vales continually change and thus update the dictionary which in turn updates the datagrid.
- Users who are interacting with the datagrid need to be able to see these changes automatically.
- It is imperative that the currently selected row in the datagrid does not lose focus when the grid is updated with the new custom object values.
- The binding must work both ways (editing values in the grid updates the dictionary too.
Question
- How can I implement this automatic binding so that I get the requirements that I need?
- I have already written the code to do all of the calculations and add/update the dictionary of MyCustomObjects.
- Examples of how to implement this datagrid binding would be greatly appreciated.
In order to accomplish this, your Dictionary would need to implement
IBindingListand fire theListChangedevent whenever changes were made. Here’s a sample (very) barebones implementation ofIDictionary<TKey, TValue>that also implementsIBindingList:Unfortunately, the selected row may or may not change, depending on which grid you’re using. Your best bet is to save off the key of the selected row whenever it changes, then reselect that row (if present) when the dictionary is updated. Otherwise, there’s no way to guarantee that you’ll maintain the selection.