Resolved Label is showing Total result by adding total to previous total instead new total

Omer Butt

Active member
Joined
Sep 6, 2021
Messages
29
Programming Experience
Beginner
I have created a function named ClearAllAfterSale() in which I Clear DataGridView, Textboxes and reset Labels as shown below:

Clear All After Sale Function:
private void ClearAllAfterSale()
        {
            DGV_Med.Rows.Clear();
            Lbl_Total.ResetText();
            Lbl_Total.ResetText();
            Lbl_TotalAmount.ResetText();
            Lbl_NoofItems.ResetText();
            Lbl_TotalQty.ResetText();
            Lbl_Disc_Percent.ResetText();
            Lbl_DiscountPrice.ResetText();
            Txt_PaidAmount.Clear();
            Lbl_Balance.ResetText();

        }

And called this function on SaveSale() function. In SaveSale() function I coded for Saving a Sale in database and printing a sale receipt where in that code I called the ClearAllAfterSale() function right after I showed a message box for Sale Created Successfully. Code shown below:

SaveSale() function called in CreateSale button click event:
public voic SaveSale()
{
    
                    string BillNo = Lbl_BillNo.Text;
                    int UnitsPurchased = int.Parse(Lbl_NoofItems.Text);
                    Int64 Qty = Int64.Parse(Lbl_TotalQty.Text);
                    int DiscountPercent = int.Parse(Lbl_Disc_Percent.Text);
                    double DiscountPrice = double.Parse(Lbl_DiscountPrice.Text);
                    double TotalAmount = double.Parse(Txt_TotalAmount.Text);
                    double PaidAmount = double.Parse(Txt_PaidAmount.Text);
                    double Balance = double.Parse(Lbl_Balance.Text);

                    string SQL1;
                    string SQL2;

                    SQL1 = "insert into Receipt(Bill_No, No_of_Items, Total_Qty, Disc_in_Percent, Discount_Amount, Total_Amount, Paid_Amount, Balance) values(@Bill_No, @No_of_Items, @Total_Qty, @Disc_in_Percent, @Discount_Amount, @Total_Amount, @Paid_Amount, @Balance) select @@identity";
                    Conn.OpenConnection();
                    SqlCommand cmd = new SqlCommand(SQL1, Conn.Connect);
                    cmd.Parameters.AddWithValue("@Bill_No", BillNo);
                    cmd.Parameters.AddWithValue("@No_of_Items", UnitsPurchased);
                    cmd.Parameters.AddWithValue("@Total_Qty", Qty);
                    cmd.Parameters.AddWithValue("@Disc_in_Percent", DiscountPercent);
                    cmd.Parameters.AddWithValue("@Discount_Amount", DiscountPrice);
                    cmd.Parameters.AddWithValue("@Total_Amount", TotalAmount);
                    cmd.Parameters.AddWithValue("@Paid_Amount", PaidAmount);
                    cmd.Parameters.AddWithValue("@Balance", Balance);
                    int LastID = int.Parse(cmd.ExecuteScalar().ToString());

                    string Medi_Name;
                    double PricePerUnit = 0;
                    int Stock_Quantity = 0;
                    int DiscPercent = 0;
                    double Disc_Amount = 0;
                    double Total_Amount_Per_Unit = 0;

                    for (int row = 0; row < DGV_Med.Rows.Count; row++)
                    {
                        Medi_Name = DGV_Med.Rows[row].Cells[1].Value.ToString();
                        PricePerUnit = double.Parse(DGV_Med.Rows[row].Cells[2].Value.ToString());
                        Stock_Quantity = int.Parse(DGV_Med.Rows[row].Cells[3].Value.ToString());
                        DiscPercent = int.Parse(DGV_Med.Rows[row].Cells[4].Value.ToString());
                        Disc_Amount = double.Parse(DGV_Med.Rows[row].Cells[5].Value.ToString());
                        Total_Amount_Per_Unit = double.Parse(DGV_Med.Rows[row].Cells[6].Value.ToString());

                        SQL2 = "insert into SaleProducts(Receipt_ID, Medi_Name, PricePerUnit, Stock_Quantity, DiscPercent, Disc_Amount, Total_Amount_Per_Unit) values(@Receipt_ID, @Medi_Name, @PricePerUnit, @Stock_Quantity, @DiscPercent, @Disc_Amount, @Total_Amount_Per_Unit)";
                        SqlCommand cmd1 = new SqlCommand(SQL2, Conn.Connect);
                        cmd1.Parameters.AddWithValue("@Receipt_ID", LastID);
                        cmd1.Parameters.AddWithValue("@Medi_Name", Medi_Name);
                        cmd1.Parameters.AddWithValue("@PricePerUnit", PricePerUnit);
                        cmd1.Parameters.AddWithValue("@Stock_Quantity", Stock_Quantity);
                        cmd1.Parameters.AddWithValue("@DiscPercent", DiscPercent);
                        cmd1.Parameters.AddWithValue("@Disc_Amount", Disc_Amount);
                        cmd1.Parameters.AddWithValue("@Total_Amount_Per_Unit", Total_Amount_Per_Unit);
                        cmd1.ExecuteNonQuery();
                    }

                    MessageBox.Show("Sales Competed");
                    BillNo();
                    ClearAllAfterSale();
                    PrintInvoice p = new PrintInvoice();
                    p.SalesID = LastID;
                    p.Show();

                    Conn.CloseConnection();
               
}
And Called the above SaveSale() function in CreateSale button click event Btn_CreateSale_Click
Issue is that It Clears all DataGridView Labels and Textboxes but when I add new Medicine in DataGridView the Lbl_Total in which the total price of all the medicines added is shown is reset but new medicine total is added in previous sale total how can I make it like after click Create Sale Button I want my Sell UserControl to be ready for making a new sale with new bill no which have no previous sale data and work fine any suggestions on what I can apply to achieve right result
 
