2012-02-29 81 views
0

我有一個窗體有兩個按鈕,文本框,列表框和一個組合框。我遇到的問題是當我試圖總按鈕。我無法弄清楚如何從這個列表中獲取成本值,所以我可以總計訂單的總成本。感謝您的建議。C#windows窗體列表框總計

private void Order_Click(object sender, EventArgs e) 
    { 
     amount = int.Parse(textBox1.Text); 
     cost *= amount; 

     if (comboBox1.SelectedItem.ToString() == "Eggs") 
     { 
      listBox1.Items.Add("The cost for " + amount + " 
      dozen large, fresh eggs is: " + (cost).ToString("C")); 
      comboBox1.Text = ""; 
      textBox1.Text = "0"; 
      textBox1.Focus(); 
      comboBox1.Focus(); 
     } 
     else if (comboBox1.SelectedItem.ToString() == "Milk") 
     { 
      if (amount == 1) 
      { 
       listBox1.Items.Add 
       ("The Cost for a fresh quart milk is: " + (cost).ToString("C")); 
       comboBox1.Text = ""; 
       comboBox1.Focus(); 
       textBox1.Text = "0"; 
       textBox1.Focus(); 
      } 
      else 
      { 
       listBox1.Items.Add 
      ("The Cost for " + amount + " quarts of fresh milk is: " + 
       (cost).ToString("C")); 
       comboBox1.Text = ""; 
       comboBox1.Focus(); 
       textBox1.Text = "0"; 
       textBox1.Focus(); 
      } 
     } 
     else 
     { 
      listBox1.Items.Add 
      ("The Cost for " + amount + " fresh loafs of bread is: " + (cost).ToString("C")); 
      comboBox1.Text = ""; 
      comboBox1.Focus(); 
      textBox1.Text = "0"; 
      textBox1.Focus(); 
     } 
    } 

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) 
    { 
     if (comboBox1.SelectedItem.ToString() == "Eggs") 
     { 
      cost = 1.90; 
      label1.Text = "The Cost is " + (cost).ToString("C") + " per dozen"; 
     } 
     else if (comboBox1.SelectedItem.ToString() == "Milk") 
     { 
      cost = 1.47; 
      label1.Text = "The Cost is " + (cost).ToString("C") + " per quart"; 
     } 
     else 
     { 
      cost = 2.12; 
      label1.Text = "The Cost is " + (cost).ToString("C") + " per loaf"; 
     } 
    } 

    private void total_Click(object sender, EventArgs e) 
    { 


    } 

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e) 
    { 
     if (!char.IsControl(e.KeyChar) 
      && !char.IsDigit(e.KeyChar) 
      && e.KeyChar != '.') 
     { 
      e.Handled = true; 
     } 

     if (e.KeyChar == '.' 
    && (sender as TextBox).Text.IndexOf('.') > -2) 
     { 
      e.Handled = true; 
     } 
     if (e.KeyChar == '-' 
&& (sender as TextBox).Text.IndexOf('-') > -2) 
     { 
      e.Handled = true; 
     } 
    } 
} 

}

回答

1

爲什麼不使用總類字段和金額每次添加項目到列表框中的時間增加了嗎?那麼你總是會有總成本,而不必試圖從列表中解析出來。

public partial class Form1 : Form 
{ 
    private double cost; 
    private double total; 
    int amount = 0; 

    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void Order_Click(object sender, EventArgs e) 
    { 
     amount = int.Parse(textBox1.Text); 
     cost *= amount; 
     total += cost; 
     ... 
    } 
+0

謝謝,會試試看 – Sloshy 2012-02-29 16:56:08