2012-07-09 101 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