How to add the Gridview cells using vb.net?

折月煮酒 提交于 2019-12-24 19:07:35

问题


My Gridview has following Fields

ID          Product            Price ($)
1           Pencil             1
2           Pen                1
3           Rubber             2

I want to calculate the total price of price fields in Gridview Footer ...ie..

Total Price = 4

How to do it using VB.NET ?


回答1:


Look at this msdn article GridView Examples for ASP.NET 2.0: Displaying Summary Data in the Footer




回答2:


Use compute method of dataTable to get the sum of all your prices and handle the RowDataBound-event to set the Footer's text:

 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



回答3:


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



来源:https://stackoverflow.com/questions/4804788/how-to-add-the-gridview-cells-using-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!