datagridview值的总和修改它并将其添加到其他总和

时间:2017-07-24 15:03:47

标签: c# winforms datagridview

我有这个销售点系统。我已经做了好几天了,我似乎真的无法让它发挥作用。点击后我有这个折扣复选框 它应该这样做:

  1. 检查所有带有“D”的产品并总计其总价并将其列为totaldiscountablesales.Text

  2. 以discount.Text

  3. 显示总折扣价
  4. 无论D与否,小计仍应是价格的全部总和。
  5. Totaldue应为小计 - 总折扣。
  6. 我不知道我的代码是什么问题,我现在所知道的就是它。

    enter image description here

    private void cbDiscount2_CheckedChanged(object sender, EventArgs e)
        {
            double sum = 0;
            double Dsum = 0;
            double sumwithoudD = 0;
            double Dsumless20;
            double Dsumless20plussum;
    
            if (cbDiscount2.Checked == true)
            {
    
                for (int i = 0; i < dgvPOScart.Rows.Count; ++i)
                {
                    if (dgvPOScart.Rows[i].Cells[6].Value.ToString() == "D")
                    {
                        Dsum += Convert.ToDouble(dgvPOScart.Rows[i].Cells[5].Value);
                        totaldiscountablesales.Text = Dsum.ToString("0.00");
                        Dsumless20 = Dsum * .20;                     
                        discount.Text = Dsumless20.ToString("0.00");
                    }
                    else if((dgvPOScart.Rows[i].Cells[6].Value.ToString() == ""))
                    {                    
                        sumwithoudD += Convert.ToDouble(dgvPOScart.Rows[i].Cells[5].Value);
                    }       
    
                }
                Dsumless20plussum = Dsum + sumwithoudD;               
                totaldue.Text = Dsumless20plussum.ToString("0.00");               
            }
            else if (cbDiscount2.Checked == false)
            {
                  for (int i = 0; i < dgvPOScart.Rows.Count; ++i)
                  {
                     sum += Convert.ToDouble(dgvPOScart.Rows[i].Cells[5].Value);
                     subtotal.Text = sum.ToString("0.00");
                     totaldue.Text = sum.ToString("0.00");
                  }                 
            } 
    
        }
    

1 个答案:

答案 0 :(得分:1)

你可能比这更复杂。尝试是这样的,你只跟踪你关心的两个总数:总购物车和打折商品:

decimal cartTotal = 0;
decimal discountTotal = 0;
for (int i = 0; i < dgvPOScart.Rows.Count; ++i) {
  cartTotal += Convert.ToDecimal(dgvPOScart.Rows[i].Cells[5].Value);
  if (cbDiscount2.Checked && dgvPOScart.Rows[i].Cells[6].Value.ToString() == "D") {
    discountTotal += Convert.ToDecimal(dgvPOScart.Rows[i].Cells[5].Value);
  }
}

totaldue.Text = string.Format("{0}", cartTotal - (discountTotal * .2M));
subtotal.Text = string.Format("{0}", cartTotal);
totaldiscountablesales.Text = string.Format("{0}", discountTotal);
discount.Text = string.Format("{0}", discountTotal * .2M);

在处理货币值时,您应该使用Decimal类型而不是Double,因为精度很重要。