2014-05-25 48 views
-3

,我要如何获得totalPrice的总和我的datagridview从MySQL我怎么总从DataGridView vb.net总和

ProductName   Qty. Price totalPrice 
2 Pcs. Chickenjoy  5  59   295 
2 Pcs. Chickenjoy  1  69   69 
2 Pcs. Chickenjoy  1  69   59 

            TOTAL?? 

-the总和应该是423的问题是,这将增加一倍的总和

,尤其是圆形是我的代码:

Try 
    'declaring variable as integer to store the value of the total rows in the datagridview 

    Dim max As Integer = DataGridView1.Rows.Count - 1 
    Dim total As String = "Total ----------->" 
    'getting the values of a specific rows 


    For Each row As DataGridViewRow In DataGridView1.Rows 
     'formula for adding the values in the rows 
     DataGridView1.Rows(max).Cells(4).Value += row.Cells(4).Value 
     DataGridView1.Rows(max).Cells(3).Value = total 
    Next 
Catch ex As Exception 
    MsgBox(ex.Message) 
End Try 

截图 http://goo.gl/Ufj53b

+0

设置一个断点并观察代码执行。你会学到很多关于你认为的代码将做什么和它实际上做什么之间的区别,并学习如何使用调试器 – Plutonix

回答

0

您的主要问题似乎是使用For Each循环。当它到达最后一行时,它将累计总数加到它自己。 for循环只有第二个最后一行应该工作:

Try 
    'declaring variable as integer to store the value of the total rows in the datagridview 

    Dim max As Integer = DataGridView1.Rows.Count - 1 
    'getting the values of a specific rows 
    DataGridView1.Rows(max).Cells(3).Value = "Total ----------->" 

    For I = 0 To DataGridView1.Rows.Count - 2 
     'formula for adding the values in the rows 
     DataGridView1.Rows(max).Cells(4).Value += DataGridView1.Rows(I).Cells(4).Value 
    Next 
Catch ex As Exception 
    MsgBox(ex.Message) 
End Try 
+0

大谢谢你先生@tinstaafl 最后一个问题和帮助 我如何发送文本框1 .text from datagridview,即时通讯对不起,我在datagridview新。 – LordWelhimNoob

0

试试这个:

Dim tot As Integer 
For Each row As DataGridViewRow In DataGridView1.Rows 
    'formula for adding the values in the rows 
    tot += row.Cells(4).Value 
Next 
DataGridView1.Rows(max).Cells(3).Value = total 
DataGridView1.Rows(max).Cells(4).Value = tot 
0

你的循环有错误。因为它会计算295,69和59的总和,然后再加上总和。这就是为什么它会加倍的总和。试试这个

Try 
    'declaring variable as integer to store the value of the total rows in the datagridview 

    Dim max As Integer = DataGridView1.Rows.Count - 1 
    Dim total As String = "Total ----------->" 
    Dim tot as integer =0 
    'getting the values of a specific rows 


    For Each row As DataGridViewRow In DataGridView1.Rows 
     'formula for adding the values in the rows 
     tot += row.Cells(4).Value 
    Next 
    DataGridView1.Rows(max).Cells(4).Value += tot 
     DataGridView1.Rows(max).Cells(3).Value = total 
Catch ex As Exception 
    MsgBox(ex.Message) 
End Try