c#Datagridview行计算

时间:2012-07-09 18:39:39

标签: c# datagridview date-arithmetic

我有一个带有Datagridview的窗体,其中包含来自xml文件的数据。 DGV的设置如下:日期,产品,价格

共有10行数据。

我试图计算价格从一行到下一行的变化,并且难以找到解决方案。例如:

1/1/12, ABC, $2.00
1/1/12, ABC, $2.50

Net Change: .50

在列中我可以使用Table.Columns.Expression,但我不清楚如何将此计算减去先前与当前。

我考虑过遍历列,添加到新表并以这种方式计算,但似乎是一个低于标准的解决方案。一旦我得到更改ID,就像将其添加到Datagridview。

没有经过测试,但有类似的事情:

if (dataGridView1.Rows.Count > 0)
{
    specifier = "###,###.00";

    double tier1Minus = 0;
    double tier2Minus = 0;

    for (int i = 0; i < dataGridView1.Rows.Count; ++i)
    {
        tier1Minus += Convert.ToDouble(dataGridView1.Rows[i].Cells["Price"].Value);

        tier2Minus += Convert.ToDouble(dataGridView1.Rows[i+1].Cells["Price"].Value);
    }

    // then add to dataGridView1
}

1 个答案:

答案 0 :(得分:3)

为什么不做类似(未经测试)的事情:

for(int i = 0; i < dataGridView1.Rows.Count - 1; i++)
    dataGridView1.Rows[i+1].Cells["NetChange"].Value =
        Convert.ToDouble(dataGridView1.Rows[i+1].Cells["Price"].Value) - 
        Convert.ToDouble(dataGridView1.Rows[i].Cells["Price"].Value);

或者更好的是,在第一次从文件导入数据并插入行时计算它。