从ComboBox获取价值

时间:2015-07-18 17:29:48

标签: c#

这是我的代码

string key = ((KeyValuePair<string, string>)ComboBox1.SelectedItem).Key;
string value = ((KeyValuePair<string, string>)ComboBox1.SelectedItem).Value;

例外:指定的演员表无效。

1 个答案:

答案 0 :(得分:1)

绑定到组合框:

var dict = new Dictionary<string, string>();

for(int i=1; i<=10; i++)
{
    dict.Add((i).ToString(), String.Format("Item {0}", i));
}
ComboBox.DataSource = new BindingSource(dict, null);
ComboBox.ValueMember = "Key";
ComboBox.DisplayMember = "Value";

获取价值

KeyValuePair<string, string> kvp = (KeyValuePair<string, string>)ComboBox.SelectedItem;

foreach(KeyValuePair k in kvp)
{
    Console.WriteLine("Key: {0}, Value: {1}", k.Key, k.Value);
}