【问题标题】:get total of column in datagridview获取datagridview中的列总数
【发布时间】:2018-12-30 14:51:47
【问题描述】:

我已将数据放入数据网格视图列

dgvAccDetail.Rows(i).Cells(3).Value = dtVD.Rows(i).Item("DEBIT").ToString.Trim

现在我需要得到 "DEBIT" 列的总和,为此...

        Dim tot As Integer = 0

             For i As Integer = 0 To dgvAccDetail.RowCount - 1
            tot += dgvAccDetail.Rows(i).Cells(4).Value

        Next
        If tot = 0 Then
            MessageBox.Show("No Records Found")
        End If

        TXTVoucherDTotal.Text = tot.ToString()

但我收到了消息

“从字符串到双精度类型的转换无效”

请告诉我这段代码有什么问题,

【问题讨论】:

  • 你的数据源是什么?是数据表吗?

标签: string vb.net types datagridview double


【解决方案1】:

首先,将 Option strict 设置为 on,它将帮助您避免将来出现许多错误。关闭选项 strict 后,编译器必须推断数据类型,这就是您的计算不起作用的原因。

其次,改变这一行:

dgvAccDetail.Rows(i).Cells(3).Value = dtVD.Rows(i).Item("DEBIT").ToString.Trim 
'This line doesn't compile with option strict on

dgvAccDetail.Rows(i).Cells(3).Value = dtVD.Rows(i).Cells("DEBIT").Value()

最后,您正在尝试对文本进行数学运算,您需要先将单元格值转换为正确的格式。

If dgvAccDetail.rows.count > 0

     Dim tot As double = 0 'integer will only work for whole numbers.
                           'It will disregard fractional values if set to integer.

        For i As Integer = 0 To dgvAccDetail.Rows.Count - 1
            tot = tot + Cdbl(dgvAccDetail.Rows(i).Cells(4).Value)

        Next

    TXTVoucherDTotal.Text = Format(tot,"0.00")

Else

    MessageBox.Show("No Records Found")

End If

【讨论】:

    【解决方案2】:

    您正在尝试将字符串值添加到整数值。 dgvAccDetail.Rows(i).Cells(4).Value 返回一个字符串。 您可以将其解析为整数:

    tot += Integer.Parse(dgvAccDetail.Rows(i).Cells(4).Value)
    

    【讨论】:

    • 感谢回复,现在我收到了其他消息“输入字符串的格式不正确”
    • 字符串的值是多少?
    • it 600 --- dgvAccDetail.Rows(i).Cells(3).Value = dtVD.Rows(i).Item("DEBIT").ToString.Trim
    【解决方案3】:

    试试这个:

     For i = 0 To dgvAccDetail.RowCount - 1
            tot += Cint(dgvAccDetail(4, i).Value)
     Next
    

    【讨论】:

      【解决方案4】:

      DataTable 的计算方法需要 2 个字符串;表达式和过滤器。使用 DataTable 中的相应列。

       Dim columnSum As Integer = CInt(dtVD.Compute("Sum(DEBIT)", Nothing))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多