Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...