简体   繁体   中英

How to add the Gridview cells using vb.net?

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 ?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM