1

I have 2 data grid views, one for Purchases and one for Sales

I sum the total of sales and subtract the total of purchases from it.

the problem is, it will only do the calculation if the number of rows of both datagridviews are the same, if one of them has more rows than the other, it will not give any value in the textbox where it should show the result

that's my code

private void GrossSale()
{
    int sum = 0;
    for (int i = 0; i < dataGridView1.Rows.Count; ++i)
    {
        sum += Convert.ToInt32(dataGridView1.Rows[i].Cells[2].Value);
    }
    txtGrossSale.Text = sum.ToString();
}
private void NetSale()
{
    int sum2 = 0;
    for (int i = 0; i < dataGridView1.Rows.Count; ++i)
    {
        sum2 += Convert.ToInt32(dataGridView1.Rows[i].Cells[3].Value);
    }
    txtNetSale.Text = sum2.ToString();
}
private void GrossPurchase()
{
    int sum3 = 0;
    for (int i = 0; i < dataGridView2.Rows.Count; ++i)
    {
        sum3 += Convert.ToInt32(dataGridView2.Rows[i].Cells[2].Value);
    }
    txtGrossPurchase.Text = sum3.ToString();
}
private void NetPurchase()
{
    int sum4 = 0;
    for (int i = 0; i < dataGridView2.Rows.Count; ++i)
    {
        sum4 += Convert.ToInt32(dataGridView2.Rows[i].Cells[3].Value);
    }
    txtNetPurchase.Text = sum4.ToString();
}
private void TotalGross()
{
    int sum5 = 0;
    int sum6 = 0;
    int sum7 = 0;
    for (int i = 0; i < dataGridView2.Rows.Count; ++i)
    {
        sum5 += Convert.ToInt32(dataGridView1.Rows[i].Cells[3].Value);
        sum6 += Convert.ToInt32(dataGridView2.Rows[i].Cells[3].Value);
    }
    sum7 = sum5 + sum6;
    txtGross.Text = sum7.ToString();
}
Joey Arnanzo
  • 329
  • 3
  • 18
  • Try with [Compute](https://msdn.microsoft.com/en-us/library/system.data.datatable.compute%28v=vs.110%29.aspx) instead perhaps. – Jacob H May 24 '18 at 12:51
  • Thanks @JacobH for your reply, should I still use For with the compute ? – Joey Arnanzo May 24 '18 at 12:58
  • Do you have a datatable? That is key. If you do, then you just create 2 ints, compute the value and then subtract the ints. No loops needed. If you have no datatable then look at @Mark answer below. – Jacob H May 24 '18 at 13:13
  • 1
    Or heck, maybe just bind a datatable and forget the looping calculations. https://stackoverflow.com/a/3779835/7948962 – Jacob H May 24 '18 at 13:14

1 Answers1

2

Have a look at TotalGross(). You are looping over dataGridView2.Rows.Count, but are accessing both dataGridView1.Rows[i] AND dataGridView2.Rows[i] inside the loop...

Mark Willis
  • 818
  • 12
  • 19