0

我在每次更新另一个 DataGrid 时更新 DataGrid 中的列的值求和。比如说,用户在 DataGrid1 中选择值,它将该数据添加到 DataGrid。那部分工作得很好。我需要对其中一列求和,这样它就可以给我一个总数。这是我想出的代码,它在 GridView1.SelectedIndexChanged 事件下触发。

        For Each GridViewRow In GridView2.Rows


            Sum = Convert.ToDouble(row.Cells(3).Text)
            Total = Sum + Total
            lblTotal.Text = Total.ToString

        Next

现在问题来自于此。如果我有 rwo 值,比如说...... 2.00,那么总和是可以的。它会给我 4。但是如果我添加另一个项目,比如 Item2,它的值为 2.30,它给我的总分是 4.60。如果我先添加 2.30 项,然后添加 2 项,它的值为 4。到底发生了什么,这么简单的数学怎么会出错:P!我错过了什么吗?四舍五入?需要解析一些东西吗?

完整的代码

 Protected Sub GridView1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles GridView1.SelectedIndexChanged


    Dim row = GridView1.SelectedRow
    If Not row Is Nothing AndAlso IsNumeric(row.Cells(3).Text) Then
        Dim Price As Double = CDbl(row.Cells(3).Text)
        Dim Name As String = CStr(row.Cells(2).Text)
        lblCart.Visible = True
        Dim InfoTotal As String = "$" & "    " & Precio & "      " & Nombre


        Dim Total As Double

        If GridView2.Rows.Count = 0 Then
            '  dt = New DataTable()
            dt.Columns.Add(New DataColumn("Name", GetType(System.String)))
            dt.Columns.Add(New DataColumn("Price", GetType(System.String)))
        Else
            dt = DirectCast(Session("DataTable"), DataTable)
        End If

        Dim Sum As Double
        Dim dr1 As DataRow = dt.NewRow()
        dr1(0) = Name.ToString
        dr1(1) = CDbl(Price.ToString)
        dt.Rows.Add(dr1)
        GridView2.DataSource = dt
        GridView2.DataBind()
        Session("DataTable") = dt

        For Each GridViewRow In GridView2.Rows
            Sum = CDbl(row.Cells(3).Text)
            Total += Sum
        Next

        lblTotal.Text = Total.ToString
        ListBox1.Items.Add(CStr(InfoTotal))

    End If


End Sub
4

2 回答 2

1

听起来您在其中添加了两次值的地方缺少一些额外的代码 - 请发布您的完整代码。下面用更少的代码完成了你正在做的事情——而且,在完成之前没有必要更新标签for

For Each GridViewRow In GridView2.Rows
                Sum = CDbl(row.Cells(3).Text)
                Total += Sum
            Next

lblTotal.Text = Total.ToString
于 2013-05-15T16:55:52.943 回答
0

代码很好......这很简单。我添加了一个会话并将行更改为列。该区域的代码:

 Dim Total As Double
    Dim Sum As Double
    Total = Session("Total")



    For Each GridViewRow In GridView2.Columns

        Sum = CDbl(row.Cells(3).Text)
        Total = CDbl(Total + Sum)
        Session("Total") = Total

    Next

    lblTotal.Text = Total.ToString
于 2013-05-15T20:05:57.473 回答