2014-04-14 102 views
0

我想計算一個數據網格上的一行上的總數,並提出以下代碼。datagrid返回錯誤值的計算行

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click 

    Dim dblQty As Double 
    Dim dblPrice As Double 

    For index As Integer = 0 To grdNewInvoice.RowCount - 1 

     dblQty += Convert.ToDouble(grdNewInvoice.Rows(index).Cells(1).Value) 
     dblPrice += Convert.ToDouble(grdNewInvoice.Rows(index).Cells(2).Value) 

     grdNewInvoice.Rows(index).Cells(3).Value = dblPrice * dblQty 


    Next 


End Sub 

如果我只有一行,效果很好。如果我有第二行,它會像這樣添加所有列的值。第1列有一個組合框,用戶可以更改數量的值,我希望每次用戶更改該值時總行都要重新計算。然而,這是不正確計算,如果我改變任何行的值,它增加了所有的行在一起,就像這樣:

enter image description here

我對酒的值更改爲4,它產生了錯誤的總數

回答

1

刪除+=,否則您將合計qty和每price

9 * $17 = $153

9 = 5 + 4, $17 = $7.00 + $10.00

代碼應該是:

For index As Integer = 0 To grdNewInvoice.RowCount - 1 

    dblQty = Convert.ToDouble(grdNewInvoice.Rows(index).Cells(1).Value) 
    dblPrice = Convert.ToDouble(grdNewInvoice.Rows(index).Cells(2).Value) 

    grdNewInvoice.Rows(index).Cells(3).Value = dblPrice * dblQty 


Next 
+0

完美,謝謝 –

+0

請給對勾! =)謝謝 –

+1

@t mckeown沒問題,完成 –