我的网格视图包含列..price ...
Sno. Product price ($)
1 Pencil 1
2 Rubber 3
3 sharpner 2
我想计算价格列....意思是////我想计算GridView的Price列中的单元格.....
价格的结果将显示为1 + 3 + 2 = 6
答案 0 :(得分:0)
您可以使用Datatable的compute函数来计算总和:
Private Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.Footer Then
e.Row.Cells(2).Text = DirectCast(Me.GridView1.DataSource, DataTable).Compute("SUM(Price)", Nothing).ToString
End If
End Sub
这是我的Testdata:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
BindFooData()
End If
End Sub
Private Sub BindFooData()
Dim tblFoo As New DataTable("Foo")
tblFoo.Columns.Add(New DataColumn("ID", GetType(Int32)))
tblFoo.Columns.Add(New DataColumn("Product", GetType(String)))
tblFoo.Columns.Add(New DataColumn("Price", GetType(Double)))
Dim drProduct As DataRow = tblFoo.NewRow
drProduct("ID") = 1
drProduct("Product") = "Pencil"
drProduct("Price") = 1
tblFoo.Rows.Add(drProduct)
drProduct = tblFoo.NewRow
drProduct("ID") = 2
drProduct("Product") = "Rubber"
drProduct("Price") = 3
tblFoo.Rows.Add(drProduct)
drProduct = tblFoo.NewRow
drProduct("ID") = 3
drProduct("Product") = "sharpner"
drProduct("Price") = 2
tblFoo.Rows.Add(drProduct)
Me.GridView1.DataSource = tblFoo
Me.GridView1.AutoGenerateColumns = True
Me.GridView1.ShowFooter = True
Me.GridView1.DataBind()
End Sub
或者您可以手动计算:
Private AllPrices As New List(Of Double)
Private Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim price As Double = DirectCast(DirectCast(e.Row.DataItem, DataRowView)("Price"), Double)
AllPrices.Add(price)
ElseIf e.Row.RowType = DataControlRowType.Footer Then
Dim TotalPrice As Double
Dim TotalUnitPriceText As New System.Text.StringBuilder
For Each price As Double In AllPrices
TotalPrice += price
TotalUnitPriceText.Append(price).Append("+")
Next
If TotalUnitPriceText.Length <> 0 Then
TotalUnitPriceText.Length -= 1
TotalUnitPriceText.Append(" = ")
End If
e.Row.Cells(1).Text = TotalUnitPriceText.ToString
e.Row.Cells(2).Text = TotalPrice.ToString
End If
End Sub
最后但并非最不重要的是,您可以使用SUM的SQL查询来计算它。