【问题标题】:How to extract embedded Value from comboBox?如何从组合框中提取嵌入的值?
【发布时间】:2012-09-17 23:11:43
【问题描述】:

我以这种方式使用基础值和显示值填充我的组合框:

Dictionary<int, string> Platypi = duckBillData.GetPlatypiVals();
comboBoxPlatypus.DataSource = new 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...

【问题讨论】:

    标签: c# winforms dictionary combobox key-value-observing


    【解决方案1】:

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

    int id = (int) comboBox.SelectedItem;
    

    【讨论】:

    • 其实就是这样: int callFlowID = (int)comboBoxCallFlow.SelectedItem;我得到,“System.InvalidCastException 未处理 Message=Specified cast is not valid.”
    • 您的字典中的键(或任何您指定为 ValueMember 的键)仍然是 int 吗?
    • 这也失败了:int callFlowID = Convert.ToInt32(comboBoxCallFlow.ValueMember); ... ValueMember 的值是“Key” ...???
    • 对,所以 ValueMember 是一个 string,它告诉 winforms 在构造组合框时将集合的哪个属性用作值。它只指定包含值的属性,而不是值本身,也不是intSelectedItem 绝对是您想要的,但您需要确保它具有正确的类型。
    • 看起来您的 SelectedItem 是一个字典 KeyValuePair。尝试检查其类型,将其转换为正确的类型,然后提取您需要的值,例如 ((KeyValuePair) comboBox.SelectedItem).Key [注意转换对象周围的括号以获取 Key 属性。]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多