不能获得价值从组合框 [英] Can't get Value from ComboBox

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

问题描述

我有一个简单的组合框,在它的一些数值/文字的项目。我已经使用ComboBox.DisplayMember和ComboBox.ValueMember正确设定值/文本。当我尝试获取该值,则返回一个空字符串。这是我的code:

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组合框的事件:

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.

该项目属性是System.Object的集合。这使得组合框存储和显示任何类型的类的对象。但是,你必须从对象转换到您的类类型使用选定的对象在code。不能在您的情况下工作,你增加了一个匿名类型的对象。你需要声明一个小助手类存储的值和文本属性。一些示例code:

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; }
    }
  }

这篇关于不能获得价值从组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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