2017-02-13 154 views
0

我有幾個不同的字典結構,我想要顯示在組合框中。基於鍵的字典顯示成員(comboBox)

在JumpType.cs:

public SortedDictionary<int, List<string>> jumpCombination = new SortedDictionary<int, List<string>>(); 

字典結構將是這個樣子:

Key Values 
1  Flygande 
     EjFlygande 
2  Bak 
     Pik 
     Test 
3  ... 

我已經創建了兩個組合框在我的UI是這樣的:

Select Key:  _____________ 
       | ComboBox | 
       --------------  __________ 
       _____________  | OK | 
Select Value: | ComboBox |  ---------- 
       -------------- 

在Form1.cs中

InitializeComponent(); 
JumpType jt = new JumpType(); 
jt.addjumpCombination(); // populating the dictionary 
if (jt.jumpCombination != null) 
{ 
      comboBoxJumpComboKey.DataSource = new BindingSource(jt.jumpCombination, null); // Key => null 
      comboBoxJumpComboKey.DisplayMember = "Value"; 
      comboBoxJumpComboKey.ValueMember = "Key"; 
      comboBoxJumpComboValue.DisplayMember = "Value"; 
      var selectedValues = jt.jumpCombination //here i'm trying to access value 
        .Where(j => j.Key == Convert.ToInt32(comboJumpComboKey.SelectedItem.Value)) 
        .Select(a => a.Value) 
        .ToList(); 
} 

我該如何去根據選定的鍵選擇相應的值?

在此先感謝。 正如您在圖像中看到的那樣,鍵將顯示(1),但我無法從其下面的組合框中選擇任何內容。 comboBox

+0

你想要做的是改變第二組合框時的名單是什麼第一個的索引被改變。因此,您可以爲'comboBoxJumpComboKey​​'索引更改事件添加事件處理程序。在那種情況下,你改變'comboBoxJumpComboValue'的'DataSource'' – Everyone

+0

@Everyone耶正好。我真的不知道該怎麼去做。你介意在這裏給我一個幫助嗎? – Joel

+0

您正在使用WPF或WinForms? – Everyone

回答

2

我會初始化Dictionary作爲UI類本身的一部分。

public SortedDictionary<int, List<string>> jumpCombination; 
    public Form1() { 
     InitializeComponent(); 
     jumpCombination = new SortedDictionary<int, List<string>>(); 
     // do whatever needed to populate the dictionary here 
     // now add the DataSource as the Keys of your dictionary which are integers 
     comboBoxJumpComboKey.DataSource = new BindingSource(jumpCombination.Keys, null); 
    } 

然後,在你的UI設計上的comboBoxJumpComboKey雙擊,一種新的方法會來,用這種填充:

private void comboBoxJumpComboKey_SelectedIndexChanged(object sender, EventArgs e) { 
     comboBoxJumpComboValue.DataSource = jumpCombination[int.Parse(comboBoxJumpComboKey.Items[comboBoxJumpComboKey.SelectedIndex].ToString())]; 
    } 
+0

我得到「invalidArgument = -1的值不適用於'索引' – Joel

+0

您的詞典是否已填充?它是否具有負數作爲鍵?如果你可以使用'comboBoxJumpComboValue.DataSource = jumpCombination [comboBoxJumpComboKey​​.SelectedIndex];' – Everyone

+0

是的,我在初始化函數後調用它,它現在已經獲得了密鑰,但是從這個鍵值中我想要以便能夠選擇關鍵字包含的值(在列表中) – Joel