DataGridView bound to a Dictionary

WillH picture WillH · May 12, 2009 · Viewed 76k times · Source

I have a Dictionary that contains items and prices. The items are unique but slowly get added and updated through the lifetime of the application (that is, I don't know the item strings in advance). I would like to bind this structure to a DataGridView, so I can show updates on my Form, something like:

Dictionary<string, double> _priceData = new Dictionary<string, double>();
BindingSource _bindingSource = new BindingSource();
dataGridView1.DataSource = _bindingSource;
_bindingSource.DataSource = _priceData;

But cannot, since Dictionary does not implement IList (or IListSource, IBindingList, or IBindingListView).

Is there a way to achieve this? I need to keep a unique list of items, but also update the price for an existing item, so a Dictionary is the ideal data structure I think, but I cannot find a way to display the data on my Form.


Update:

Marc's suggestion below works very nicely, but I'm still not sure how to update the DataGridView during execution.

I have a class-level variable:

private DictionaryBindingList<string, decimal> bList; 

Then instantiate that in Main():

bList = new DictionaryBindingList<string,decimal>(prices); 
dgv.DataSource = bList; 

Then during program execution if a new entry is added to the dictionary:

prices.Add("foobar", 234.56M); bList.ResetBindings(); 

I thought that would refresh the DataGridView. Why not?

Answer

Chris picture Chris · May 13, 2009

Or, in LINQ, it's nice and quick:

var _priceDataArray = from row in _priceData select new { Item = row.Key, Price = row.Value };

That should then be bindable, to the columns 'Item' and 'Price'.

To use it as a data source in a grid view, you just have to follow it with ToArray().

dataGridView1.DataSource = _priceDataArray.ToArray();