2013-03-11 65 views
0

我想知道我可以添加到以下價格:如何將價格添加到我在C#中的組合框項目?

private void OrderForm_Load(object sender, EventArgs e) 
{ 
    comboBox1.Items.Add("0"); 
    comboBox1.Items.Add("10"); 
    comboBox1.Items.Add("20"); 
    comboBox1.Items.Add("30"); 
    comboBox1.Items.Add("40"); 
    comboBox1.Items.Add("50"); 
    comboBox1.Items.Add("60"); 
    comboBox1.Items.Add("70"); 
    comboBox1.Items.Add("80"); 
    comboBox1.Items.Add("90"); 
    comboBox1.Items.Add("100"); 
    comboBox2.Items.Add("None"); 
    comboBox2.Items.Add("Chocolate"); 
    comboBox2.Items.Add("Vanilla"); 
    comboBox2.Items.Add("Strawberry"); 
    comboBox3.Items.Add("Paypal"); 
    comboBox3.Items.Add("Visa Electron"); 
    comboBox3.Items.Add("MasterCard"); 
    comboBox4.Items.Add("None"); 
    comboBox4.Items.Add("Small"); 
    comboBox4.Items.Add("Medium"); 
    comboBox4.Items.Add("Large"); 
} 

的號碼價格從「0 - 100」應爲「£15」每一個?

+1

我真的不明白你想要達到什麼樣的效果 – VladL 2013-03-11 23:12:15

+0

這聽起來像你想要的東西:10 Vanilla @ 15美元收費簽證?訂單? – 2013-03-11 23:15:03

+0

我只想知道我是否可以在物品跌落時向物品添加價格。例如,如果我要在組合框中選擇「10」,那麼總共應該出現「15英鎊」... – user2158786 2013-03-11 23:15:58

回答

4

該組合框顯示ToString方法的結果作爲該項目的名稱。這意味着您可以創建包含名稱和價格的自己的對象,並覆蓋ToString以僅顯示名稱。例如:

public class MyItem 
{ 
    private readonly string name; 
    public string Name 
    { 
     get { return this.name; } 
    } 

    private readonly decimal price; 
    public decimal Price 
    { 
     get { return this.price; } 
    } 

    public MyItem(string name, decimal price) 
    { 
     this.name = name; 
     this.price = price; 
    } 

    public override string ToString() 
    { 
     return this.name; 
    } 
} 

然後創建並添加您自己的對象。

comboBox2.Items.Add(new MyItem("Chocolate", 10.00m)); 
comboBox2.Items.Add(new MyItem("Vanilla", 15.00m)); 
comboBox2.Items.Add(new MyItem("Strawberry", 8.50m)); 

每當你從ComboBox(例如當前選擇的項目)獲得一個項目,該Price屬性將告訴你價格。例如:

MyItem selectedItem = (MyItem)comboBox2.SelectedItem; 
decimal totalPrice = selectedItem.Price + 1.00m /* Shipping */; 
+0

你的ToString覆蓋不包括價格,我會做'返回string.Format(「{0} - {1}」,this.name,this.price);'。但除此之外,這是確切的我該怎麼做。 – 2013-03-11 23:45:03

+0

@TheGreatCO OP評論「_如果我要在組合框中選擇」10「,那麼」總共15英鎊「應該出現在.. ..」所以他不想在組合框中的價格。但我同意,如果OP想要字符串中的價格,他應該在'ToString'中使用您的解決方案。 – Virtlink 2013-03-11 23:55:24

+0

我誤解了他所問的,我的不好。 – 2013-03-12 04:01:29

0

直接回答你的問題,你可以使用ComboBox.SelectedIndex值,像這樣:

if (comboBox4.SelectedIndex < 100) { 
    price = 15; 
} 

不會提出,在我的代碼雖然。以這種方式編寫代碼尖叫「維護地獄」,所以請重新構建您的代碼。我打算按Martin的解決方案提出一個建議,使用面向對象來存儲名稱/價格,所以我建議給出一個解決方案。

相關問題