Link to home
Start Free TrialLog in
Avatar of SniperCode Sheva
SniperCode Sheva

asked on

How to calculate the sum of all rows at each new row in C#

My app is a sort of cash register for a shop so in the datagrid there is Reference ,
it is the reference of the product.
When the user types the reference directly the information about the product will be filled in the other columns and the user can choose the quantity he wants and it will do the calculation.

ALSO, I tried to put the total of the bill in the datagrid...

Reference | Product |Quantity |Price |Total |Total Bill
AB              |AB           |2               |1000 |2000 |5000
BC              |BC            |3              |1000 |3000

This is what I am trying to do... To do it, I tried this code:

private void TAB_Credit_RowValidated(object sender, DataGridViewCellEventArgs e)
{
    int sum = 0;
 
    for (int i = 0; i < TAB_Credit.Rows.Count; ++i)
    {
 
        sum += Convert.ToInt32(TAB_Credit.Rows[i].Cells["Total"].Value);
    }
 
    TAB_Credit.Rows[e.RowIndex].Cells["Total_Bill"].Value = sum.ToString();
}

Open in new window

Avatar of Dmitry G
Dmitry G
Flag of New Zealand image

I'd say it's not really correct, from an object perspective, to add "grand total" to a row - this is characteristic of a rows collection.

And if we talk about a "cash register", check any receipt from a cash counter (or invoice, or...) - the "grand total" is never printed in items rows. I can't see any point to change commonly accepted behavior.
Hi,
You can use compute function instead of for loop.

TAB_Credit.Rows[e.RowIndex].Cells["Total_Bill"].Value = TAB_Credit.Compute("sum(Total)", "id>0");

Open in new window

Hmmmm... TAB_Credit is a DataGridView, as I understand. And dataGridView has NO "Compute" method, this method is on the DataTable class. Am I wrong? Or the above code is wrong?
ASKER CERTIFIED SOLUTION
Avatar of Dmitry G
Dmitry G
Flag of New Zealand image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial