2016-07-16 45 views
1

我想显示项目总价格的总和。我面临的2个问题:显示DataTable的列的总和值

  • 它显示我错了全部项目的价格
  • 我想补充.00总价格

可以在image检查问题的一个明确的解释。

这里是我的代码:

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(); 

回答

1

在你的循环您添加到总总是排的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。

+0

非常感谢你s我真的非常感谢你,你真的杀死天才人我可以问你一个更多的问题,如果你不介意如此关于列表框 –

+0

和另外一件事我问你我的第一个问题我如何加.00与项目价格 –

+0

您的问题的这部分内容不清楚。我看不到你如何添加项目到列表框。但是,如果您从产品列表中取出项目,则需要按照现在的格式对其进行格式化。 – Steve

1

而不是使用for循环,您可以简单地使用Compute方法的数据表并传递一个表达式来计算。例如:

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

而且格式化总表现出后位小数2位,你可以使用这些选项之一: