Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

c# - Show total Sum of values of a Column of a DataTable

I want to show sum of total Price of items. I am facing 2 issues:

  • It's showing me wrong total of items price
  • I want to add .00 to the total price

You can check issue in the image for a clear explanation.

Here is my code:

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();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In your loop you add to the total always the SelectedItem row. This is always the first item so you end up doubling the value of the first item.

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

If you allow me to give an advice. Do not name your controls that way. They are unreadable and not easily recognizable. Looking at this code some day from now you will have a lot of problems to remember which control is textBox59 or listBox60.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...