2014-01-29 32 views
0

我試圖用TEXT和價值組合框添加一個對象項目,以便我能讀它之後C#組合框,保存項目以價值和文本

public partial class Form1 : Form 
{ 
    ComboboxItem item; 
    public Form1() 
    { 
     InitializeComponent(); 

     comboBox1.Items.Add(new ComboboxItem("Dormir", 12).Text); 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     ComboboxItem c = (ComboboxItem)comboBox1.SelectedItem; 
     label1.Text = c.Text; 
     label2.Text = c.Value.ToString(); 
    } 
} 

的問題是,我不能添加完整項目因爲不是字符串...並在click事件的開始給出一個例外


額外信息: 這ComboboxItem,它說我有兩個參數,字符串創建一個類,和int

public class ComboboxItem 
{ 
    public string Text { get; set; } 
    public object Value { get; set; } 

    public ComboboxItem(string texto, double valor) 
    { 
     this.Text = texto; 
     this.Value = valor; 
    } 
} 

回答

0

您可以(應該)將displaymember和valuemember設置在另一個地方,但是...

public Form1() 
    { 
     InitializeComponent(); 
     comboBox1.DisplayMember="Text"; 
     comboBox1.ValueMember ="Value"; 
     comboBox1.Items.Add(new ComboboxItem("Dormir", 12)); 
    } 
+0

謝謝!,這就是我真正想要的!,也許我的英語不是很好..我想添加一個項目,但顯示文本;) – user3249619

0

你不需要在(「文本」,「值」)的末尾添加。文本

所以將其添加爲:

comboBox1.Items.Add(new ComboBoxItem("dormir","12")); 
+0

價值不來的文本之前,在這裏:它ComboBoxItem的只是構造函數。 –

+0

就像那樣,在我的組合框上將會出現「WindowsFormsApplication1.ComboboxItem」而不是「文本」。 – user3249619

+0

我不好,看看編輯。文本之前 – user1063280

0

你在正確的線路通過創建自己的ComboBoxItem類。

public class ComboboxItem 
{ 
    public string Text { get; set; } 
    public object Value { get; set; } 

} 

有兩種方法來使用這個,(構造函數除外): 方法1:

private void button1_Click(object sender, EventArgs e) 
{ 
    ComboboxItem item = new ComboboxItem(); 
    item.Text = "Item text1"; 
    item.Value = 12; 

    comboBox1.Items.Add(item); 
} 

方法2:

private void button1_Click(object sender, EventArgs e) 
{ 
    ComboboxItem item = new ComboboxItem 
    { 
     Text = "Item text1", 
     Value = 12 
    }; 

    comboBox1.Items.Add(item); 
} 

你有沒有嘗試添加它像這樣呢?然後,當你曾經獲得該項目從只投它作爲一個ComboboxItem :)

... 
var selectedItem = comboBox1.SelectedItem as ComboboxItem; 
var myValue = selectedItem.Value; 
... 

替代KeyValuePair:基於returnign字符串值和其他組合框的答案

comboBox1.Items.Add(new KeyValuePair("Item1", "Item1 Value")); 

問題.. ComboBox: Adding Text and Value to an Item (no Binding Source)

+0

如果我做「comboBox1.Items.Add(item);」,在我的組合框它不會顯示「項目text1」,而是顯示「」WindowsFormsApplication1.ComboboxItem「 – user3249619

+0

你可以隨時傳遞一個KeyValuePair? – JonE

0

創建ComboboxItem類並重寫ToString方法。 ToString方法將被調用以可視化該項目。默認情況下,ToString()返回類型名稱。

public class ComboboxItem 
{ 
    public object Value{get;set;} 
    public string Text {get;set;} 

    public override string ToString(){ return Text; } 
} 

然後,你可以這樣做:

var item = new CombobxItem { Value = 123, Text = "Some text" }; 
combobox1.Items.Add(item); 
+0

可以剛剛鏈接你的答案在這裏? http://stackoverflow.com/questions/3063320/組合框-添加文本 - 值對的項目 - 無結合源 – JonE