显示DataTable列的总值

我想显示物品总价格的总和。 我面临两个问题:

  • 它显示我错误的物品总价格
  • 我想在总价中加上.00

您可以检查图像中的问题以获得清晰的解释。

这是我的代码:

 tDisplay.Text = "Return/" + "Receipt No:" + Return_Form.setalueforText011; label1.Text = Return_Form.setalueforText011; OleDbConnection VCON = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Restaurant.accdb"); DataSet dsa = new DataSet(); DataTable dt = new DataTable(); dsa.Tables.Add(dt); OleDbDataAdapter da = new OleDbDataAdapter(); da = new OleDbDataAdapter("SELECT [Column1],[Column2],[Column3] from [Total] Where [Receipt No] = " + label1.Text + "", VCON); da.Fill(dt); //dataGridView1.DataSource = dt; for (int i = 0; i < dt.Rows.Count; i++) { products.Add(new tblProduct() { productName = dt.Rows[i]["Column2"].ToString(),productPrice = Convert.ToDecimal(Math.Round(Convert.ToDecimal(dt.Rows[i]["Column1"].ToString())))}); label3.Text = dt.Rows[i]["Column3"].ToString(); textBox59.Text = "Rs: "+String.Format("{0:}", Total); tblProduct selected = (tblProduct)(listBox60.SelectedItem); Total += (decimal)selected.productPrice; } VCON.Close(); 

在循环中,总是将SelectedItem行添加到总数中。 这始终是第一项,因此您最终将第一项的值加倍。

 for (int i = 0; i < dt.Rows.Count; i++) { // Create and initialize a new tblProduct from the datatable row tblProduct current = new tblProduct(); current.ProductName = dt.Rows[i]["Column2"].ToString(); current.productPrice = Convert.ToDecimal(Math.Round(Convert.ToDecimal(dt.Rows[i]["Column1"].ToString()))); // Add to your list of products products.Add(current); // This line is wrong because you overwrite the value at each loop label3.Text = dt.Rows[i]["Column3"].ToString(); // Sum the price of the current tblProduct Total += (decimal)current.productPrice; } // Outside the loop update your total label textBox59.Text = "Rs: "+String.Format("{0:0.00}", Total); 

如果你允许我提出建议。 不要那样命名你的控件。 它们不可读,不易识别。 从现在开始的某一天查看此代码,您将遇到很多问题需要记住哪个控件是textBox59或listBox60。

您可以简单地使用数据表的Compute方法并将表达式传递给compute,而不是使用for循环。 例如:

 var total = double.Parse(yourDataTable.Compute("SUM(Column1)", "").ToString()); 

另外要格式化总计以显示小数位后的2位数,您可以使用以下任一选项:

  • “0”自定义数字格式字符串 : string.Format("{0:0.00}", total))

  • 定点“F”格式说明 string.Format("{0:F2}", total))string.Format("{0:F2}", total))