开发者

Sum Column in DataGridView ignore negative numbers

开发者 https://www.devze.com 2023-04-05 06:19 出处:网络
Hello I need to ignore negative numbers in a sum of a DGV column.The code I am using to add the values is as follows:

Hello I need to ignore negative numbers in a sum of a DGV column. The code I am using to add the values is as follows:

private double DGVTotal()
    {
        double tot = 0;
        int i = 0;
        for (i = 0; i < dataGridView1.Rows.Count; i++)
        {
            tot = tot + Convert.ToDouble(dataGridView1.Rows[i].Cells["Total"].Value);
      开发者_StackOverflow社区  }
        return tot;
    }

How would I change that so if the value of the Row is a negative number to not have it be included in the sum?

Thanks!

Kor


One line change:

tot = tot + Math.Max(0, Convert.ToDouble(dataGridView1.Rows[i].Cells["Total"].Value));

Look Ma! No IF! No ternary operators! Just plain Math!


Something like this:

private double DGVTotal()
    {
        double tot = 0;
        int i = 0;
        for (i = 0; i < dataGridView1.Rows.Count; i++)
        {
            Double dbTemp = Convert.ToDouble(dataGridView1.Rows[i].Cells["Total"].Value);
            if (dbTemp > 0)
               tot = tot + dbTemp;
        }
        return tot;
    }


Change the body of the for loop to

    {
        double rowValue = Convert.ToDouble(dataGridView1.Rows[i].Cells["Total"].Value);
        if (rowValue > 0)
            tot += rowValue;
    }


for (i = 0; i < dataGridView1.Rows.Count; i++)
{
    double val = Convert.ToDouble(dataGridView1.Rows[i].Cells["Total"].Value);
    tot = tot + val > 0.0 ? val : 0.0;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消