2017-02-13 153 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