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属性。]