我在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
现在问题来自于此。如果我有两个值,比如... 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
答案 0 :(得分:1)
听起来你错过了一些额外的代码,你在那里添加两次值 - 请发布你的完整代码。下面的代码完成了你正在做的事情(从而稍微减少) - 同样,在for
完成之前,没有必要更新标签。
For Each GridViewRow In GridView2.Rows
Sum = CDbl(row.Cells(3).Text)
Total += Sum
Next
lblTotal.Text = Total.ToString
答案 1 :(得分:0)
代码很好......这很简单。我添加了一个会话并将Rows更改为Column。该领域的代码:
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