无法从ComboBox获取价值

ade*_*ers 2 .net c# combobox

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

FormLoad事件:

cbPlayer1.ValueMember = "Value";
cbPlayer1.DisplayMember = "Text";
Run Code Online (Sandbox Code Playgroud)

ComboBox事件的SelectIndexChanged:

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

然后它返回一个空的对话框.我也尝试过ComboBox.SelectedItem.Value(VS看到,见图),但它没有编译:

'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?)
Run Code Online (Sandbox Code Playgroud)

替代文字

我究竟做错了什么?

Han*_*ant 6

不确定ComboBox.SelectedValue是什么意思,它有一个SelectedItem属性.仅当用户进行选择时,才会在添加项目时设置该项目.

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

  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; }
    }
  }
Run Code Online (Sandbox Code Playgroud)