2016-07-16 43 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位,你可以使用這些選項之一: