无法从ComboBox获取值 [英] Can't get Value from ComboBox

查看:322
本文介绍了无法从ComboBox获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的组合框与一些值/文本项目。我使用ComboBox.DisplayMember和ComboBox.ValueMember正确设置值/文本。当我尝试获取该值时,它返回一个空字符串。这是我的代码:

I have a simple comboBox with some Value/Text items in it. I have using ComboBox.DisplayMember and ComboBox.ValueMember to correctly set the value/text. When I try to get the value, it returns an empty string. Here's my code:

FormLoad事件:

FormLoad event:

cbPlayer1.ValueMember = "Value";
cbPlayer1.DisplayMember = "Text";

SelectIndexChanged ComboBox事件:

SelectIndexChanged of ComboBox event:

cbPlayer1.Items.Add(new { Value = "3", Text = "This should have a value of 3" });
MessageBox.Show(cbPlayer1.SelectedValue+"");

并返回一个空对话框。我也试过ComboBox.SelectedItem.Value(VS看到,见图片),但它不编译:

And it returns an empty dialog box. I also tried ComboBox.SelectedItem.Value (which VS sees, see picture) but it does not compile:

'object' does not contain a definition for 'Value' and no extension method 'Value' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

我做错了什么?

推荐答案

不确定ComboBox.SelectedValue是什么意思,有一个SelectedItem属性。只有当用户进行选择时,才会设置此选项。

Not sure what ComboBox.SelectedValue means, it has a SelectedItem property. That would not be set when you add an item, only when the user makes a selection.

Items属性是System.Object的集合。这允许组合框存储和显示任何类型的对象。但是你必须将它从对象转换为类类型,以便在代码中使用所选对象。这不能在你的情况下工作,你添加了一个匿名类型的对象。您需要声明一个小助手类来存储值和文本属性。一些示例代码:

The Items property is a collection of System.Object. That allows a combo box to store and display any kind of class object. But you'll have to cast it from object to your class type to use the selected object in your code. That can't work in your case, you added an object of an anonymous type. You'll need to declare a small helper class to store the Value and Text properties. Some sample code:

  public partial class Form1 : Form {
    public Form1() {
      InitializeComponent();
      comboBox1.Items.Add(new Item(1, "one"));
      comboBox1.Items.Add(new Item(2, "two"));
      comboBox1.SelectedIndexChanged += new EventHandler(comboBox1_SelectedIndexChanged);
    }
    void comboBox1_SelectedIndexChanged(object sender, EventArgs e) {
      Item item = comboBox1.Items[comboBox1.SelectedIndex] as Item;
      MessageBox.Show(item.Value.ToString());
    }
    private class Item {
      public Item(int value, string text) { Value = value; Text = text; }
      public int Value { get; set; }
      public string Text { get; set; }
      public override string ToString() { return Text; }
    }
  }

这篇关于无法从ComboBox获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