Vb.net 如何在DataGridView中获取列的总数

Vb.net 如何在DataGridView中获取列的总数,vb.net,Vb.net,每次有空白单元格时,结果都是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

每次有空白单元格时,结果都是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
Dim tot为十进制
尝试
如果BREAKDOWNLIST.RowCount为1,则
对于BREAKDOWNLIST.Rows中作为DataGridViewRow的每一行
如果为Nothing(Me.BREAKDOWNLIST.CurrentRow.Cells(5.Value)),则
其他的
如果BREAKDOWNLIST.RowCount=1,则
tot=Val(行单元格(5)值)
ElseIf BREAKDOWNLIST.RowCount>1则
tot+=Val(行单元格(5)值)
如果结束
如果结束
下一个
ElseIf BREAKDOWNLIST.RowCount=1,则
如果结束
TOTAL.Text=tot
接住
结束尝试

如果单元格不包含值,将抛出一个,并保留
Try
-块

因此,在计算之前,需要检查单元格中的数值。 此外,您可以缩短代码并省略
Try/Catch
-块:

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()

就像Mat说的,但我更喜欢.net的方式。他们说
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

您确定单元格的内容是整数而不是字符串吗?网格是否绑定到
数据表
?如果是这样,“空”单元格实际上包含
DBNull.Value
,而不是
Nothing
。如果它绑定到一个
数据表
,那么您可以简单地调用该
数据表
计算
方法。您看到哪里有一个空的
捕获
?这可能会隐藏您需要看到的错误。我做了一个简短的测试,我的答案中的方法比您使用
TryParse
(测试了1M行)的方法快10%左右。您是否有一个链接/引用,指向
TryParse
IsNumeric
快的语句?一个扩展的引号对于IsNumeric,它在内部使用Double.TryParse。事实上,Double.TryParse是专门为提高IsNumeric的性能而编写的。如果您想知道字符串是否可以转换为该类型,您应该自己使用相应数字类型的TryParse方法我的测试结果有点不同。每1M,点网循环耗时232毫秒。VB6循环耗时312毫秒。点网循环耗时231毫秒。VB6循环耗时419毫秒。点网循环耗时249毫秒。VB6循环耗时342毫秒。点网循环耗时234毫秒。VB6循环耗时322毫秒。@MatSnow我在VS 2017环境中运行测试,这可能是错误的方式。我使用了.Net秒表类。我以前从未尝试过计时。丈夫对我没有:-(@Mary我现在已经确定了结果不同的原因。我在循环中进行了双重转换,因为从另一个测试中复制粘贴了错误的行。我没有粘贴
tot+=decValue
,而是粘贴了
tot+=CDec(row.Cells(5.Value)
。所以你的结果是正确的。对不起:)(顺便说一句,我用秒表进行了相同的测试)