2009-11-02 118 views
5

我有一本字典項,如下將字典綁定到C#中的DataGridView?

Dictionary<string, List<StrikePrice>> 

其中

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; 
    } 
} 

,我想轉讓本字典給DataGridView

this.dataGridViewTest.DataSource = listSmiles; 

我明白,一個字典不能分配給DataSource,因爲這不是來自IList接口。

有什麼辦法可以將這個字典元素分配給數據網格嗎?

+0

WPF或WinForms? – 2009-11-02 04:53:38

+0

@Cameron: WinForms – tush1r 2009-11-02 07:04:13

回答

3

的ToArray的,我知道這是一個有點老,但也許它會幫助別人。這一行解決方案爲我工作

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

gridTAV是一個DataGridView。 dTAV是一個詞典。關鍵是一個日期(不重要),並且該值是一個類。

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

因爲該值是一類「ToArray的()」方法並沒有爲我工作,因爲它沒有「解包」之類的屬性。

請注意,這並不把KEY放在網格中,但我並不真的需要這樣做。

+0

此外,要啓用排序等,您可以將列表轉換爲Datatable並將其綁定。看看這裏http://stackoverflow.com/questions/564366/convert-generic-list-enumerable-to-datatable的代碼。 – pStan 2012-09-27 15:12:51

-1

如果問題涉及到WPF或silverlight,這個article給出了一個解決方案。

我一直在使用它,即使對於大量的列,它也表現良好。

+0

@Phillip: 這是Winforms應用程序。 – tush1r 2009-11-02 05:18:17

2

您是否嘗試過使用字典的Values屬性?

this.dataGridViewTest.DataSource = listSmiles.Values.ToList(); 
+0

@Kane: 我試過這樣做,但是這不起作用。 – tush1r 2009-11-02 05:19:00

2

是,通過調用詞典

 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();