6

I have a dictionary item as below

Dictionary<string, List<StrikePrice>>

where

public class StrikePrice
{
    public string Strike { get; private set; }
    public string Price { get; private set; }

    public StrikePrice(string strike, string price)
    {
        Strike = strike;
        Price = price;
    }
}

and I wish to assign this dictionary to the DataGridView

this.dataGridViewTest.DataSource = listSmiles;

I understand that a dictionary can't be assigned to the the DataSource as this doesn't derive from the IList interface.

Is there any way I can assign this dictionary element to the datagrid?

Gustavo Mori
  • 8,319
  • 3
  • 38
  • 52
tush1r
  • 19,443
  • 14
  • 36
  • 35

4 Answers4

3

I know this is a bit old, but perhaps it will help someone. This one line solution worked for me

gridTAV.DataSource = dTAV.Values.ToList<TotalAccountValue>();

gridTAV is a DataGridView. dTAV is a Dictionary. The key is a date (not important), and the value is a class.

Dictionary<DateTime, TotalAccountValue> dTAV = new Dictionary<DateTime, TotalAccountValue>();

Since the value was a class the "ToArray()" method did not work for me, since it didn't "unpack" the class properties.

Note that this does not place the KEY in the grid, but I didn't really need that.

pStan
  • 1,084
  • 3
  • 14
  • 36
  • Also, to enable sorting, etc. you can convert the list to a Datatable and bind that instead. Look here http://stackoverflow.com/questions/564366/convert-generic-list-enumerable-to-datatable for the code. – pStan Sep 27 '12 at 15:12
2

Have you tried using the Values property of the Dictionary?

this.dataGridViewTest.DataSource = listSmiles.Values.ToList();
Community
  • 1
  • 1
Kane
  • 16,471
  • 11
  • 61
  • 86
2

Yes ,by Calling ToArray of Dictionary

        var g = this.dataGridView1;
        var s = new Dictionary<string, string>();
        s.Add("1", "Test1");
        s.Add("2", "Test2");
        s.Add("3", "Test3");
        g.DataSource = s.ToArray();
DeveloperX
  • 4,633
  • 17
  • 22
-1

If the question relates to WPF or silverlight, this article gives a solution.

I've been using it and it performs well, even for large numbers of columns.

Phillip Ngan
  • 15,482
  • 8
  • 63
  • 79