0

I created a program which calculates the sum of a column in a datagridview, the problem arises when I refactor the logic from the click handler into a separate a method. The calcSum method does not seem to give me the correct output compared with button2_Click which has all the logic directly in the click handler.

Can anyone please point out what's wrong with my code?

//Calls sum of column method, "incorrect" output
private void button1_Click(object sender, EventArgs e){
    calcSum(a,b,3);
}

private double calcSum(double a, double b, int c){
    foreach(DataGridViewRow r in dataGridView1.Rows){
        a = Convert.ToDouble(r.Cells[c].Value);
        b = b + a;
    }
    MessageBox.Show("sum is " = b.ToString());
    return b;
}

//shows correct/calculates output
private void button2_Click(object sender, EventArgs e){
    double a =0,b=0;
    foreach (DataGridViewRow r in dataGridView1.Rows){
        a = Convert.ToDouble(r.Cells[3].Value);
        b = b + a;
    }
    MessageBox.Show(b.ToString());
}
DisplayName
  • 61
  • 2
  • 2
  • 8

4 Answers4

1

In your method, you call the row "row" inside the loop, but declare it as r in the foreach.

I would recommend simplifying your code though. Have a look at the answer here: how I can show the sum of in a datagridview column?

I don't think you need the a & b variables to get at your answer and perhaps you are initializing them differently in the 1st example when you are passing them into the method.

int a= 0;
foreach (DataGridViewRow r in dataGridView1.Rows){
{
    a += Convert.ToInt32(r.Cells[c].Value);
}
Community
  • 1
  • 1
zaq
  • 2,571
  • 3
  • 31
  • 39
0

It looks like you are passing your parameters a and b are declared elsewhere. If b has a value other then zero when you click the button, it will be added to the results. Try this:

private void button1_Click(object sender, EventArgs e){
    calcSum(3);
}

private double calcSum(int c){
    double a=0, b=0;
    foreach(DataGridViewRow row in dataGridView1.Rows){
        a = Convert.ToDouble(row.Cells[c].Value);
        b = b + a;
    }
    MessageBox.Show("sum is " = b.ToString());
    return b;
}
chadnt
  • 1,095
  • 9
  • 24
0
private void button1_Click(object sender, EventArgs e){
    calcSum(out a,out b,3);
}

private double calcSum(out double a, out double b, int c){
    foreach(DataGridViewRow r in dataGridView1.Rows){
        a = Convert.ToDouble(r.Cells[c].Value);
        b = b + a;
    }
    MessageBox.Show("sum is " = b.ToString());
    return b;
}

You should read about Out parameters

Sourav Sarkar
  • 292
  • 3
  • 20
-1

First thought, it looks like a and b are global variables, you should reset them to zero

user2709119
  • 36
  • 1
  • 3