我的Gridview有以下字段
ID Product Price ($)
1 Pencil 1
2 Pen 1
3 Rubber 2
我想计算Gridview Footer中价格字段的总价格...即..
总价= 4
如何使用VB.NET做到这一点?
答案 0 :(得分:0)
答案 1 :(得分:0)
使用dataTable的compute方法获取所有价格的总和并处理RowDataBound事件以设置页脚的文本:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
BindData()
End If
End Sub
Private Sub BindData()
Dim tbl As New DataTable
Dim col As New DataColumn("ID", GetType(Int32))
tbl.Columns.Add(col)
col = New DataColumn("Product", GetType(String))
tbl.Columns.Add(col)
col = New DataColumn("Price", GetType(Double))
tbl.Columns.Add(col)
Dim row As DataRow = tbl.NewRow
row("ID") = 1
row("Product") = "Pencil"
row("Price") = 1
tbl.Rows.Add(row)
row = tbl.NewRow
row("ID") = 1
row("Product") = "Pen"
row("Price") = 1
tbl.Rows.Add(row)
row = tbl.NewRow
row("ID") = 1
row("Product") = "Rubber"
row("Price") = 2
tbl.Rows.Add(row)
Me.GridView1.ShowFooter = True
Me.GridView1.DataSource = tbl
Me.GridView1.DataBind()
End Sub
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
Dim tbl As DataTable = DirectCast(GridView1.DataSource, DataTable)
Dim total As Double = DirectCast(tbl.Compute("SUM(Price)", Nothing), Double)
e.Row.Cells(2).Text = total.ToString
End If
End Sub
答案 2 :(得分:0)
Sub BindAmount()
Dim r As DataGridViewRow
If DataGridView1.RowCount > 0 Then
Dim TAmt As Decimal = 0.0
For Each r In DataGridView1.Rows
If r.Visible = True Then
TAmt = TAmt + r.Cells("PRICE").Value
TXT_PRICE.Text = TAmt
End If
Next
Else
TXT_PRICE.Text = 0
End If
End Sub
** LOAD ON KEYDOWN