Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何从comboBox中提取嵌入值?_C#_Winforms_Dictionary_Combobox_Key Value Observing - Fatal编程技术网

C# 如何从comboBox中提取嵌入值?

C# 如何从comboBox中提取嵌入值?,c#,winforms,dictionary,combobox,key-value-observing,C#,Winforms,Dictionary,Combobox,Key Value Observing,我用一个基础值和一个显示值填充组合框,如下所示: Dictionary<int, string> Platypi = duckBillData.GetPlatypiVals(); comboBoxPlatypus.DataSource = new BindingSource(Platypi, null); comboBoxPlatypus.ValueMember = "Key"; comboBoxPlatypus.DisplayMember = "Value"; Dictionar

我用一个基础值和一个显示值填充组合框,如下所示:

Dictionary<int, string> Platypi = duckBillData.GetPlatypiVals();
comboBoxPlatypus.DataSource = new BindingSource(Platypi, null);
comboBoxPlatypus.ValueMember = "Key";
comboBoxPlatypus.DisplayMember = "Value";
Dictionary Platypi=duckBillData.getplatyvals();
comboBoxPlatypus.DataSource=新的BindingSource(Platypi,null);
comboBoxPlatypus.ValueMember=“Key”;
comboBoxPlatypus.DisplayMember=“Value”;
现在我想提取所选项目的ValueMember。我该怎么做?所有“明显”的事情似乎都没有“ValueMember”…我试过:

int id = comboBoxPlatypus.ValueMember;
int id = comboBoxPlatypus.SelectedIndex. <-- no "ValueMember" here...
int id = comboBoxPlatypus.SelectedItem. <-- no "ValueMember" here...
int id=comboBoxPlatypus.ValueMember;

int id=comboBoxPlatypus.SelectedIndex
ValueMember
告诉组合框要绑定到原始集合的哪个属性,它不是绑定对象本身
SelectedItem
应包含结果值。您只需要将其转换为正确的类型,在本例中,这是您的
int

int id = (int) comboBox.SelectedItem;

实际上,使用以下命令:int callFlowID=(int)comboBoxCallFlow.SelectedItem;我得到,“System.InvalidCastException was unhandled Message=指定的强制转换无效。”字典上的键(或指定为ValueMember的任何键)仍然是int吗?这也会失败:int callFlowID=Convert.ToInt32(comboBoxCallFlow.ValueMember)。。。ValueMember的值是“Key”…???对,因此ValueMember是一个
字符串
,它告诉winforms在构造组合框时要将集合的哪个属性用作值。它只指定包含值的属性,而不是值本身,并且不是
int
SelectedItem
绝对是您想要的,但是您需要确保它的类型正确。看起来您的SelectedItem是一个字典键值对。尝试检查其类型,将其强制转换为正确的类型,然后提取所需的值,例如,
((KeyValuePair)comboBox.SelectedItem).Key
[请注意强制转换对象周围的括号以获取Key属性。]