如何使用组合框中的键值查找显示值



我有一个组合框,它有一个字典作为数据源。我正在尝试在组合框中查找一个键并获取它的显示值。FindString查找显示值。

var dictionary = new Dictionary<string, string>();
dictionary.Add("key1", "value1");
dictionary.Add("key2", "value2");
dictionary.Add("key3", "value3");
comboBox1.DataSource = new BindingSource(dictionary, null);
comboBox1.ValueMember = "Key";
comboBox1.DisplayMember = "Value";
comboBox1.FindString("key3") //returns -1
comboBox1.FindString("value3") //returns 2

但是我想查找key3的显示值。我该怎么做?

如果要查找当前所选项目和值:
comboBox1.SelectedValue与文本

如果你想通过原始源进行枚举,通常你只需要枚举原始源:

dictionary["key3"];

如果你因为某种原因无法访问它,只需从comboBox:中取回它

var originalDictionary = ((Dictionary<string,string>)((BindingSource)comboBox1.DataSource).DataSource);
var randomValue = originalDictionary["key3"];

最新更新