vb.net - 如何在数据网格视图中按名称对单元格值求和?
问题描述
您好,我创建了一个表单,在其中放置了 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
解决方案
在线评论和解释
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
推荐阅读
- angular - 您如何在 ag-grid 模块中使用多个组件?
- c - 另一个 ListView 中的 ListView 没有组装正确的模板
- python - 没有弃用警告的 unicode_escape
- javascript - Chart.js - 如何更新数据
- python - Python:如何制作非阻塞while循环?
- instagram-api - 带有故事存档失败响应的 Instagram 私人 api 列表卷轴媒体查看器
- c++ - 将句子传递给c ++中的char数组
- python - 有没有办法自动创建新实例?
- python - 使用 Numpy 向量化三个嵌套循环
- node.js - 使用 Express 后处理 Sequelize finder