首页 > 解决方案 > 如何在数据网格视图中按名称对单元格值求和?

问题描述

您好,我创建了一个表单,在其中放置了 datagridview 和两个名称为现金和卡的文本框。每当我在datagridview中输入值时,我想分别汇总现金和卡值并插入到sql数据库中。我的代码不起作用

Dim rw As New DataGridViewRow

For Each rw In DataGridView2.Rows
    For index As Integer = 0 To DataGridView2.RowCount - 1
        Dim u As string = rw.Cells(0).Value
        Dim v As string = rw.Cells(0).Value
        If rw.Cells(0).Value = "CASH" Then
            u += Convert.ToDouble(DataGridView2.Rows(index).Cells(1).Value)
            Label45.Text = u
        End If

        If rw.Cells(0).Value = "CARD" Then
            v += Convert.ToDouble(DataGridView2.Rows(index).Cells(1).Value)
            Label46.Text = u
        End If
    Next
Next

标签: vb.net

解决方案


在线评论和解释

Private Sub OPCode2()
    'Give names to variables that are meaningful
    Dim TotalCash As Double
    Dim TotalCard As Double
    'just one loop
    For Each rw As DataGridViewRow In DataGridView2.Rows
        'resolve values of cells just once for each iteration
        Dim MethodOfPayment As String = rw.Cells(0).Value.ToString
        Dim value As Double = CDbl(rw.Cells(1).Value)
        'Single If statement with an ElseIf
        If MethodOfPayment = "CASH" Then
            TotalCash += value
            'Don't updat the label on every iteration - slows things down
            'Label45.Text = u
        ElseIf MethodOfPayment = "Card" Then
            TotalCard += value
        End If
    Next
    'Update labels only once after the loop
    Label45.Text = TotalCash.ToString
    Label46.Text = TotalCard.ToString
End Sub

推荐阅读