如何在数据网格视图中按名称对单元格值求和?

时间:2018-12-26 17:53:20

标签: vb.net

您好,我创建了一个表单,在其中放置了datagridview和两个名称为cash和card的文本框。我想分别对现金和卡值进行求和并在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

2 个答案:

答案 0 :(得分:0)

在线评论和解释

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

答案 1 :(得分:0)

如果您了解使用lambda,可以考虑以下选择,否则Mary's将为您工作。

在尝试下面的代码之前,请务必阅读所有注释,以便您有所了解,而不仅仅是尝试代码,从而可以从介绍的内容中学习。

在Visual Studio 2017中编写

Imports System.Data.SqlClient
''' <summary>
''' Assumes cell 1 data is numeric
''' One DataGridView, two columns
''' 0 - PaymentTypeColumn
''' 1 - AmountColumn
''' Two TextBox controls
''' One Button
''' </summary>
Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        DataGridView2.Rows.Add("CASH", 200.5)
        DataGridView2.Rows.Add("CARD", 200.5)
        DataGridView2.Rows.Add("CASH", Nothing)
        DataGridView2.Rows.Add("CARD", 10.25)
        DataGridView2.Rows.Add("CASH", 25.0)
    End Sub
    ''' <summary>
    ''' Use Lambda to get values then sum them.
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim cash = DataGridView2.
                Rows.
                Cast(Of DataGridViewRow).
                Where(Function(row) CStr(row.Cells("PaymentTypeColumn").Value) = "CASH").
                Select(Function(row) CDbl(row.Cells("AmountColumn").Value)).
                Sum()


        Dim card = DataGridView2.
                Rows.
                Cast(Of DataGridViewRow).
                Where(Function(row) CStr(row.Cells("PaymentTypeColumn").Value) = "CARD").
                Select(Function(row) CDbl(row.Cells("AmountColumn").Value)).
                Sum()


        cashTextBox.Text = cash.ToString("c2")
        cardTextBox.Text = card.ToString("c2")

        '
        ' Get AddNewRecord method ready to use before un-commenting code
        '
        'Dim ops As New DataOperations
        'Dim id = ops.AddNewRecord(cash, card)

    End Sub
    ''' <summary>
    ''' Alternate if unsure all cells values in AmountColumn column are numeric,
    ''' do a TryParse.
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim cash = DataGridView2.
                Rows.
                Cast(Of DataGridViewRow).
                Where(Function(row) CStr(row.Cells("PaymentTypeColumn").Value) = "CASH").
                Select(Function(row)
                           Dim value As Double = 0
                           Double.TryParse(CStr(row.Cells("AmountColumn").Value), value)
                           Return value
                       End Function).
                Sum()
        cashTextBox.Text = cash.ToString("c2")
    End Sub
End Class
''' <summary>
''' Keep here or place in in a separate class file
''' </summary>
Public Class DataOperations
    Private ConnectionString As String = "TODO"
    ''' <summary>
    ''' Returns new primary key (optional), you have a primary key though.
    ''' </summary>
    ''' <param name="cash">cash amount</param>
    ''' <param name="card">card amount</param>
    ''' <returns>new primary key</returns>
    ''' <remarks>
    '''  - highly advisable to wrap the open operation and
    '''    Execute method in a try/catch and deal with any runtime errors
    '''    back in the UI
    ''' </remarks>
    Public Function AddNewRecord(cash As Double, card As Double) As Integer
        Dim newPrimaryKey As Integer = 0

        Dim insertStatement As String = "INSERT INTO SomeTable (Cash,Card) VALUES (@Cash,@Card);" &
                                        "SELECT CAST(scope_identity() AS int);"

        Using cn = New SqlConnection() With {.ConnectionString = ConnectionString}
            Using cmd = New SqlCommand() With {.Connection = cn, .CommandText = insertStatement}
                cmd.Parameters.AddWithValue("@Cash", cash)
                cmd.Parameters.AddWithValue("@Card", card)
                cn.Open()
                newPrimaryKey = Convert.ToInt32(cmd.ExecuteScalar())
            End Using
        End Using
        Return newPrimaryKey
    End Function
End Class