Solution
And where do you set TotalAmount back to 0? Line #2 is a declaration that only runs once when the class is instantiated, but you are recycling the class instance but clearing the text field and grid.

As quick aside, when dealing with money, use decimal, not double so that you minimize the chances of rounding errors.
Without showing us how Lbl_Total.Text is set, we can't really tell you why you have the previous total being added to the current total. I would suspect that you you may have a class variable that you forgot to reset to zero along with clearing your UI fields.

Which brings around your request for suggestions. The primary suggestion is not to make your UI hold your data. Your UI should only reflect what your data model has. It should not be the source of truth. Your data should be there source of truth. This is a relatively hard earned lesson that programmers finally figured out after the 80's and early 90's when the fad was to create a control that would do everything for you including holding all your data. The lessons learned gave rise to the MV* patterns: Model-View-Controller, Model-View-Presenter, Model-View-ViewModel, etc. Notice how the Model and the View are separate entities. The Model is the data. The View is the UI.
 
this.jpg


below is a code blocks as requested:
//Declared a variable
protected double TotalAmount = 0;
//inside AddtoCard button click event after clicking this button medicine add to the Data Grid View and show the total in Lbl_Total and Txt_TotalAmount
TotalAmount += Double.Parse(Txt_TotalPrice.Text);
Lbl_Total.Text = "Rs. " + TotalAmount.ToString();
Txt_TotalAmount.Text = TotalAmount.ToString();

//if discount entered for a medicine
TotalAmount += Double.Parse(Txt_Sale.Text);
Lbl_Total.Text = "Rs. " + TotalAmount.ToString();
Lbl_Total.Text = String.Format("{0:N2}", Lbl_Total.Text);
Txt_TotalAmount.Text = TotalAmount.ToString();
Txt_TotalAmount.Text = String.Format("{0:N2}", Txt_TotalAmount.Text);

and in the Txt_TotalPrice and Txt_Sale are the total based on Per Unit Price and No of Units and if Discount % is added the code is below:
C#:
if (Txt_Disc_Percentage.Text != "")
            {
                //int Dis;
                double Dis, DisCoverted, Final;
                Dis = Double.Parse(Txt_Disc_Percentage.Text);
                Final = Dis * Convert.ToDouble(Txt_TotalPrice.Text) / 100;
                DisCoverted = Final;
                Txt_DiscountPrice.Text = DisCoverted.ToString();
                Txt_DiscountPrice.Text = String.Format("{0:N2}", double.Parse(Txt_DiscountPrice.Text));
                Txt_Sale.Text = (Convert.ToDouble(Txt_TotalPrice.Text) - Final).ToString();
                Txt_Sale.Text = String.Format("{0:N2}", double.Parse(Txt_Sale.Text));
            }
            else
            {
                Txt_Sale.Clear();
                Txt_DiscountPrice.Clear();
            }
 
And where do you set TotalAmount back to 0? Line #2 is a declaration that only runs once when the class is instantiated, but you are recycling the class instance but clearing the text field and grid.

As quick aside, when dealing with money, use decimal, not double so that you minimize the chances of rounding errors.
 
Solution
yes thank you very much I was not checking the declaration of TotalAmount and assuming that Reseting or setting all controls to null will work But What I did is in the Create Sale button after Calling the SaveSale() function I again declare the TotalAmount=0; So whenever sale is created it will reset the value of TotalAmount Back to 0.
 
Back
Top Bottom