我如何从datagridview vb.net总和

时间:2014-05-25 18:52:45

标签: vb.net vb.net-2010

- 我如何从mysql

获取datagridview中totalPrice的总和
ProductName          Qty.   Price    totalPrice
2 Pcs. Chickenjoy     5      59         295
2 Pcs. Chickenjoy     1      69          69
2 Pcs. Chickenjoy     1      69          59

                                  TOTAL??

- 总和应该是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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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