简体   繁体   English

如何在DataGridView中获取列的总数

[英]How to get the total of a column in DataGridView

Every time there is a blank cell the result is 0? 每次有一个空白单元格时结果为0?

Dim tot As Decimal
Try
    If BREAKDOWNLIST.RowCount <> 1 Then
        For Each row As DataGridViewRow In BREAKDOWNLIST.Rows
            If IsNothing(Me.BREAKDOWNLIST.CurrentRow.Cells(5).Value) Then

            Else
                If BREAKDOWNLIST.RowCount = 1 Then
                    tot = Val(row.Cells(5).Value)
                ElseIf BREAKDOWNLIST.RowCount > 1 Then
                    tot += Val(row.Cells(5).Value)
                End If
            End If
        Next
    ElseIf BREAKDOWNLIST.RowCount = 1 Then
    End If

    TOTAL.Text = tot
Catch
End Try

Like Mat said but I like the .net way better. 就像Mat所说的一样,但我更喜欢.net方式。 They say TryParse is faster which could make a difference if you have an awful lot of rows. 他们说TryParse更快,如果您有很多行,可能会有所作为。

Dim decValue As Decimal
Dim tot As Decimal
For Each row As DataGridViewRow In BREAKDOWNLIST.Rows
    If Decimal.TryParse(row.Cells(5).Value, decValue) Then
        tot += decValue
    End If
Next

If the cell contains no value, an InvalidCastException is thrown and the Try -block is left. 如果单元格不包含任何值,则抛出InvalidCastException并保留Try -block。

So you'll need to check the cell for a numeric value before calculating. 因此,您需要在计算之前检查单元格中的数字值。 Furthermore you can shorten your code and omit the Try/Catch -block: 此外,您可以缩短代码并省略Try/Catch -block:

Dim tot As Decimal

For Each row As DataGridViewRow In BREAKDOWNLIST.Rows
    If IsNumeric(row.Cells(5).Value) Then
        tot += Val(row.Cells(5).Value)
    End If
Next

TOTAL.Text = tot.ToString()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM