2009-12-05 68 views
2

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

FormLoad事件:

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

SelectIndexChanged组合框的事件:

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

,并返回一个空的对话框。我也试过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?) 

alt text

我在做什么错?

回答

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

这是我更喜欢的方法。感谢您的帮助,它的工作。 – ademers 2009-12-05 03:20:44

2

正如您在调试器中看到的,SelectedItem包含您所需的信息。但是要访问SelectedItem.Value,则需要将SelectedItem转换为适当的类型(如果使用的是匿名类型,则会出现问题)或使用反射。 (VS不能编译SelectedItem.Value因为编译时间VS只知道是的SelectedItem Object类型,它不具有价值属性。)

使用反射来获取值成员之一,采用类型。使用BindingFlags.GetProperty调用成员。

要转换SelectedItem,使用Value和Text属性声明一个具有名称的类型,而不是使用匿名类型,并将指定类型的实例添加到ComboBox中,而不是匿名类型的实例。然后转换SelectedItem :((MyType)(cb.SelectedItem))。Value。

1

不知道为什么SelectedValue不返回任何东西......我认为这可能是由于您没有使用数据绑定(DataSource)。您应该尝试将卡的列表分配给DataSource属性。

关于SelectedItem的问题:ComboBox.SelectedItem的类型为Object,它没有名为Value的属性。您需要将其转换为该项目的类型;但由于它是一个匿名类型,你不能......你应该创建一个类来保存的价值和卡的文字,并投这种类型:

Card card = ComboBox.SelectedItem as Card; 
if (card != null) 
{ 
    // do something with card.Value 
} 
1

要修改的内容SelectedIndexChanged处理程序中的组合框。当您修改内容时,它会导致选定的项目未设置。设置您正在读取null,它显示在消息框中作为空字符串。

0

我很好奇你是否将组合框绑定到集合,或手动填充它。如果您将组合框绑定到某种数据源......您应该将项目添加到数据源,而不是组合框本身。当一个项目被添加到数据源时,组合框应该更新。

如果你没有绑定,那么添加一个项目不会导致该项目被选中。您需要等待用户选择项目,或者以编程方式选择代码中的项目。

0

为了避免创建一个新的类所有的组合框,我建议你刚才在下面的例子中使用KeyValuePair,如:

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

cbPlayer1.DataSource = new List<KeyValuePair<string,string>>() 
{new KeyValuePair<string,string>("3","This should have the value of 3")}; 

你仍然需要转换所选值

string selectedValue = (string)cbPlayer1.SelectedValue; 

MessageBox.Show(selectedValue);