我在每次更新另一个 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