2012-07-09 80 views
5

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

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

回答

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

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

+0

啊!我没有想过这样引用它。我会尽力。谢谢! – JAS 2012-07-09 19:00:39

+0

确保禁用排序 – Jesse 2012-07-09 19:13:08