2013-04-28 77 views
-4

我试图将数量和价格文本框中的值相乘,然后将其传递到每次按下添加按钮时都会更新的总文本框中。以下是我迄今为止所尝试的。在每次迭代按钮按下累积总计

如何让它在我的总文本框中显示产品并积累它?例如。在数量4和价格4读取16,然后,如果我投放量2,价格2它将读取20

private void add_btn_Click(object sender, EventArgs e) 
    { 
     try 
     { 
      if (customer_textBox.Text == "") 
      { 
       MessageBox.Show(
        "Please enter valid Customer"); 
      } 
      if (quantity_textBox.Text == "") 
      { 
       MessageBox.Show(
        "Please enter valid Quantity"); 
      } 
      if (price_per_item_textBox.Text == "") 
      { 
       MessageBox.Show(
        "Please enter valid Price"); 
      } 
      else 
      { 
       decimal total = Decimal.Parse(total_textBox.Text); 
       total = int.Parse(quantity_textBox.Text) * int.Parse(price_per_item_textBox.Text); 
       total += total; 
       total_textBox.Text = total.ToString(); 
      } 
      quantity_textBox.Clear(); 
      customer_textBox.Clear(); 
      price_per_item_textBox.Clear(); 
      item_textBox.Clear(); 
     } 
     catch (FormatException) 
     { 

     } 
     total_textBox.Focus(); 


    } 

回答

3

更改此

decimal total = Decimal.Parse(total_textBox.Text); 
total = int.Parse(quantity_textBox.Text) * int.Parse(price_per_item_textBox.Text); 
total += total; 
total_textBox.Text = total.ToString(); 

这个

total = currentTotal + (decimal.Parse(quantity_textBox.Text) * decimal.Parse(price_per_item_textBox.Text)); 
total_textBox.Text = total.ToString("C"); 

并创建一个类级变量private decimal currentTotal;

第一行不需要,因为您只需重新分配值第四行中的文本框。我假设每件产品的价格是decimal价值(例如1.99美元)。将其解析为int将失去精度(例如$ 1.99将变为1)。将int乘以int也将返回int,$ 1.99 * 2将变为1 * 2,其将仅为2而不是3.98。