Calculate sum of a column in a datagridview c#

瘦欲@ 提交于 2019-12-25 05:32:40

问题


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());
}

回答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);
}



回答2:


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;
}



回答3:


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




回答4:


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



来源:https://stackoverflow.com/questions/41882703/calculate-sum-of-a-column-in-a-datagridview-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!