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

查看:59
本文介绍了无法从 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";

ComboBox 事件的 SelectIndexChanged:

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 的集合.这允许组合框存储和显示任何类型的类对象.但是您必须将它从 object 转换为您的类类型才能在您的代码中使用选定的对象.这在您的情况下不起作用,您添加了一个匿名类型的对象.您需要声明一个小的帮助器类来存储 Value 和 Text 属性.一些示例代码:

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天全站免登陆