2009-12-05 57 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);