【问题标题】:Sum Column in DataGridView ignore negative numbersDataGridView 中的求和列忽略负数
【发布时间】:2011-09-15 13:04:57
【问题描述】:

您好,我需要忽略 DGV 列总和中的负数。我用来添加值的代码如下:

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);
        }
        return tot;
    }

如果 Row 的值为负数,我将如何更改它以使其不包含在总和中?

谢谢!

韩国

【问题讨论】:

    标签: c# winforms datagridview sum


    【解决方案1】:

    换行:

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

    看妈!没有如果!没有三元运算符!只是简单的数学!

    【讨论】:

      【解决方案2】:

      类似这样的:

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

      【讨论】:

        【解决方案3】:

        for 循环的主体更改为

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

        【讨论】:

          【解决方案4】:
          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;
          }
          

          【讨论】:

            猜你喜欢
            • 2020-03-04
            • 2019-10-22
            • 1970-01-01
            • 2011-10-08
            • 2015-02-10
            • 2018-04-22
            • 2016-12-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多